Django: getting previous url
Solution 1
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.
# Returns None if user came from another website
request.META.get('HTTP_REFERER')
Note: I gave this answer when Django 1.10 was an actual release. I'm not working with Django anymore, so I can't tell if this applies to Django 2
Solution 2
You can get the referring URL by using request.META.HTTP_REFERER
More info here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META
Solution 3
I can't answer @tryingtolearn comment, but for future people, you can use request.META['HTTP_REFERER']
Solution 4
Instead of adding it to your context, then passing it to the template, you can place it in your template directly with:
<a href="{{ request.META.HTTP_REFERER }}">Return</a>
Solution 5
A much more reliable method would be to explicitly pass the category in the URL of the Add Post button.
Related videos on Youtube
tryingtolearn
Updated on October 30, 2020Comments
-
tryingtolearn over 3 years
I have a Post model that requires a certain category before being added to the database, and I want the category to be generated automatically. Clicking the addPost button takes you to a different page and so the category will be determined by taking a part of the previous page url.
Is there a way to get the previous page url as a string?
Thanks
Edit: I have added my AddPost button here.
<aside class="addPost"> <article> <form action="/Forum/addPost"> <input type="submit" name="submit" value="Add Post"/> </form> </article> </aside>
-
tryingtolearn over 9 yearsI'm sorry, could you elaborate? I'm a definite newbie to this.
-
tryingtolearn over 9 yearsApologies, I don't quite follow how that works. Could you explain? If I was able to retrieve the URL this way would it allow me to treat it as type string?
-
tryingtolearn over 9 yearswhen trying to use request.META.HTTP_REFERER I get an error saying dict object has no attribute HTTP_REFERER.
-
almost a beginner over 6 yearsname 'self' is not defined?
-
Kurt Peek almost 6 yearsThis could raise a
KeyError
causing the page to crash; usingdict.get()
as described in the accepted answer would prevent this. -
Willy satrio nugroho almost 5 yearsjust simply add self.request if you use class based view
-
justbeingalearner over 3 yearsThis is raising MultiValueDictKeyError
-
justbeingalearner over 3 yearsThanks for this, it is working for Django 3 as well
-
run_the_race over 2 years@justbeingalearner sounds like your reverse proxy is not adding the header