Reputation: 11330
I'm trying to display individual fields of the Django form one by one as I want to change certain properties.
This is my forms.py. I've reduced it to just one field for clarity.
from django import forms
class NameForm(forms.Form):
name = forms.CharField(max_length=100)
It works perfectly if I render the form completely. My HTML code -
<form style="text-align:center; padding-bottom: 2%" action="/contact/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
</form>
The page source for the above code comes like this -
<p><label for="id_name">Name:</label> <input id="id_name" maxlength="100" name="name" type="text" /></p>
The problem comes when I try to render individual field like using {{ form.name }}
instead of {{form}}
. The page source for this shows empty. No HTML is formed.
I also tried -
{% for field in form %}
<div class="fieldWrapper">
{{ field }}
</div>
{% endfor %}
And the HTML rendered for this is like -
<div class="fieldWrapper">
<
</div>
<div class="fieldWrapper">
p
</div>
<div class="fieldWrapper">
>
</div>
<div class="fieldWrapper">
<
</div>
<div class="fieldWrapper">
l
</div>
<div class="fieldWrapper">
a
</div>
<div class="fieldWrapper">
b
</div>
<div class="fieldWrapper">
e
</div>
<div class="fieldWrapper">
l
</div>
<div class="fieldWrapper">
</div>
<div class="fieldWrapper">
f
</div>
<div class="fieldWrapper">
o
</div>
<div class="fieldWrapper">
r
</div>
<div class="fieldWrapper">
I haven't posted the full HTML source but seems like the loop is printing each character of the HTML code rendered from the form as if we combine the first few characters printed it forms HTML like -
<p><label for>
and so on...
Please explain why this is happening.
Upvotes: 0
Views: 926
Reputation: 135
Please check what are you returning from your view. This might happen if your view is returning the form.as_p. This can be corrected by returning the form only. It should work! If it still doesnt work, post views and entire template.
Upvotes: 1
Reputation: 13
If you know the name of the field, you can render it individually like that :
<div class="fieldWrapper">
{{ form.myfield.errors }}
<label for="{{ form.myfield.id_for_label }}">Label for myfield : </label>
{{ form.myfield }}
</div>
(you can also use {{ form.myfield.label_tag }} for the label if you defined it in the Form class)
Else, if you want to have a for you can do it like that :
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
It works well for me. If you still have a issue, it must be in the rest of your code I think. Show the enter template if so :)
Upvotes: 0