Django 获取绝对 URL [英] Django Get Absolute URL
问题描述
我想在模板中获取绝对网址.我不能用网址.它给了我一个相对 URL.我需要得到这个:
I want to get absolute url in templates. I can't do with url. It gives me a relative URL. I need to get this:
http://domain.tld/article/post
但 Django 只给了我
but Django gives me just
/article/post
我玩过 settings.py 但它没有用.(debug=false, 允许的主机 vs.)
I played with settings.py but it didn't work. (debug=false, allowed hosts vs.)
模板代码:
{% url 'blog:detail' blog.slug %}
推荐答案
与 Django 长时间会面后,我学到了很多东西.针对这个问题,我创建了一个绝对 URL 模板标签.
After a long time meeting with Django, I learned a lot of things. For this issue, I created an absolute URL templatetag.
将此添加到您的模板标签,然后使用像默认的 url 标签:
Add this to your template tags, then use like default url tag:
{% absurl 'some-view' with, arguments %}
这里是绝对URL模板标签的Gist,你需要添加请求对象到 template_context_processors,否则这将不起作用.为此,请打开您的 settings.py 并添加以下几行:
Here is the Gist for the absolute URL templatetag, you will need to add request object to template_context_processors, otherwise this will not work. To achieve this, open your settings.py and add these following lines:
from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.request',
)
这篇关于Django 获取绝对 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!