有没有比下面显示的技术更好、更“Django-istic”的方法来按特定顺序放置 Django 表单错误消息?我有一个包含十个字段的表单。如果用户未填写必填字段或输入无效数据,我将通过显示红色“x”和错误消息来遍历表单的错误字段,这些字段已放入自定义错误列表中以下无效字段旁边的顶部和红色“x”:
{# template.html #}
<form method="post" action=".">
{% csrf_token %}
{# Non-field errors removed for clarity #}
{# Iterate through error messages in custom ordered error list #}
{% for error_message in ordered_error_list %}
<img src='/static/img/red_x.png' alt='Error'></img>
{{ error_message }}<br>
{% endfor %}
<br>
{% for field in form.visible_fields %}
<div>
{{ field.label_tag }}<br />
{{ field }}
{% if field.errors %}
<img src='/static/img/red_x.png' alt='Error'></img>
{% endif %}
</div>
{% endfor %}
{# Hidden fields removed for clarity #}
<p><input type="submit" value="Continue" /></p>
</form>
这是我的视图和辅助功能:
# views.py
def create_member_profile(request):
if request.method == "POST":
form = CreateMemberProfileForm(request.POST)
if form.is_valid():
# Process form data and redirect to next page...
return HttpResponseRedirect(reverse('review-member-profile'))
# Before I re-POST the form and display the errors, I'll put the errors in order
else:
ordered_error_list = put_member_profile_errors_in_order(form)
else:
form = CreateMemberProfileForm()
return render_to_response(template, locals(), context_instance=RequestContext(request))
def put_member_profile_errors_in_order(form):
errors_in_order = [] # List
for error in form['field_1'].errors:
errors_in_order.append(error)
for error in form['field_2'].errors:
errors_in_order.append(error)
for error in form['field_3'].errors:
errors_in_order.append(error)
# ...
for error in form['field_10'].errors:
errors_in_order.append(error)
return errors_in_order
这一切看起来很有必要的原因是 form.errors 是一个字典,而 Python 字典,根据定义,是无序的。但是,正如我所说,我希望顶部的任何错误消息都以与它们引用的表单字段相同的顺序显示。我找不到任何允许我重新排序表单错误的 form.errors 属性。我不喜欢“for error in form[]”块,但如果我想从每个错误的开头剥离 HTML 标记,它们似乎是必需的。另请注意,我不是通过将每个“for”循环放在“if form['field'].errors”块中来检查错误,因为省略它并没有什么不同,我希望这段代码运行得尽可能快可能的。
有一个更好的方法吗?谢谢!