Django Subdomains using django-subdomains package

心不动则不痛 提交于 2019-12-06 03:57:48

问题


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:


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',
)


来源:https://stackoverflow.com/questions/27493297/django-subdomains-using-django-subdomains-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!