Django multiple success urls

时间:2015-06-30 13:52:52

标签: python django django-views django-1.8

How can I set multiple success urls using kwargs or something else?

I want, depending on what button clicked a different success URL.

  • Save = Go to a DetailView

  • save&continue = Stay in this UpgradeView

  • save&createNew = Go to a CreateView

It should be working later exactly like in the Django admin

I have this UpdateView:

class TopicEditView(UpdateView):
    fields = ['title','description',]
    model = Topic

    def post(self, request, *args, **kwargs):
        data = request.POST.copy()
        if data.get('save', False):
            pass
        elif data.get('save_and_continue', False):
            pass
        ...
        return UpdateView.post(self, request, *args, **kwargs)

    def get_success_url(self):
        return reverse('topic_detail', kwargs={'pk':self.object.pk})

And this simple template:

<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Speichern" name="save"/>
    <input type="submit" value="Speichern & weiter" 
        name="save_and_continue"/>
</form>

1 个答案:

答案 0 :(得分:2)

In your get_success_url method, check for the value of the submit button in self.request.POST, and return the appropriate url:

def get_success_url(self):
    if self.request.POST.get('save'):
        return reverse('success_url_for_save')
    elif self.request.POST.get('save_and_continue'):
        return reverse('success_url_for_save_and_continue', kwargs={'pk':self.object.pk})
    else:
        return reverse('fallback_success_url')

Checking the values in the post method shouldn't be necessary.