自定义 URL 对应的视图
在 views.py 中增加 URL 的过滤和响应事件
在 views.py 中增加过滤
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello world, You're at the polls index.")
新建 urls.py
此 urls.py 中主要是为了设置 URL 的拦截
拦截到url 后,通过拦截到的URL和 request 做一些不同的响应(response)
^$ 代表所有的路径都要进行过滤
urlpatterns = [
url(r'^$', views.index, name='index')
]
这样配置后将 views 中的 index 方法注册为了 URL的过滤和处理的一个方法,所有的网络请求,都会进入此方法进行匹配
【说明】r'^' 这个是正则表达式
注册 urls.py 文件
在前两步只是定义了方法和声明这个方法为 url 的过滤方法之一,但是我们的定义和声明都在 views.py 、 urls.py 文件中放置,程序并不会执行到这个地方,我们需要告诉程序
在 工程的 urls.py 文件中配置

path.png
此处配置了URL的过滤
第一行是:将匹配到 polls/ 路径下的 的所有请求使用 polls.urls.py 文件中的过滤方法进行过滤
第二行是默认的执行过滤
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls))
]
正则
针对 URL /polls/test/ 说明匹配
- jango发现匹配到了正则表达式'^polls/'
- 然后,Django将去掉匹配到的文本("polls/")并将剩下的文本 —— "test/" —— 发送给‘polls.urls’ URLconf 做进一步处理
url() 方法的使用
url()函数具有四个参数:两个必需的regex和 view,以及两个可选的kwargs和name。 到这里,就可以研究下这些参数的含义了
r'^(?P<question_id>[0-9]+)/$'
很明显这个是正则 (?P<question_id>) 定义了一个名字,它将用于标识匹配的模式
[0-9]是标识至少存在一个数字
模板
- 将模板放置在 templates 的 polls 目录下面。因为 通过 polls 相当于是创建了命名空间
- 在 views.py 中,不同的 path 返回不同的模板
- views.py 文件就是一个中间者 mvc 中的 c。模板就是 v。传给模板的值就是 m
模板的使用
def index(request):
last_question_list = Question.objects.order_by('-pub_date')[:5]
# 因为我们我们已经设置过查找 templates 并且默认的就是查找 templates ,故默认就是在 templates 文件下
# 取出模板
indexTemplate = loader.get_template('polls/index.html')
# 创建一个渲染上下文
context = RequestContext(request, {
'latest_question_list': last_question_list,
})
# 将上下文应用到模板
out_put = indexTemplate.render({
'latest_question_list': last_question_list,
})
return HttpResponse(out_put)
404
# 此处是获取对象的属性
# get_object_or_404()
# 函数将一个Django模型作为它的第一个参数,任意数量的关键字参数作为它的第二个参数,它会将这些关键字参数传递给模型管理器中的get()
# 函数。如果对象不存在,它就引发一个
# Http404异常。
# 还有一个get_list_or_404()
# 函数,它的工作方式类似get_object_or_404() —— 差别在于它使用filter()
# 而不是get()。如果列表为空则引发Http404。
question = get_object_or_404(Question,pk=question_id)
URL 的三种写法
<a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a>
<a href="{% url 'detail' question.id %}">{{ question.question_text }}</a>
<a href="/polls/{{ question.id }}">{{ question.question_text }}</a>