revy revy - 3 months ago 15
Python Question

Showing default required message after customizing template

guys. I'm learning to use Django and I'm facing some issues:
I created some required field forms, made some changes in the template because and the default required message no longer is shown when the field is left empty.

Here is my code in forms.py:

class CreateProjectForm(forms.Form):
project_name = forms.CharField(required=True)
project_description = forms.CharField(widget=forms.Textarea(attrs={'style':'resize:none;'}), required=True)
project_expiration = forms.CharField(required=False)

def __init__(self, *args, **kwargs):
super(CreateProjectForm, self).__init__(*args, **kwargs)
self.fields['project_name'].label = "Project Name:"
self.fields['project_description'].label = "Project Description:"
self.fields['project_expiration'].label = "Expiration Date:"

for name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'


And here is my code in the template:

<form class="form-horizontal" role="form" action="" method="post">
{% csrf_token %}
{% for field in form %}

<div class="form-group">
<div class="col-sm-4">
<label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label>
</div>

<div class="col-sm-8">
{{field}}
</div>
</div>
{% endfor %}


<button type="submit" class="btn btn-primary">Create Project</button>
</form>


I can't understand why if I don't do the for loop in the template everything works, but if I try to iterate over the form it stops showing the messages.

Thanks!

Answer

If you loop over the form's fields in the template, then you need to include the errors manually with {{ field.errors }}.

<form class="form-horizontal" role="form" action="" method="post">
    {% csrf_token %}
    {% for field in form %}

    <div class="form-group">
        {{ field.errors }}
        <div class="col-sm-4">
            <label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label>
        </div>

        <div class="col-sm-8">
            {{field}}
        </div>
     </div>
    {% endfor %}


    <button type="submit" class="btn btn-primary">Create Project</button>
</form>

You might find the docs on rendering form error messages useful as well.

Comments