views:

31

answers:

1

Hello, I am a newbie in Django. I am writing 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!

+3  A: 

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.

Manoj Govindan
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`.
Daniel Roseman
@Daniel: correct. Will update my answer. Thanks.
Manoj Govindan