Django 学习笔记(三)—— 第一个自定义应用 中篇

本文接上篇 Django 学习笔记(二)—— 第一个自定义应用 上篇,前提是已经完成了 Django 项目的初始化以及数据模型的创建。
本篇主要讲视图(View)的创建,视图即一类具有相同功能和模板的网页的集合。

本应用中需要用到一下几个视图:

  • 问题索引页:展示最近几个问题的列表
  • 问题详情页:展示某个需要投票的问题及其选项
  • 问题结果页:展示某个投票的结果
  • 投票处理器:响应用户为某个问题的特定选项投票的操作

一、模板

理论上讲,视图可以从数据库读取记录,可以使用模板引擎(Django 自带的或者第三方模板),可以输出 XML,创建压缩文件,可以使用任何想用的 Python 库。

必须的要求只是返回一个 HttpResponse 对象,或者抛出一个异常

借助 Django 提供的数据库 API,修改视图(polls/views.py 文件)中的 index() 函数,使得应用首页可以展示数据库中以发布时间排序的最近 5 个问题:

from django.http import HttpResponse
from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = '/n'.join([q.question_text for q in latest_question_list])
    if output:
        output = 'Em...there is no questions. Please add some.'
    return HttpResponse(output)

开启测试服务器,进入 Django 后台管理系统(http://127.0.0.1:8000/admin),添加测试问题:

add

访问 index 视图(http://127.0.0.1:8000/polls)效果如下:

test question

在当前的代码中,页面的布局定义是固定在视图函数中的,页面设计变更时则需要对 Python 代码进行改动。
此时可以通过使用 Django 的模板系统,将页面设计从业务代码中分离出来。

polls 目录下创建 templates 目录,Django 会自动在该目录下寻找模板文件。
polls/templates 目录下创建 polls 目录,并在该目录下创建 index.html 文件(即最终的模板文件为 polls/templates/polls/index.html)。

具体代码如下:

{% if latest_question_list %}
    
{% else %}
    

No polls are available.

{% endif %}

修改视图函数(polls/view.py)已使用刚刚创建的模板:

from django.shortcuts import 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)

render() 函数用于加载模块并填充上下文,然后返回生成的 HttpResponse 对象。

效果如下:


polls index
404 错误

此时访问问题详情页面(即点击 index 页面中的 test quesion 链接),会提示 Page not found 错误,原因是模板(index.html)中指定的 polls/{{ question_id }}/ 还没有创建对应的路由及其绑定的页面。

page not found

这里需要创建一个问题详情页的视图,用于显示指定问题的详细信息。同时当访问的问题不存在时,该视图会抛出 Http404 异常。
视图代码(polls/views.py)如下:

from django.http import Http404
from django.shortcuts import 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):
    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})

创建对应 detail 视图的模板文件(polls/templates/polls/detail.html):

{{ question.question_text }}

    {% for choice in question.choice_set.all %}
  • {{ choice.choice_text }}
  • {% endfor %}

其中 choice 模型还没有关联至后台页面并添加数据,不过暂时不影响页面显示。

修改路由配置文件(polls/urls.py),添加关联 detail 页面的路由,内容如下:

from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
    path('',views.index, name='index'),
    path('/', views.detail, name='detail'),
]

运行效果如下:


test question
page not found
去除硬编码 URL

polls/index.html 模板中的问题详情页链接当前是如下形式:

  • {{ question.question_text }}
  • 这种硬编码形式的链接在包含多个应用的项目中,相对而言并不方便修改。
    因为之前在路由配置文件 polls/urls.pyurl() 函数中通过 name 参数对 URL 进行了命名(path('/', views.detail, name='detail'),),所以可以在模板中使用 {% url %} 替代原来的硬编码链接:

  • {{ question.question_text }}
  • 同时,对于包含多个应用的项目,为了避免 URL 重名的情况出现,可以为 URL 名称添加命名空间。即 polls/urls.py 文件中的如下代码行:
    app_name = 'polls'

    此时模板文件(polls/templates/polls/index.html)中的硬编码链接即改为如下形式:

  • {{ question.question_text }}
  • 完整 index.html 代码如下:

    {% if latest_question_list %}
        
    {% else %}
        

    No polls are available.

    {% endif %}

    二、表单

    修改问题详情页的模板文件(polls/templates/polls/detail.html),添加

    表单:

    {{ question.question_text }}

    {% if error_message %}

    {{ error_message }}

    {% endif %} {% csrf_token %} {% for choice in question.choice_set.all %}
    {% endfor %}

    上面的模板在 Question 中的每个 Choice 前添加一个单选按钮,其 value 为 "choice.id" ,即每次选择并提交表单后,它将发送一个 POST 数据 choice=#choice_id

    表单的 action 为 {% url 'polls:vote' question_id %},且 action 方法为 POST。forloop.counter用于指示for`` 标签当前循环的次数。

    {% csrf_token %} 用于防御跨站点请求伪造

    接下来需要在视图文件(polls/views.py)中添加定义 vote 视图的函数:

    from django.http import HttpResponse, HttpResponseRedirect
    from django.shortcuts import render, get_object_or_404
    from django.urls import reverse
    from .models import Question, Choice
    
    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 vote(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        try:
            selected_choice = question.choice_set.get(pk=request.POST['choice'])
        except (KeyError, Choice.DoesNotExist):
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': "You didn't select a choice.",
                })
        else:
            selected_choice.votes += 1
            selected_choice.save()
    
            return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
    
    def results(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        return render(request, 'polls/results.html', {'question': question})
    

    其中 get_object_or_404() 是一个用于获取对象或者抛出 Http404 异常的快捷函数。
    HttpResponseRedirect 用于将用户重定向至指定页面(投票结果 results 页)。

    所以还需要创建一个 polls/templates/polls/results.html 模板文件:

    {{ question.question_text }}

      {% for choice in question.choice_set.all %}
    • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
    • {% endfor %}
    Vote again?

    修改 polls/urls.py 文件,添加上 vote 和 results 的路由配置:

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

    项目进行到这里算是基本告一段落了。为了可以在 Django 后台系统中操作 Choice 模型关联的数据库,还需要将 polls/admin.py 文件改为如下形式:

    from django.contrib import admin
    from .models import Question, Choice
    
    admin.site.register(Question)
    admin.site.register(Choice)
    

    此时运行测试服务器,最终效果如下:


    访问后台添加示例 question
    访问后台添加 choice 选项
    polls 主页
    投票页面
    结果展示页

    参考资料

    Django 2.2 官方文档

    你可能感兴趣的:(Django 学习笔记(三)—— 第一个自定义应用 中篇)