I am building a django app for which one component is simple CRUD for some models. I have created add, edit, delete, view details and listing pages. I have given the buttons to edit and delete records on listing page as well as view details page. Since the edit buttons from listing page and inner details page use same views and templates, the success url can either link back to view details page or listing page. I would like to add code so that if user goes to edit page from view details then is redirect back to details page on success, but if the user goes to edit page from listing page then the user is redirected to listing page (also listing page has pagination so user should go back to page s/he was on.
Asked
Active
Viewed 3,003 times
1 Answers
7
One way to do this would be to store the url that the user came from in their session and then redirect them back to the url on success. This mixin could be added to your views
class RedirectToPreviousMixin:
default_redirect = '/'
def get(self, request, *args, **kwargs):
request.session['previous_page'] = request.META.get('HTTP_REFERER', self.default_redirect)
return super().get(request, *args, **kwargs)
def get_success_url(self):
return self.request.session['previous_page']
Then you can just subclass this mixin in your class based views
class MyModelUpdateView(RedirectToPreviousMixin, UpdateView):
model = MyModel

Iain Shelvington
- 31,030
- 3
- 31
- 50