Django2.2丨表单和通用视图

本文介绍了如何在Django2.2中编写和处理简单的投票表单,包括设置表单模板、处理POST数据以及防止跨站请求伪造。此外,还探讨了如何使用通用视图简化视图函数,通过调整URLconf和视图配置,实现更加高效的应用开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个简单的表单

编写投票详情页模板

# polls/templates/polls/detail.html
<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。每个单选按钮的name是"choice"。意味着,当选择一个单选按钮并提交表单提交时,它将发送一个POST数据choice=#,其中#为选择的Choice的ID。

  • 设置表单的action为{% url 'polls:vote' question.id %},并设置method=‘post’。

  • forloop.counter指示for标签已经循环多少次

  • 由于创建一个POST表单(具有修改数据的租用),所以需要小心跨站点请求伪造。Django具备完善的防御系统,如果使用表单,要在URL的POST表单使用{% csrf_token %}模型标签

创建一个数据,来处理提交数据

# polls/urls.py
path('<int:question_id>/vote/', views.vote, name='vote')
# polls/views.py
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,)))
  • request.POST是一个类字典对象,可以通过关键字的名字获取提交的数据。request.POST的值永远是字符串

  • 如果在request.POST[‘choice’]数据中没有提供choice,POST将引发一个KeyError。

  • 在增加Choice的得票数之后,代码返回一个HttpResponseRedirect而不是常用的HttpResponse、HttpResponseRediect只接受一个参数:用户将要被重定向的URL。

  • revers()函数避免了在视图函数中硬编码的URL

对Question进行投票后,vote()视图将请求重定向到Question的结果界面。

# polls/views.py
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})

创建polls/results.html模板

# 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>
使用通用视图

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

步骤:

  • 转换URLconf
  • 删除一些旧的、不再需要的视图
  • 基于DJango的通用视图引入新的视图
改良URLconf

修改polls/urls.py

# polls/urls.py
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'),
]
改良视图

修改polls/views.py

# polls/views.py
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.

ListViewDetailView,这两个视图分别抽象显示一个对象列表和显示一个特定类型对象的详细信息页面这两个种概念。

  • 每个通用视图需要知道它将作用于哪个模型。由model属性提供。

  • DetailView期望从URL中捕获名为"pk"的主键值,所以要把通用视图question_id改为pk。

默认情况下,通用视图DetailView使用一个叫做<app name>/<model name>的模板,template_name属性是用来告诉Django使用一个指定的模板名字,而不是自动生成的默认名字。

同样ListView使用一个叫做<app name>/<model name>的模板。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值