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)
0 comments
Reply