如何在django中检测当前域名?

时间:2017-03-28 04:37:40

标签: python django

我想设计我的Web应用程序来提供两个不同的前端模板,具体取决于用户输入我的django应用程序的域。

因此,如果用户输入aaa.com,它将从应用程序AAA_USA提供前端服务,但如果用户从aaa.co.my进入,它将从应用程序AAA_MY服务于前端。

最好的方法是什么?我在考虑“检测当前域名”,然后在View函数中添加if-else语句。

这两个域将指向包含我的Django应用程序的相同Nameservers。

3 个答案:

答案 0 :(得分:0)

使用

request.build_absolute_uri()

将追溯完整路径: ES:

  

http://localhost:8000/test/

答案 1 :(得分:0)

我这样做的方式基本上是使用中间件(使用会话并检测HTTP_HOST。

class SimpleMiddleware(object):
def __init__(self, get_response):
    self.get_response = get_response
    # One-time configuration and initialization.

def __call__(self, request):
    # Code to be executed for each request before the view (and later middleware) are called.

    # sets to show Taiwan or Indo version
    # sets the timezone too
    http_host = request.META['HTTP_HOST']
    if(http_host == 'http://www.xxx.tw'):
        request.session['web_to_show'] = settings.TAIWAN
        request.session['timezone_to_use'] = settings.TAIWAN_TIMEZONE
    else:
        request.session['web_to_show'] = settings.INDO
        request.session['timezone_to_use'] = settings.INDONESIA_TIMEZONE

    response = self.get_response(request)

    # Code to be executed for each request/response after the view is called.

    return response

答案 2 :(得分:0)

如果您无权访问请求对象,则可以使用sites framework

from django.contrib.sites.shortcuts import get_current_site
domain = get_current_site(None)

这将返回Django配置的站点(使用保存在数据库的 django_site 表中的值。(请参阅:https://docs.djangoproject.com/.../sites/shortcuts/