Django Subdomains using django-subdomains package

2019-04-08 23:29发布

I am using the django-subdomains package to create subdomains. The problem is that no matter how I configure the SUBDOMAIN_URLCONFS, the site always directs to whatever I have put in ROOT_URLCONF as a default. Any insight as to what I am doing incorrectly would be greatly appreciated!

EDIT: Added 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条回答
欢心
2楼-- · 2019-04-09 00:17

As noted in the django-subdomains docs the subdomain middleware should come before CommonMiddleware

Add subdomains.middleware.SubdomainURLRoutingMiddleware to your MIDDLEWARE_CLASSES in your Django settings file. If you are using django.middleware.common.CommonMiddleware, the subdomain middleware should come before CommonMiddleware.

so your settings should look like this:

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',
)
查看更多
登录 后发表回答