Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect / return to same (previous) page in Django?

What are the options when you want to return the user to the same page in Django and what are the pros/cons of each?

Methods I know:

  • HTTP_REFERER
  • GET parameter containing the previous URL
  • Session data to store the previous URL

Are there any other?

like image 645
Al Bundy Avatar asked Oct 06 '12 10:10

Al Bundy


People also ask

How do I return to the same page in Django?

Use return redirect(request. META['HTTP_REFERER']) to redirect to previous url.

How do I redirect on the same view?

One can use the anchor tag to redirect to a particular section on the same page. You need to add ” id attribute” to the section you want to show and use the same id in href attribute with “#” in the anchor tag.

How do I redirect one page to another in Django?

In Django, redirection is accomplished using the 'redirect' method. The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name. In the above example, first we imported redirect from django.

How can I get previous URL in Django?

You can do that by using request. META['HTTP_REFERER'] , but it will exist if only your tab previous page was from your website, else there will be no HTTP_REFERER in META dict . So be careful and make sure that you are using . get() notation instead.


2 Answers

One of the way is using HTTP_REFERER header like as below:

from django.http import HttpResponseRedirect  def someview(request):    ...    return HttpResponseRedirect(request.META.get('HTTP_REFERER')) 

Not sure of cons of this!

like image 126
Rohan Avatar answered Dec 09 '22 11:12

Rohan


While the question and answer is old, I think it's lacking a few options. I have not find any cons with the methods, I would be happy to know if there are any?

  • request.path_info
  • request.get_full_path()
  • request.build_absolute_uri()

    from django.shortcuts import redirect  redirect(request.path_info) # No query parameters  redirect(request.build_absolute_uri()) # Keeps query parameters  redirect(request.get_full_path()) # Keeps query parameters 
like image 30
Daniel Backman Avatar answered Dec 09 '22 11:12

Daniel Backman