Django: getting previous url

2019-01-19 11:58发布

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>

4条回答
三岁会撩人
2楼-- · 2019-01-19 12:17

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

查看更多
仙女界的扛把子
3楼-- · 2019-01-19 12:25

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

查看更多
Evening l夕情丶
4楼-- · 2019-01-19 12:26

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

查看更多
家丑人穷心不美
5楼-- · 2019-01-19 12:34

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

查看更多
登录 后发表回答