如果开发比较大的网站项目,会有很多个app。如果每个app的url都写在根目录的urls文件里会显得比较混乱,不好维护。可以在每个app里都创建urls文件,再由include方法引入到根目录。
见在根目录urls里的介绍:
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
根目录urls改为
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', include('blog.urls')),
]
blog的urls:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^index/', views.index),
]
但是这样网址会变成http://127.0.0.1:8000/index/index/
比较合理的是http://127.0.0.1:8000/blog/所以要改成这样
根目录urls
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/', include('blog.urls')),
]
blog的urls
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
]
但是需要注意:
- blog里url虽然是空字符串,但是不能写成r'',而要写r'^$'。$意思是以前边的字符结尾。如果没有$则在网址栏后边输入什么都可以进入网站。
- ^blog/$里,blog后边必须有/,否则报错。只要不是空字符串都得有/.