前言:
使用django已经很久了,之前一直采用django搭建网站,简单的解析到一个www域名上,很多时候前端也是采用自适应框架,而不必考虑去同时绑定pc域名和手机域名,那么今天遇到了,就系统的跟大家分享一下相关经验!
需求场景:
想用django建一个网站,分为pc端和手机移动端,也就是两个域名分别对应手机端和pc端
比如:
m.bugscaner.com 对应的是 手机端
www.bugscaner.com 对应的是 pc端
那么两个域名该怎么解析到django项目上呢?
我首先想到的是创建两个django项目, 分别去解析!这样有个麻烦就是需要分别管理,和创建models
有没有更好的解决方案呢?答案是有,那就是django的一个插件 django-hosts
我使用的是django1.8.2, 但是django-hosts 最低支持的版本是 django1.11 那么需要先卸载老版本的django1.8.2 安装新的django
卸载命令:
pip uninstall django安装django1.11 版本的命令是:
pip install django==1.11
安装django-hosts 命令很简单 直接在virtualenv环境里执行命令
pip install django-hosts
安装完毕之后,就跟我一步一步开始改造你的django, 让他支持多级域名解析吧!
安装步骤:
1:增加 django_hosts 到 INSTALLED_APPS:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_hosts', 'core', ]2:在MIDDLEWARE最开始添加HostsRequestMiddleware 在MIDDLEWARE最后面添加 HostsResponseMiddleware
MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', 'django.middleware.security.SecurityMiddleware', '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', 'django_hosts.middleware.HostsResponseMiddleware', ]
3:然后在settings.py文件里添加如下配置:
ROOT_HOSTCONF = 'mysite.hosts' # Change `mysite` to the name of your project DEFAULT_HOST = 'www' # Name of the default host, we will create it in the next steps4:创建一个hosts.py文件在你的项目urls.py在一个目录里,结构如下:
mysite/ |-- __init__.py |-- hosts.py # <-- The `ROOT_HOSTCONF` refers to this file |-- settings.py |-- urls.py +-- wsgi.pymysite/hosts.py文件内容为:
from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), # <-- The `name` we used to in the `DEFAULT_HOST` setting )###############################
下面是一个使用实例:
Let’s create an app named help to illustrate the usage of the django-hosts:
django-admin startapp help
Then inside of the new app, we create a urls.py module:
help/urls.py
from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^articles/$', views.articles, name='articles'), url(r'^articles/(?P<pk>\d+)/$', views.article_details, name='article_details'), ]
Now we update the mysite/hosts, which is our ROOT_HOSTCONF:
mysite/hosts.py
from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'help', 'help.urls', name='help'), )
设置本地hosts用来测试:
windows hosts 文件位置在 C:\Windows\System32\drivers\etc
其他系统请自行搜索
127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost 127.0.0.1 www.mysite.local 127.0.0.1 help.mysite.local