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 withform.errors
and for each field withform.fieldname.errors
.
Manoj Govindan
2010-09-14 05:45:47
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
2010-09-14 08:31:40
@Daniel: correct. Will update my answer. Thanks.
Manoj Govindan
2010-09-14 09:23:30