Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

success_url in UpdateView, based on passed value

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.

like image 316
Bryce Avatar asked Jun 14 '12 06:06

Bryce


Video Answer


4 Answers

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

like image 105
Dima Bildin Avatar answered Oct 14 '22 01:10

Dima Bildin


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})
like image 31
Aleck Landgraf Avatar answered Oct 14 '22 02:10

Aleck Landgraf


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

    
like image 29
chaulap Avatar answered Oct 14 '22 03:10

chaulap


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.

like image 31
C14L Avatar answered Oct 14 '22 03:10

C14L