Django-urls配置

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include('booktest.urls'))
]

4.配置booktest/urls

from django.urls import path , re_path
from . import views

urlpatterns = [
    path('', views.index),
    re_path(r'^detail/(?P<p1>[0-9]{4})/(?P<p2>[0-9]{2})/(?P<p3>[0-9]{2})/$', views.detail)
]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import *
from django.template import RequestContext, loader


# Create your views here.
def index(request):
    return HttpResponse('Hello World!')

def detail(request, p1, p2, p3):
    return HttpResponse('year:%s,month:%s,day:%s' % (p1, p2, p3))


5.访问网址

http://127.0.0.1:8000/booktest/

http://127.0.0.1:8000/booktest/detail/2018/06/04/

 

6.定义404错误文件,在templates目录下增加404.html文件

注:setting文件配置需要修改为调试模式

DEBUG = False

# 允许外网访问
ALLOWED_HOSTS = ['*']

 

出自于:GerryBlog