开发者

Parsing error message to Django template?

I am a newbie in Django. I am wr开发者_如何学Goiting a sample application that has a form, submit that form then saving the data into the database. My form need to be validated before allowing to save data. So my question is how can I pass the error messages (that generated by validation) to the view? Any suggestion are welcome. Thanks!


Are you using a Form instance? Then you can render the form in the template and the error messages with automagically show up. For instance:

# views.py
def my_view(request, *args, **kwargs):
    if request.method == 'POST':
        form = MyForm(request.POST.copy())
        if form.is_valid():
            # Save to db etc.
    elif request.methof == 'GET':
        form = MyForm()

    return render_to_response(..., {'form' : form})

And in the template:

{{ form.as_p }}

You will note that if the form is not vald (is_valid() returns False) then the view will proceed to return the form (with errors) to the template. The errors then get rendered in the template when form.as_p is called.

** Update **

As @Daniel said:

Even if you're not using form.as_p, you can get the errors for the whole form with form.errors and for each field with form.fieldname.errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜