success_url in UpdateView, based on passed value

安稳与你 提交于 2019-11-30 10:57:00

问题


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.


回答1:


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




回答2:


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



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/11027996/success-url-in-updateview-based-on-passed-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!