简体   繁体   English

如何从 Django 请求中获取完整的 URL

[英]How to get full url from django request

Is there a better way to get the full url in django than doing the following:有没有比执行以下操作更好的方法来获取 django 中的完整 url:

url = request.META['HTTP_HOST']
    + request.META['PATH_INFO']
    + request.META['QUERY_STRING']

Is there something like request.META['URL'] ?有类似request.META['URL']东西吗?

You can get full URL using request.build_absolute_uri method:您可以使用request.build_absolute_uri方法获取完整的 URL:

FULL_URL_WITH_QUERY_STRING: request.build_absolute_uri()
FULL_URL: request.build_absolute_uri('?')
ABSOLUTE_ROOT: request.build_absolute_uri('/')[:-1].strip("/")
ABSOLUTE_ROOT_URL: request.build_absolute_uri('/').strip("/")

Should this will help full to you.如果这将对您有所帮助。

The best way to use ABSOLUTE URLS in Django, you can create a context_processors or middleware and find your ABSOLUTE_URL and return that so that you can use any where in Django.在 Django 中使用 ABSOLUTE URLS 的最佳方法是,您可以创建一个 context_processors 或中间件并找到您的ABSOLUTE_URL并返回它,以便您可以在 Django 中的任何地方使用。

Like this example:像这个例子:

def absolute(request):
    urls = {
        'ABSOLUTE_ROOT': request.build_absolute_uri('/')[:-1].strip("/"),
        'ABSOLUTE_ROOT_URL': request.build_absolute_uri('/').strip("/"),
    }

    return urls

And Then you should use {{ABSOLUTE_ROOT}} in any where into you django template.然后你应该在 django 模板的任何地方使用{{ABSOLUTE_ROOT}}

Is there a better way to get the full url in django than doing the following:有没有比执行以下操作更好的方法来获取 django 中的完整 url:

url = request.META['HTTP_HOST']
    + request.META['PATH_INFO']
    + request.META['QUERY_STRING']

Is there something like request.META['URL'] ?有没有类似request.META['URL']

you can use您可以使用

in template在模板中

{{ request.META.PATH_INFO }}

in views在观点中

end_point = request.META.get('PATH_INFO', None)    # not recommend

please use David542 's answer请使用David542的回答

request.build_absolute_uri()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM