Django子域名使用django-subdomains包

时间:2014-12-15 21:17:48

标签: python django subdomain middleware

我正在使用django-subdomains package创建子域名。问题是无论我如何配置SUBDOMAIN_URLCONFS,网站总是指向我在ROOT_URLCONF中放置的任何内容作为默认值。我非常感谢您对我所做错误的了解!

编辑:添加了MIDDLEWARE_CLASSES


mysite的/ settings.py

...

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'subdomains.middleware.SubdomainURLRoutingMiddleware',
)

...

ROOT_URLCONF = 'mysite.urls'

SUBDOMAIN_URLCONFS = {
    None: 'mysite.urls',
    'www': 'mysite.urls',
    'myapp': 'myapptwo.test',
}

...



mysite的/ urls.py

from django.conf.urls import patterns, include, url
from myapp import views
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^admin/', include(admin.site.urls)),
)



的myapp / views.py

from django.shortcuts import render
from django.http import HttpResponse

def index(Request):
    return HttpResponse("Hello world.")



myapptwo / urls.py

from django.conf.urls import patterns, include, url
from myapptwo import views
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^admin/', include(admin.site.urls)),
)



myapptwo / views.py

from django.shortcuts import render
from django.http import HttpResponse

def index(Request):
    return HttpResponse("Hello world. This is the myapptwo subdomain!")

1 个答案:

答案 0 :(得分:3)

django-subdomains docs中所述,子域中间件应该出现在CommonMiddleware

之前
  

将subdomains.middleware.SubdomainURLRoutingMiddleware添加到Django设置文件中的MIDDLEWARE_CLASSES。如果您使用的是django.middleware.common.CommonMiddleware,则子域中间件应该在CommonMiddleware之前。

因此您的设置应如下所示:

MIDDLEWARE_CLASSES = (
    'subdomains.middleware.SubdomainURLRoutingMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)