Steve
Steve

Reputation: 1192

Django - redirect to a view after edit

I have a view that allows me to edit/update a post. The post is the result of filling out a form. This is similar I'm guessing to redirecting to a CMS post after editing. Here's the post view:

class PostUpdateView(UpdateView):
   model = Product
   form_class = ProductForm
   template_name = 'edit_product.html'

   def form_valid(self, form):
      self.object = form.save(commit=False)
      self.object.save()
      return redirect ('products')

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
     return super(PostUpdateView, self).dispatch(request, *args, **kwargs)

After updating the details in the form it redirects to the 'product' page, whereas I want to redirect to the item just edited. The URL for the items is:

url(r'^([0-9]+)/$', views.detail, name = 'detail'),

Each post is then a number in the url, such as http://127.0.0.1:8000/13/. I can redirect to the previous page, but takes me back to the edit view, whereas, I want to go back to the actual post view, showing the edit. Hopefully this isn't clear as mud.

I get the sense I need to grap the orginating url, then use it once the form is updated so I'm researching that right now. Any guidance gratefully received.

Upvotes: 0

Views: 1814

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

It redirects to the products page because that is what you explicitly told it to do in form_valid. If you want to redirect to the detail page, then do that:

return redirect('detail', self.object.pk)

Upvotes: 2

Related Questions