Best way to trap IntegrityError in Django form?

822 views
Skip to first unread message

ldm999

unread,
Mar 8, 2009, 11:39:49 AM3/8/09
to Django users
I have a form tied to a List model where User and Name are
unique_together.

What's the best way to trap the IntegrityError if someone tries to
create a new List with a User/Name combo that already exists?

I know I could allow Django forms to do it if I include User in the
form, but obviously I need User to be hidden and defaulted to the
current user.

TIA.

Adam Jenkins

unread,
Mar 8, 2009, 6:15:57 PM3/8/09
to django...@googlegroups.com
You can override the clean method on the for and have it raise the appropriate error for you. I've done the same thing before and came across the issue that the form doesn't know the current user. I ended up adding a user parameter to the init and passing it when I instantiated the form. Then I made my clean_fieldname() method and checked for the record and raised ValidationError if it existed.

You can find the docs at http://docs.djangoproject.com/en/dev/ref/forms/validation/

ldm616

unread,
Mar 15, 2009, 12:48:35 PM3/15/09
to Django users
In the end I just did it in the view. Checked for the duplicate before
saving, and sent an error message back to the form if the dupe test
fails. Looks like this. And downside to this approach?

def add_fablist(request):
#
--------------------------------------------------------------------------------------
fablists = FabList.objects.filter(user=request.user) # Get
fablists for left column
duplicate = False

if request.method == 'POST':
form = FabListForm(data=request.POST)
if form.is_valid():
fablist = form.save(commit=False)
if not FabList.objects.filter(user=request.user,
name=fablist.name): # Check for dupe user/list name combo
fablist.user = request.user
fablist.slug = defaultfilters.slugify(fablist.name) #
Slugify list name
fablist = form.save()
return HttpResponseRedirect('/')
else:
duplicate = True
else:
form = FabListForm()
return render_to_response('fablist_form.html',
{ 'form' : form,
'fablists' : fablists,
'ADD_FABLIST' : True,
'DUPLICATE' : duplicate
}, context_instance=RequestContext
(request))

On Mar 8, 3:15 pm, Adam Jenkins <emperorce...@gmail.com> wrote:
> You can override the clean method on the for and have it raise the
> appropriate error for you. I've done the same thing before and came across
> the issue that the form doesn't know the current user. I ended up adding a
> user parameter to the init and passing it when I instantiated the form. Then
> I made my clean_fieldname() method and checked for the record and raised
> ValidationError if it existed.
>
> You can find the docs athttp://docs.djangoproject.com/en/dev/ref/forms/validation/
Reply all
Reply to author
Forward
0 new messages