django and handling form validation errors

1,074 views
Skip to first unread message

reduxdj

unread,
Jul 13, 2010, 7:22:28 PM7/13/10
to Django users
HI,

(sorry for this re-post, my original post isn't here??, so I replaced
it, and I have been checking up all day as I hope to find the
solution)

Forgive me, here's another n00b doozie. I've created a form, which
extends form, however, my form is not validating and I can't get the
form to print errors next to my form fields. What's curious, at the
form.is_valid()
in all the examples, I don't see an else: clause. Which leads me to
believe that a validation error should be
raised at this point, so an else is not neccessary??

So, my form should hold clean_fieldname methods for each field name
correct? and if an error is raised,
automagically, django handles the error messages, as long as it's
defined in my template, correct or not?
So every property needs a clean method?

Sorry, I've read the resources and I'm a little unclear on this?

Thanks for your time,
Django and the community rocks

from my views:

def listing(request):
if request.method == 'POST': # If the form has been submitted...
new_listing = Listing()
form = ListingForm(data=request.POST,instance=new_listing)
#form.save()
if form.is_valid(): # All validation rules pass
form.save()
return HttpResponseRedirect('/listing/') # Redirect after
#else:
#return HttpResponseRedirect('/listing/') # Redirect after
#return HttpResponse('form is a failure, like you.')
#return HttpResponseRedirect('/create/') # Redirect after
else:
form = ListingForm() # An unbound form
return render_to_response('listing.html', {
'form': form,
})


listing.html template

{% extends "base.html" %}
{% block content %}
<div id="content-main">
<form action="/create/" method="post">
{% include "form_snippet.html" %}
<input type="submit" value="Submit" />
</form>
{% endblock %}
so apparently that should work



form_snippet.html template

% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}


Daniel Roseman

unread,
Jul 14, 2010, 3:54:25 AM7/14/10
to Django users
What's happened is that you have indented the final line too much. It
should line up with the main function content - ie on the same level
as the 'else' above it, it shouldn't actually come under that else.

That means that if the form is a post, but doesn't validate, the flow
falls from if form.is_valid() straight down to that return - and so
the form that was instantiated by passing in request.POST is passed
back to the template, and rendered along with its errors. This is why
you don't need that commented-out else block.
--
DR.
Reply all
Reply to author
Forward
0 new messages