如何从Django模板中获取当前站点的域名?我试着在标签和过滤器中寻找,但没有什么。
当前回答
我认为我们想要的是现有url标签的替代品,所以我写了一个新标签:
from django.template import Library
from django.urls import reverse
@register.simple_tag(takes_context = True)
def fullURL(context, name, *args, **kwargs):
request = context['request']
return f'{request.scheme}://{request.get_host()}{reverse(name, args = args, kwargs = kwargs)}'
然后在你的模板中你可以这样…
{% extends "myapp/email/email_base.html" %}
{% load mytags %} {# Replace mytags with whatever the name of your custom tags calss is. #}
{% block content %}
<p>You can use <a href="{% fullURL 'signup' %}">this link</a> to get started with your account. We look forward to seeing you soon!</p>
{% endblock content %}
然后,当你生成这个时,你只需要记住将请求传递到上下文,就像这样……
from django.template.loader import render_to_string
def sendEmail(subject, to, template, **context):
html = render_to_string(f'myapp/email/{template}.html', context | {'subject': subject})
# ... and so on with the rest of my function for sending email...
其他回答
我知道这个问题很老了,但我是在寻找一种python方法来获取当前域时偶然发现的。
def myview(request):
domain = request.build_absolute_uri('/')[:-1]
# that will build the complete domain: http://foobar.com
我认为我们想要的是现有url标签的替代品,所以我写了一个新标签:
from django.template import Library
from django.urls import reverse
@register.simple_tag(takes_context = True)
def fullURL(context, name, *args, **kwargs):
request = context['request']
return f'{request.scheme}://{request.get_host()}{reverse(name, args = args, kwargs = kwargs)}'
然后在你的模板中你可以这样…
{% extends "myapp/email/email_base.html" %}
{% load mytags %} {# Replace mytags with whatever the name of your custom tags calss is. #}
{% block content %}
<p>You can use <a href="{% fullURL 'signup' %}">this link</a> to get started with your account. We look forward to seeing you soon!</p>
{% endblock content %}
然后,当你生成这个时,你只需要记住将请求传递到上下文,就像这样……
from django.template.loader import render_to_string
def sendEmail(subject, to, template, **context):
html = render_to_string(f'myapp/email/{template}.html', context | {'subject': subject})
# ... and so on with the rest of my function for sending email...
我发现了{{请求。Get_host}}方法。
这种方法怎么样?对我有用。 它也用于django注册。
def get_request_root_url(self):
scheme = 'https' if self.request.is_secure() else 'http'
site = get_current_site(self.request)
return '%s://%s' % (scheme, site)
from django.contrib.sites.models import Site
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
推荐文章
- pylab和pyplot的区别是什么?
- Argparse:确定使用了哪个子解析器
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?