前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Django学习笔记 1.4 表单和通用视图

Django学习笔记 1.4 表单和通用视图

作者头像
twowinter
发布于 2020-04-17 04:14:01
发布于 2020-04-17 04:14:01
83100
代码可运行
举报
文章被收录于专栏:twowintertwowinter
运行总次数:0
代码可运行

文章目录
  • 前言
  • 1 编写一个简单的表单
    • 1.1 模版中新增表单
    • 1.2 视图中新增交互处理
    • 1.3 重定向的 results 页面增加显示
    • 1.4 完善 results.html 页面代码
  • 2 通用视图
    • 2.1 改良 URLconf
    • 2.2 改良视图
  • 小结

前言

这一节我们将继续编写投票应用,专注于简单的表单处理并且精简我们的代码。

小能手正在学习 Django,系列笔记请点此查看

1 编写一个简单的表单

1.1 模版中新增表单

更新一下在上一个教程中编写的投票详细页面的模板 (“polls/detail.html”) ,增加一个 HTML 元素:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<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>

所有针对内部 URL 的 POST 表单都应该使用 {% csrf_token %} 模板标签。

1.2 视图中新增交互处理

polls/views.py 中将投票选择存入数据库,同时做URL的重定向处理。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, 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):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

1.3 重定向的 results 页面增加显示

还是在视图中处理 results。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from django.shortcuts import get_object_or_404, render


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})

1.4 完善 results.html 页面代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<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>

2 通用视图

投票应用中的 detail 和 results 视图的操作都差不多,显得冗余。

这些视图反映基本的 Web 开发中的一个常见情况:根据 URL 中的参数从数据库中获取数据、载入模板文件然后返回渲染后的模板。 由于这种情况特别常见,Django 提供一种快捷方式,叫做“通用视图”系统。

通用视图将常见的模式抽象化,可以使你在编写应用时甚至不需要编写Python代码。

让我们将我们的投票应用转换成使用通用视图系统,仅仅需要做以下几步来完成转换: 1.转换 URLconf。 2.删除一些旧的、不再需要的视图。 3.基于 Django 的通用视图引入新的视图。

2.1 改良 URLconf

polls/urls.py

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

2.2 改良视图

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


def vote(request, question_id):
    ... # same as above, no changes needed.

小结

这节终于用上了通用视图,再一次感受到了Django框架,把冗余的东西都做了简化抽象。

定义了通用视图,传递给它指定模版,以及模型,一切就OK了。它比 render 快捷函数更加简洁。


本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 前言
  • 1 编写一个简单的表单
    • 1.1 模版中新增表单
    • 1.2 视图中新增交互处理
    • 1.3 重定向的 results 页面增加显示
    • 1.4 完善 results.html 页面代码
  • 2 通用视图
    • 2.1 改良 URLconf
    • 2.2 改良视图
  • 小结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档