1.URL配置
1.1.Django处理请求
(1)通过URLconf模块。通常在setting.py中,通过ROOT_URLCONF设置。但如果传入 HttpRequest 对象拥有 urlconf 属性(通过中间件设置)将代替 ROOT_URLCONF 设置。
(2)加载该模块并寻找可用的 urlpatterns
(3)遍历每个 URL 模式,然后会在所请求的URL匹配到第一个模式后停止,并与 path_info 匹配
(4)URL 匹配成功,Djagno 导入并调用相关的视图,这个视图是一个Python 函数(或基于类的视图 class-based view )。
视图会获得如下参数:
一个 HttpRequest 实例。
如果匹配的 URL 包含未命名组,那么来自正则表达式中的匹配项将作为位置参数提供。
关键字参数由路径表达式匹配的任何命名部分组成,并由 django.urls.path() 或 django.urls.re_path() 的可选 kwargs 参数中指定的任何参数覆盖。
(5)如果没有 URL 被匹配,或者匹配过程中出现了异常,Django 会调用一个适当的错误处理视图。
1.2.URLconf
(1)example
from django.urls import path
from . 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),
]
(2)路径转换器
如上图:<int:year>
- str- 匹配除了 '/' 之外的非空字符串。如果表达式内不包含转换器,则会默认匹配字符串。
- int- 匹配 0 或任何正整数。返回一个 int 。
- slug- 匹配任意由 ASCII 字母或数字以及连字符和下划线组成的短标签。比如,building-your-1st-django-site 。
- uuid- 匹配一个格式化的 UUID 。为了防止多个 URL 映射到同一个页面,必须包含破折号并且字符都为小写。比如,075194d3-6885-417e-a8a8-6c931e272f00。返回一个 UUID 实例。
- path- 匹配非空字段,包括路径分隔符'/' 。它允许你匹配完整的 URL 路径而不是像 str 那样匹配 URL 的一部分。
注册自定义的路径转换器:
converters.py:
class FourDigitYearConverter:
regex = "[0-9]{4}"
def to_python(self, value):
return int(value)
def to_url(self, value):
return "%04d" % value
URLconf :
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FourDigitYearConverter, "yyyy")
urlpatterns = [
path("articles/2003/", views.special_case_2003),
path("articles/<yyyy:year>/", views.year_archive),
...,
]
(3)使用正则表达式
使用 re_path() 而不是 path()
from django.urls import path, re_path
from . import views
urlpatterns = [
path("articles/2003/", views.special_case_2003),
re_path(r"^articles/(?P<year>[0-9]{4})/$", views.year_archive),
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,
),
]
嵌套参数
正则表达式允许嵌套参数,Django 将处理它们并传递给视图
from django.urls import re_path
urlpatterns = [
re_path(r"^blog/(page-([0-9]+)/)?$", blog_articles), # bad
re_path(r"^comments/(?:page-(?P<page_number>[0-9]+)/)?$", comments), # good
]
(4)指定视图参数的默认值
URLconf :
from django.urls import path
from . import views
urlpatterns = [
path("blog/", views.page),
path("blog/page<int:num>/", views.page),
]
views.py:
def page(request, num=1):
print("num:", num)
(5)包含其他应用的URLconf
且,被包含的URLconf 会收到来自父URLconf 捕获的任何参数
from django.urls import include, path
urlpatterns = [
path("community/", include("aggregator.urls")),
path("contact/", include("contact.urls")),
]
(6)传递额外选项给视图函数
path() 函数可带有可选的第三参数(必须是字典),传递到视图函数里。
from django.urls import path
from . import views
urlpatterns = [
path("blog/<int:year>/", views.year_archive, {"foo": "bar"}),
]
(7)url反向解析
从相应的 Django 视图标识以及要传递给它的参数来获取相关联的 URL
Django 提供执行反转 URL 的工具,这些工具与需要 URL 的不同层匹配:
- 在模板里:使用 url 模板标签。
- 在 views.py:使用 reverse() 函数。
- 在与 Django 模型实例的 URL 处理相关的高级代码中: get_absolute_url() 方法。
URLconf :
from django.urls import path
from . import views
urlpatterns = [
path("articles/<int:year>/", views.year_archive, name="news-year-archive"),
]
在模板代码中:
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
{# Or with the year in a template context variable: #}
<ul>
{% for yearvar in year_list %}
<li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>
在views.py:
from django.http import HttpResponseRedirect
from django.urls import reverse
def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse("news-year-archive", args=(year,)))
(8)命名空间
方法一:
polls/urls.py:
from django.urls import path
from . import views
app_name = "polls"
urlpatterns = [
path("", views.IndexView.as_view(), name="index"),
path("<int:pk>/", views.DetailView.as_view(), name="detail"),
]
urls.py:
from django.urls import include, path
urlpatterns = [
path("polls/", include("polls.urls")),
]
方法二:
urls.py:
from django.urls import include, path
from . import views
polls_patterns = (
[
path("", views.IndexView.as_view(), name="index"),
path("<int:pk>/", views.DetailView.as_view(), name="detail"),
],
"polls",
)
urlpatterns = [
path("polls/", include(polls_patterns)),
]
2.视图
2.1.视图函数
(1)example
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
(2)返回错误信息
HttpResponse 的子类
from django.http import HttpResponse, HttpResponseNotFound
def my_view(request):
# ...
if foo:
return HttpResponseNotFound("<h1>Page not found</h1>")
else:
return HttpResponse("<h1>Page was found</h1>")
Http404 异常:
from django.http import Http404
from django.shortcuts import render
from polls.models import Poll
def detail(request, poll_id):
try:
p = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404("Poll does not exist")
return render(request, "polls/detail.html", {"poll": p})
自定义报错视图,添加在URLconf
handler404 = "mysite.views.my_custom_page_not_found_view"
handler500 = "mysite.views.my_custom_error_view"
2.2.内置函数
(1)render()
render(request, template_name, context=None, content_type=None, status=None, using=None)
必选参数:
request 用于生成此响应的请求对象。
template_name 要使用的模板的全名或模板名称的序列。
可选参数:
context 要添加到模板上下文的值的字典。 默认情况下,这是一个空的字典。 如果字典中的值是可调用的,则视图将在渲染模板之前调用它。
content_type 用于结果文档的 MIME 类型。默认 'text/html' 。
status 响应的状态码默认为 200。
using 用于加载模板的模板引擎的 NAME 。
(2)redirect()
redirect(to, *args, permanent=False, **kwargs)
返回一个 HttpResponseRedirect,指向传递参数的适当 URL。
参数可以是:
- 一个模型:模型的 get_absolute_url() 函数将被调用。
- 视图名,可能带有的参数:reverse() 将被用于反向解析名称。
- 一个绝对或相对 URL,将按原样用作重定向位置。
默认情况下发出临时重定向;通过传递 permanent=True 发出永久重定向。
(3)get_object_or_404()
get_object_or_404(klass, *args, **kwargs)
在给定的模型管理器( model manager) 上调用 get() ,但它会引发 Http404 而不是模型的 DoesNotExist 异常。
参数:
klass 从中获取对象的 Model 类, Manager ,或 QuerySet 实例。
*args Q objects.
**kwargs 查询参数,应采用 get() 和 filter() 接受的格式。
2.3.视图装饰器
(1)允许的 HTTP 方法
@require_http_methods(request_method_list)
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
pass