这是一件非常简单的事情。您有几个不同的选择。
直接从模板检查 HTTP_HOST
一个非常简单的方法是从模板检查 request.META 字典中 HTTP_HOST 键的值。
{# Anything other than port 80, HTTP_HOST will also include the port number as well #}
{% ifequal request.META.HTTP_HOST 'example2.com' %}
<!-- your css imports here -->
{% endifequal %}
请记住,这是由客户端设置的,因此,如果您正在做任何其他对安全敏感的事情,这将不是使用方法。只是为了加载一些 CSS 就可以了。
自定义中间件
另一种选择是创建自定义中间件并从那里检查相同的对象。基本上是相同的过程,但你可能想做一些事情,比如在请求对象上设置一个额外的键
在某个文件中..yourproject/someapp/middlware.py
class DomainCheckMiddleware(object):
def process_request(self, request):
if request.META['HTTP_HOST'] == "example2.com":
request.IS_EXAMPLE2 = True
else:
request.IS_EXAMPLE2 = False
return None
在你的 settings.py 中
MIDDLEWARE_CLASSES = (
# whatever middleware you're already loading
# note: your middleware MUST exist in a package that's part of the INSTALLED_APPS
'yourproject.someapp.DomainCheckMiddleware'
)
在您的模板中
{% if request.IS_EXAMPLE2 %}
<!-- load your css here -->
{% endif %}
这是更多的跑腿工作,几乎做同样的事情,但您可以轻松地应用一些额外的测试来查看您是否处于调试模式或只是通过 localhost:8000 访问并且仍然将 IS_EXAMPLE2 设置为 true,而无需使您的模板更难阅读。
这也有前面提到的同样的缺点。
https://docs.djangoproject.com/en/dev/topics/http/middleware/
使用网站框架
仅当您启用了站点框架 (django.contrib.sites) 时,使用站点框架才有效,默认情况下它不再是启用的,并且对于您的目的来说是多余的。不过,您可以从这个答案中看到一个如何工作的示例:
How can I get the domain name of my site within a Django template?