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>
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 noHTTP_REFERER
in METAdict
. So be careful and make sure that you are using.get()
notation instead.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
I can't answer @tryingtolearn comment, but for future people, you can use
request.META['HTTP_REFERER']
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
A much more reliable method would be to explicitly pass the category in the URL of the Add Post button.