2016-08-15 132 views
0

Django newb在这里,但我在学习。Django表单,用户输入字段不在模板中呈现

问题陈述

输入字段在HTML模板不渲染。

输出在浏览器中

|提交按钮|

相关代码

forms.py 
from django import forms 
from django.db import models 

class PostNotes(forms.Form): 
    clientid = models.IntegerField() 
    notetext = models.CharField(max_length=1000) 

-

views.py 
def post_form_notes(request): 
    if request.method == 'GET': 
     sawit = True 
     form = PostNotes(initial={'notetext':'This is a sample note'}) 
    else: 
     sawit = False 
     pass 
    return render(request, 'clientadmin/post_form_notes.html', { 
     'form': form, 
     'sawit': sawit, 
    }) 

-

post_form_notes.html 
{{ sawit }} 
<form action="" method="post">{% csrf_token %} 
    {{ form.as_p }} 
    <input type="submit" value="Submit" /> 
</form> 

故障已经完成

  • 我已经从浏览器中退出了相当数量的代码(具体而言,如果我看到 POST)请求。不用找了。
  • 我还包括一个变量,以确保我看到GET请求以及模板变量正在工作。我得到True的输出。
  • 尽可能简化Form类。
+0

马特,感谢您的回复,并且我认为您所发生的事情是正确的。我创建一个对象并将其传递给模板。我相信,as_p过滤器应该将其转换为来自对象的代表性对象。但是,由于它不起作用,我当然不确定这是否正确。遵循(或多或少)这个例子。 http://pythoncentral.io/how-to-use-python-django-forms/ – PerryDaPlatypus

回答

0

我修改了forms.py以使用我已经拥有的DB​​模型。

forms.py:

from django.forms import ModelForm 
from clientadmin.models import notes 

class PostNotes(ModelForm): 
    class Meta: 
     model = notes 
     fields = ['notedate', 'notetext'] 

我还修改了views.py不设置初始值,所以该函数使用,而不是什么提出以下。

models.py:

def post_form_notes(request): 
    if request.method == 'GET': 
     form = PostNotes() 
    else: 
     pass 
    return render(request, 'clientadmin/post_form_notes.html', { 
     'form': form, 
    }) 

希望这有助于这是有同样的问题我是......

参考以下网址了解更多信息的人:https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

相关问题