A match, path
from django.contrib import admin from django.urls import path from index import views urlpatterns = [ path('articles/2003/', views.special_case_2003), path('articles/<int:year>/', views.year_archive), path('articles/<int:year>/<int:month>/', views.month_archive), path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail), ]
from django.http import HttpResponse def special_case_2003(request): return HttpResponse("This is the special 2003") def year_archive(request,year): return HttpResponse("This is year archive,Year number is %d" % year) def month_archive(request,year,month): return HttpResponse("This is month archive,It's %d year %d month" %(year,month)) def article_detail(request,year,month,slug): return HttpResponse("This is month articl details,It's %d year, %d month,slug is %s" %(year,month,slug))
1. a / separated, acquiring parameters with angle brackets, can specify the type
must be / otherwise not match any path behind the path 2.
3. view passed to the view function request contains parameters are examples and the acquired path
4 the sequence matches
two converter
what angle brackets in the following categories
- str, in addition to the matching / non-empty string, is not specified the default converter
- int, matching plastic
- slug, a short tag matches any ASCII letters or numbers, and the hyphen and the underscore
- uuid, this does not know Gansha
- path, comprising a matching / non-empty field
path('articles/<path:anythings>/',views.anythings)
def anythings(request,anythings): return HttpResponse("match nonthing above,your input is %s" % anythings)
Access http://127.0.0.1:8000/articles/mylove/hello/check/
响应match nonthing above,your input is mylove/hello/check
Third, custom converters
class FourDigitYearConverter: regex = '[0-9]{4}' def to_python(self, value): return int(value) def to_url(self, value): return '%04d' % value
from django.urls import path,register_converter
register_converter(converter.FourDigitYearConverter,'yyyy')
View register_converter centralized file can see the default rule converter django provisions, regex is a regular expression to match the value of.
to_python back end of the preceding python program is transmitted or the type of value, the conversion can be done here special
Fourth, the regular expression converter
path---> re_path
Converter wording: (? P <name after matching parameters> Regular Expressions)
例如:re_path('articles/?P<year>[0-9]{4}/$',views.function)
五、include
The app similar to the url specified in the urlconf.