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 %}
    <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/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):

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

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

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

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'),
]

运行效果如下:


test question
page not found
去除硬编码 URL

polls/index.html 模板中的问题详情页链接当前是如下形式:
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

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

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

此时模板文件(polls/templates/polls/index.html)中的硬编码链接即改为如下形式:
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

完整 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 %}

二、表单

修改问题详情页的模板文件(polls/templates/polls/detail.html),添加 <form> 表单:

<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

上面的模板在 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 模板文件:

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

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

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'),
]

项目进行到这里算是基本告一段落了。为了可以在 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 官方文档

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,809评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,189评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,290评论 0 359
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,399评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,425评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,116评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,710评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,629评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,155评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,261评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,399评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,068评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,758评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,252评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,381评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,747评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,402评论 2 358

推荐阅读更多精彩内容