Django 4.0文档学习(二)

编写你的第一个 Django 应用,第 3 部分

编写更多视图

polls/views.py 里添加更多视图。这些视图有一些不同,因为他们接收参数:

from django.http import HttpResponse
def index(request):
    return HttpResponse("Hello,world.You're at the polls index.")
def detail(request,question_id):
    return HttpResponse("You're looking at question %s." % question_id)
def results(request,question_id):
    response = "You're looking at the result of question %s."
    return HttpResponse(response % question_id)
def vote(request,question_id):
    return HttpResponse("You're voting on question %s." % question_id)

把这些新视图添加进 polls.urls 模块里

from django.urls import path
from . import views
urlpatterns=[
    path('',views.index,name='index'),
    path('<int:question_id>/',views.detail,name='detail'),
    path('<int:question_id>/results/',views.results,name='results'),
    path('<int:question_id>/vote/',views.vote,name='vote'),
]
> python manage.py runserver

打开浏览器输入以下url查看是否成功显示
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

写一个真正有用的视图

每个视图必须要做的只有两件事:返回一个包含被请求页面内容的 HttpResponse 对象,或者抛出一个异常,比如 Http404 。至于你还想做些什么,根据你的需求决定。

展示数据库里以发布日期排序的最近 5 个投票问题,以空格分割
polls/views.py
添加及改动内容如下,其他不变

from .models import Question
def index(request):
    latest_question_list=Question.objects.order_by('-pub_date')[:5]
    output=', '.join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

将页面的设计从代码中分离出来。

首先,在你的 polls 目录里创建一个 templates 目录。Django 将会在这个目录里查找模板文件。在templates目录里再创建目录polls,并在polls目录新建一个文件 index.html,并写入内容如下:
polls/templates/polls/index.html

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{
     
     { question.id }}/">{
   
   { question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

更新一下 polls/views.py 里的 index 视图来使用模板

from django.template import loader
def index(request):
    latest_question_list=Question.objects.order_by('-pub_date')[:5]
    template=loader.get_template('polls/index.html')
    context={
    
    'latest_question_list':latest_question_list,}
    return HttpResponse(template.render(context,request))

在这里插入图片描述
你将会看见一个无序列表,列出了我们在 教程第 2 部分 中添加的 “What’s up” 投票问题,链接指向这个投票的详情页。

一个快捷函数: render()

重写 index() 视图,polls/views.py

from django.shortcuts import render
def index(request):
    latest_question_list=Question.objects.order_by('-pub_date')[:5]    
    context={
    
    'latest_question_list':latest_question_list,}
    return render(request,'polls/index.html',context)

抛出 404 错误

polls/views.py

from django.http import Http404
def detail(request,question_id):
    try:
        question=Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request,'polls/detail.html',{
    
    'question':question})

如果指定问题 ID 所对应的问题不存在,这个视图就会抛出一个 Http404 异常。
polls/templates/polls/detail.html

{
    
    {
    
    question}}

在这里插入图片描述
在这里插入图片描述

一个快捷函数: get_object_or_404()

修改polls/views.py

在这里插入图片描述
在这里插入图片描述

也有 get_list_or_404() 函数,工作原理和 get_object_or_404() 一样,除了 get() 函数被换成了 filter() 函数。如果列表为空的话会抛出 Http404 异常。

使用模板系统

polls/templates/polls/detail.html

<h1>{
    
    {
    
    question.question_text}}</h1>
<ul>
    {
    
    % for choice in question.choice_set.all %}
        <li>{
    
    {
    
    choice.choice_text}}</li>
    {
    
    % endfor %}
</ul>

在这里插入图片描述

去除模板中的硬编码 URL

修改polls/index.html

<li><a href="{% url 'detail' question.id %}">{
    
    {
    
     question.question_text }}</a></li>

这个标签的工作方式是在 polls.urls 模块的 URL 定义中寻具有指定名字的条目。
如果你想改变投票详情视图的 URL,比如想改成 polls/specifics/12/ ,你不用在模板里修改任何东西(包括其它模板),只要在 polls/urls.py 里稍微修改一下就行:
如:path('specifics/<int:question_id>/',views.detail,name='detail'),

为 URL 名称添加命名空间

教程项目只有一个应用,polls 。在一个真实的 Django 项目中,可能会有五个,十个,二十个,甚至更多应用。Django 如何分辨重名的 URL 呢?
polls/urls.py添加

app_name='polls'

编辑 polls/index.html

<li><a href="{% url 'polls:detail' question.id %}">{
    
    {
    
     question.question_text }}</a></li>

目前各代码内容如下:
polls/views.py

from django.http import HttpResponse
from django.shortcuts import get_object_or_404,render
from .models import Question
def index(request):
    latest_question_list=Question.objects.order_by('-pub_date')[:5]
    context={
    
    'latest_question_list':latest_question_list,}
    return render(request,'polls/index.html',context)
def detail(request,question_id):
    question=get_object_or_404(Question,pk=question_id)
    return render(request,'polls/detail.html', {
    
    'question':question})
def results(request,question_id):
    response = "You're looking at the result of question %s."
    return HttpResponse(response % question_id)
def vote(request,question_id):
    return HttpResponse("You're voting on question %s." % question_id)

polls/urls.py

from django.urls import path
from . import views
app_name='polls'
urlpatterns=[
    path('',views.index,name='index'),
    path('<int:question_id>/',views.detail,name='detail'),
    path('<int:question_id>/results/',views.results,name='results'),
    path('<int:question_id>/vote/',views.vote,name='vote'),
]

在这里插入图片描述
index.html

{
    
    % if latest_question_list %}
    <ul>
    {
    
    % for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{
    
    {
    
     question.question_text }}</a></li>
    {
    
    % endfor %}
    </ul>
{
    
    % else %}
    <p>No polls are available.</p>
{
    
    % endif %}

detail.html

<h1>{
    
    {
    
    question.question_text}}</h1>
<ul>
    {
    
    % for choice in question.choice_set.all %}
        <li>{
    
    {
    
    choice.choice_text}}</li>
    {
    
    % endfor %}
</ul>

猜你喜欢

转载自blog.csdn.net/weixin_46322367/article/details/129627929