42

How can I set success_url based on a parameter?
I really want to go back to where I came from, not some static place. In pseudo code:

url(r'^entry/(?P<pk>\d+)/edit/(?P<category>\d+)',
    UpdateView.as_view(model=Entry, 
                       template_name='generic_form_popup.html',
                       success_url='/category/%(category)')),

Which would mean: edit entry pk and then return to 'category'. Here an entry can be part of multiple categories.

5 Answers 5

69

Create a class MyUpdateView inheritted from UpdateView and override get_success_url method:

class MyUpdateView(UpdateView):
    def get_success_url(self):
        pass #return the appropriate success url

Also i like to pass such parameters like template_name and model inside of inheritted class view, but not in .as_view() in urls.py

1
  • This way get_success_url will point to a url like /items/1/None which does not exist. Feb 18, 2021 at 8:59
36

Had the same issue. Was able to get the paramater from self.kwargs as Dima mentioned:

def get_success_url(self):
        if 'slug' in self.kwargs:
            slug = self.kwargs['slug']
        else:
            slug = 'demo'
        return reverse('app_upload', kwargs={'pk': self._id, 'slug': slug})
4
  • This was useful for me - though I needed to make sure that the slug started with "/", otherwise I was getting urls like "/formpage/successurl/successurl/successurl/" that kept adding to the end, instead of the beginning. Jan 21, 2014 at 15:34
  • @JayCrossler - I think that is due to relative addresses versus absolute addresses. The leading slash implies that the url starts there. Without a slash, it gets appended to the previous url, Like unix paths with the ls command. Aug 31, 2014 at 13:13
  • 2
    Could further simplify using .get(): slug = self.kwargs.get('slug', 'demo')
    – MDB
    Sep 6, 2016 at 17:37
  • 1
    I'm in Django 2.2.5 - 'pk': self._id need to change into 'pk': self.object.id
    – C.K.
    Sep 30, 2019 at 2:36
8

I found a way which is useful and very simple. Check it out.

class EmployerUpdateView(UpdateView):
        model = Employer
        #other stuff.... to be specified

        def get_success_url(self):
           pk = self.kwargs["pk"]
           return reverse("view-employer", kwargs={"pk": pk})

    
4
  • Could you explain what view-employer is in this context? Feb 18, 2021 at 9:07
  • 1
    view-empployer is the name of the EmployerDetailView in urlpatterns list. Like so path("view-employer/<pk>/", EmployerDetailView.as_view(), name="view-employer")
    – chaulap
    Feb 18, 2021 at 9:46
  • Thanks. Unfortunately, it still produces and error: "Reverse for 'view-employer' not found. 'view-employer' is not a valid view function or pattern name. I just opened a question with my particular issue: stackoverflow.com/questions/66262282/… Feb 18, 2021 at 14:49
  • Ok I will take a look at it.
    – chaulap
    Feb 18, 2021 at 21:49
4

Define get_absolute_url(self) on your model. Example

class Poll(models.Model):
    question = models.CharField(max_length=100)
    slug = models.SlugField(max_length=50)
    # etc ...

    def get_absolute_url(self):
        return reverse('poll', args=[self.slug])

If your PollUpdateView(UpdateView) loads an instance of that model as object, it will by default look for a get_absolute_url() method to figure out where to redirect to after the POST. Then

url(r'^polls/(?P<slug>\w+)/, UpdateView.as_view(
    model=Poll, template_name='generic_form_popup.html'),

should do.

1
  • And in case of a CreateView, since the instance does not exist yet, just create a form_valid function like: def form_valid(self, form): obj = form.save(commit=False) obj.profile_id = self.request.user.id obj.save() self.success_url = self.model.get_absolute_url(obj)
    – openHBP
    Feb 28, 2019 at 16:10
0

Why don't you add a 'next' parameter to your form (template) and catch it in your view. It's common practice to achieve redirecting this way.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.