Django表单:如果无效,显示带有错误消息的表单 [英] Django Forms: if not valid, show form with error message

查看:326
本文介绍了Django表单:如果无效,显示带有错误消息的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我Django表单,它可以检查表单是否有效:

I Django forms, it can check whether the form is valid:

if form.is_valid(): 
    return HttpResponseRedirect('/thanks/')

但是,如果它是没有效如何返回带有错误消息的表单?我没有在任何示例中看到else。

But I'm missing what to do if it isn't valid? How do I return the form with the error messages? I'm not seeing the "else" in any of the examples.

推荐答案

如果在窗体中呈现相同的视图在模板中无效,您可以使用 form.errors 访问表单错误。

If you render the same view when the form is not valid then in template you can access the form errors using form.errors.

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

def myView(request):
    form = myForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    return render_to_response('my_template.html', {'form': form})

这篇关于Django表单:如果无效,显示带有错误消息的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆