本文目录:
一、路由的基本使用
# url是个函数,有四个参数,第一个参数要传正则表达式,第二个传函数内存地址,第三个传默认参数,第四个传路由别名
"""day78_urls URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 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')) """ from django.conf.urls import url from django.contrib import admin from app01 import views from app01 import views urlpatterns = [
# 写路由的地方 url(r'^test/$', views.test), url(r'^test2/$', views.test2,name='test2'), ]
二、路由的无名分组
url(r'^test2/(d+)/(w+)$', views.test2),
无名分组分出几个值,视图函数就要接受几个值(位置参数形式传过来的)
三、路由的有名分组
url(r'^test3/(?P<id>d+)/(?P<name>w+)$', views.test3),
有名分组分出几个值,视图函数就要接受几个值(按关键字传入,位置可以打乱)
Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url,include from django.contrib import admin from app01 import views # from app01 import urls as app01_urls # from app02 import urls urlpatterns = [ url(r'^admin/', admin.site.urls), # url是个函数,有四个参数,第一个参数要传正则表达式,第二参数传函数内存地址,第三个参数传默认参数,第四个是路由的别名 # url(r'^test/$', views.test), # test3(request,1,lqz) # url(r'^test2/(d+)/(w+)$', views.test2), # test3(request,id=1,name=lqz) # url(r'^test3/(?P<id>d+)/(?P<name>w+)$', views.test3), # url(r'^test4/(?P<id>d+)/(?P<name>w+)$', views.test4), # url(r'^test4/(d+)/(w+)$', views.test4), # 路由分发 # app01/test # 这种方式不建议用 # url(r'^app01/', include(urls)), url(r'^app01/', include('app01.urls',namespace='app01')), url(r'^app02/', include('app02.urls',namespace='app02')), # url(r'^userrrrrrrrrrrr/(?P<id>d+)/$', views.userinfo,name='userinfo'), # 当用户访问info这个地址的时候,就给我重定向到id为1的那个人的详情 url(r'^index/', views.index), url(r'^info/', views.info), # url(r'^userinfotttaaa/', views.userinfo,name='userinfo'), # url(r'^userinfottt/(d+)', views.userinfo,name='userinfo'), url(r'^userinfottt/(?P<id>d+)', views.userinfo,name='userinfo'), url(r'^namespace_test/(d+)$', views.namespace_test), ]
四、有名和无名不能混着用
五、在setting中配置(以后的项目,一般不用动)
# 默认是true,浏览器浏览到时候,默认-加上斜杠
# 如果是False,浏览器默认不会加/
# APPEND_SLASH=False
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '92(mcd-jcux+2t99ki_sj7m#xz8fu&xut92k57415ap9*uu-yo' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', 'app02.apps.App02Config', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'day78_urls.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'day78_urls.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' # 默认是true,浏览器浏览的时候,默认加上斜杠 # 如果是False,浏览器默认不会加/ # APPEND_SLASH=False
六、路由分发
1.导入include
from django.conf.urls import include
2.在主路由中
urlpatterns = [ url(r'^admin/', admin.site.urls), # 路由分发 # app01/test # 这种方式不建议用 # url(r'^app01/', include(urls)), url(r'^app01/', include('app01.urls',namespace='app01')), url(r'^app02/', include('app02.urls',namespace='app02')), ]
3.在不同APP中新建一个urls
from app01 import views urlpatterns = [ url(r'^test/', views.test), ]
七、反向解析
反向解析有什么作用?
在视图函数中重定向的地址原来是写死的,如果url地址变更,我需要所有的url都修改,很麻烦,所以通过反向解析获取url地址。
如何使用:
路由层:
from django.conf.urls import url,include from django.contrib import admin from app01 import views # from app01 import urls as app01_urls # from app02 import urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^userinfotttaaa/', views.userinfo,name='userinfo'), url(r'^userinfottt/(d+)', views.userinfo,name='userinfo'), ]
视图层
from django.shortcuts import reverse def info(reuqest): # url=reverse('userinfo',args=(1,)) # return redirect(url) # url=reverse('userinfo',args=(1,)) url=reverse('userinfo',kwargs={'id':1}) print(url) # return redirect('/userinfo/1') return redirect(url) def userinfo(request): return HttpResponse('%s的详情') # def userinfo(request, id): # # return HttpResponse('%s的详情'%id) # url=reverse('url地址的别名') #如果做了分组 # url=reverse('url地址的别名',args=[],kwargs={})
模板层
{% url 'url地址的别名'%}
#如果做了分组
{% url 'url地址的别名' 参数1 参数2%}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/userinfo/">点我</a> <a href="{% url 'app01:test2' %}">点我</a> <a href="{% url 'app02:test2'%}">点我</a> </body> </html>
八、名称空间
-路由分发时,可以指定名称空间呢:
from django.conf.urls import url,include from django.contrib import admin from app01 import views # from app01 import urls as app01_urls # from app02 import urls urlpatterns = [ url(r'^admin/', admin.site.urls), -url(r'^app01/', include('app01.urls',namespace='app01')), -url(r'^app02/', include('app02.urls',namespace='app02')), ]
-在试图中方向解析;
def namespace_test(request,id): print(type(id)) url=reverse('app01:test2') url2=reverse('app02:test2') print(url) print(url2) return HttpResponse('namespace')
-在模板中方向解析:
{% url 'app01:url地址的别名'%}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/userinfo/">点我</a> <a href="{% url 'app01:test2' %}">点我</a> <a href="{% url 'app02:test2'%}">点我</a> </body> </html>
九、django2.0的path,re_path(了解)
1.0后的url就是2.0后的re_path
2.0后的path 第一个参数不在是正则表达式
5个转换器:int,str,slug,path,uuid
十、自定义转换器
1.写一个类:
class MyCon: regex = '[0-9]{4}' def to_python(self, value): return int(value) def to_url(self, value): return '%04d' % value
2.在urls中:
-from django.urls import register_converter -register_converter(类名,'别名') -path('test/<别名:year>', views.test,name='year'),