django form fields are not showing up in template - why?

点点圈 提交于 2021-02-08 04:41:13

问题


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})

this is my form. defined in forms.py and imported into views.py

class AddBook(forms.Form):
   titel = forms.TextInput()
   author = forms.TextInput()

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?


回答1:


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: 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/



来源:https://stackoverflow.com/questions/19474696/django-form-fields-are-not-showing-up-in-template-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!