如何从Django模板中获取当前站点的域名?我试着在标签和过滤器中寻找,但没有什么。
当前回答
我使用自定义模板标记。例如:<your_app>/templatetags/site.py:
# -*- coding: utf-8 -*-
from django import template
from django.contrib.sites.models import Site
register = template.Library()
@register.simple_tag
def current_domain():
return 'http://%s' % Site.objects.get_current().domain
在模板中使用它,就像这样:
{% load site %}
{% current_domain %}
其他回答
这种方法怎么样?对我有用。 它也用于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)
我认为你想要的是访问请求上下文,参见RequestContext。
我认为我们想要的是现有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...
您可以在模板中使用{{protocol}}://{{domain}}来获取您的域名。
下面这些可以获得完整的url和部分url:
def myview(request):
request.build_absolute_uri()
# http://localhost:8000/admin/store/product/
request.build_absolute_uri('/')
# http://localhost:8000/
request.build_absolute_uri('/')[:-1]
# http://localhost:8000
request.scheme
# http
request.META['HTTP_HOST']
# localhost:8000
request.path
# /admin/store/product/
推荐文章
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码