Sativa
Sativa

Reputation: 358

Django multiple success urls

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

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

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>

Upvotes: 3

Views: 1210

Answers (1)

Alasdair
Alasdair

Reputation: 309009

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.

Upvotes: 7

Related Questions