Django表单字段未显示在模板中-为什么? [英] django form fields are not showing up in template - why?
问题描述
文档说,要在模板中显示表单字段,我需要这样做:
The Docs says, to display the form fields in template, i need to do this:
<form action="/search_for_book/">{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Suchen" />
</form>
我做到了.这是我的看法.
i did this. and this is my views.
def addbook(request):
form = AddBook()
return render(request,'searchbook.html',{'form':form})
这是我的表格.在forms.py中定义并导入到views.py
this is my form. defined in forms.py and imported into views.py
class AddBook(forms.Form):
titel = forms.TextInput()
author = forms.TextInput()
为什么表单字段没有显示在模板中?我几乎从文档中复制了1:1.模板仅显示按钮追求n
,没有其他内容.Docs没有谈论Urlconf,我也必须这样做吗?
why dont Form fields show up in template? I did almost the 1:1 copy from docs. Template shows only the button Suchen
and nothing else. Docs doesnot say anything about Urlconf, do i have to do also?
推荐答案
之所以这样,是因为您要定义一个小部件,而该小部件只是HTML输入元素的一种表示形式,而不是在forms.py中定义一个字段.
请执行以下操作:
The reason why is that you're defining a widget, which is merely a representation of a HTML input element, instead of defining a field in your forms.py
Do the following:
class AddBook(forms.Form):
titel = forms.CharField(widget=forms.TextInput())
author = forms.CharField(widget=forms.TextInput())
PS:不要怪Django的文档-它们真的很棒!
有关小部件的参考,请在此处阅读: https://docs.djangoproject.com/en/dev/ref/forms/widgets/
有关字段的参考,请在此处阅读: https://docs.djangoproject.com/en/dev/ref/forms/fields/
PS: don't blame django's docs - they are really excellent!
For the referencce on widgets, read here: https://docs.djangoproject.com/en/dev/ref/forms/widgets/
For the reference on fields, read here: https://docs.djangoproject.com/en/dev/ref/forms/fields/
这篇关于Django表单字段未显示在模板中-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!