Django redirect on duplicate object creation

So I had this project with a peculiar requirement: It had to do a redirect to an existing object when the CreateView failed because such an object already existed in the db.

Not really hard to do but it took me a while to figure out.. so here's the code.

class ExampleCreateView(CreateView):
    def form_invalid(self, form):
        try:  
            obj = Example.objects.get(foo=form.instance.foo)
            url = obj.get_absolute_url()
            return HttpResponseRedirect(url)
        except ObjectDoesNotExist:
           pass  
        return super(ExampleCreateView, self).form_invalid(form)

Published on April 4, 2012 at 3:53 p.m. by Nicolas and tagged Django. You can follow the discussion with the comment feed for this post. Feeling generous? Donate!

0 comments

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.