简体   繁体   中英

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

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM