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.

Raw
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)

0 comments

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo