人。我正在学习使用Django而我正面临一些问题: 我创建了一些必需的字段表单,在模板中进行了一些更改,因为当字段为空时,不再显示默认的必需消息。
这是我在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'
这是模板中的代码:
<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>
我无法理解为什么如果我不在模板中执行for循环,一切正常,但如果我尝试迭代表单,它就会停止显示消息。
谢谢!
答案 0 :(得分:0)
如果您loop over the form's fields in the template,则需要使用{{ 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>
您可能会发现rendering form error messages上的文档也很有用。