django urls
url 与 path
django 2.0 发布之后,url使用方面与1.11有蛮大的变化。下面举几个小栗子来说明(代码就是最好的文档:p)
from django.conf.urls import url,include # 1.11与2.0 from django.urls import path,re_path,include # 2.0 urlpatterns = [ url('^$',index,name='index'), path('', index,name='index'), url('^register/$',register,name='register'), path('register/', register,name='register'), url('^articles/(?P<year>[0-9]{4})/$', articles,name='articles'), path('articles/<int:year>/',articles,name='articles'), ]
如何管理多个app下的路由分发,使得管理更加清晰?
1. 在app下创建urls.py文件
from django.urls import path,re_path from myapp.views import IndexView urlpatterns = [ path(r'index/', IndexView.as_view(),name="index"), ]
2.在myproject/myproject/urls.py配置
from django.urls import url,path,include urlpatterns = [ path(r'myapp/',include("myapp.urls")),#包含myapp中的urls ]
reverse
好处,就是需要修改url路径时仅需修改一处即可。与tempaltes中的{ url 'index' }情形是一样的。
from django.urls import reverse from django.http import HttpResponseRedirect class LogoutView(View): """ 用户登出 """ def get(self, request): logout(request) return HttpResponseRedirect(reverse("index"))