Reputation: 15834
Need to clear a basic concept. In Django, what's the harm in redirecting to a view from form_valid()
itself, instead of declaring a get_success_url()
?
I.e. why is the following inferior, compared to what's below it:
class PostCreateView(CreateView):
model = Post
def form_valid(self, form):
# do something
return redirect("home")
class PostCreateView(CreateView):
model = Post
def form_valid(self, form):
# do something
return super(CreateView, self).form_valid(form)
def get_success_url(self):
return reverse("home")
Upvotes: 1
Views: 633
Reputation: 308999
Returning redirect
isn't necessarily inferior. If you don't call super, then you need to save the form yourself. Duplicating two lines (save and return redirect) isn't really a problem. If super
was more complicated then the duplication would be more of an issue, as there's a bigger chance of functionality being left out or errors being introduced.
On the plus side, returning the redirect response makes it obvious what form_valid
will do, without having to look at what super
does. Having control over how the form is saved can be useful too.
If your view might be subclassed, then you probably shouldn't return redirect, because you'll break any subclasses that override get_success_url.
Upvotes: 1