Django's view
Unlike other language MVC patterns, Django uses the MVT model, the model, the view, the Template, where the view is essentially a controller in other languages (emmm ...). , and the template is actually HTML file, so the principle is actually very much the same, here does not repeat
Configure URLs
The default route in Django is in urls.py in the project home directory, and the basic routing configuration is as follows:
from django.urls import path, includefrom . import viewsurlpatterns = [ 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), path(‘‘, include(‘test.urls‘)) # 引入不同应用的url配置]
These are common matches, and there are several functions that can be used to limit the type of parameters in a route.
- STR: matches any non-empty string except for path delimiter '/'
- int: match 0 or any positive integer
- Slug: matches any slug string consisting of ascii letters or numbers, as well as hyphens '-' and underscore ' _ ' characters
- UUID: Match formatted UUID
- Path: Matches any non-empty string, including path delimiter '/'
Using regular expression matching
from django.urls import path, re_pathfrom . import viewsurlpatterns = [ path(‘articles/2003/‘, views.special_case_2003), re_path(r‘^articles/(?P<year>[0-9]{4})/$‘, views.year_archive), # ?P<year>意为指定参数的名字 re_path(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$‘, views.month_archive), re_path(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$‘, views.article_detail),]
URL Alias
This example is used in relation to the route () usage in the PHP laravel framework, as follows
# 路由中的配置from django.urls import path, includefrom test import viewsurlpatterns = [ path(‘‘, views.index, name=‘test-index‘), path(‘/<int:num>‘, views.getNum) path(‘‘, include(‘test.urls‘, namespace = ‘test‘)) #为include起别名]# 在template中的运用<a href="{% url ‘test-index‘ 此处可以跟参数 %}"></a># 在views中的运用from django.http import HttpResponseRedirectfrom django.urls import reversedef redirect_to_year(request): year = 2006 # 参数 return HttpResponseRedirect(reverse(‘test-index‘, args=(year,)))
Python--django (iii) view