[Django]-How to get the previous URL from a POST in Django

61πŸ‘

βœ…

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

πŸ‘€Viktor

9πŸ‘

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

πŸ‘€Abid A

4πŸ‘

I can’t answer @tryingtolearn comment, but for future people, you can use request.META['HTTP_REFERER']

3πŸ‘

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>
πŸ‘€run_the_race

2πŸ‘

A much more reliable method would be to explicitly pass the category in the URL of the Add Post button.

1πŸ‘

You can get the previous url in "views.py" as shown below:

# "views.py"

from django.shortcuts import render

def test(request):
    
    pre_url = request.META.get('HTTP_REFERER') # Here
        
    return render(request, 'test/index.html')

You can also get the previous url in Django Template as shown below:

# "index.html"

{{ request.META.HTTP_REFERER }}

Leave a comment