Django基础4-表单和通用视图

写一个简单的表单

我们更一下上一节的投票详情模版 (“polls/detail.html”) , 新的模版包含一个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>
****个人心得**
此时你可能会想运行一下看看效果,但是你肯定看不到预期的效果,因为我们还没有为具体的问题添加选项,这必须在后台管理页面进行。这里就感觉这系列教程多少有点不合理,应该先将后台做一些数据上的完善比较好。
我做到这里就卡住了,看不到预期效果,还以为自己写的代码有问题,尝试了好多次都没用,最终才发现问题所在,然后跳去第七节教程,学习和处理了后台管理这部分之后,一切都OK了。

现在,我们可以创建处理和提交数据的视图了。我们在教程3中为polls应用创建了一个URLconf,包含下面的一行代码:

path('<int:question_id>/vote/', views.vote, name='vote'),

我们还 创建了一个vote()函数。这里,我们来完善其功能。添加如下代码:

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

在某个问题中投了票之后,vote()视图会重定向到结果页面。让我们来写这个视图:

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 模版:

<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>

使用通用视图

到目前为止,我们的detail()、results()和 index() 都是非常简单的。
这些视图代表了一个基本的web开发案例:根据URL中传递的参数,从数据库获取数据,加载模版,然后返回渲染后的模版。因为这非常通用,Django提供了一个快捷的处理方式,叫做“通用视图”系统。

通用视图将通用的模式抽象出来,你设置不需要写任何python代码。
让我们将poll应用转换为使用通用视图系统,这样我们可以删除一堆代码了。我们必须按以下步骤来做此转换:

  • 转换URLconf。
  • 删除无用的视图.
  • 加入基于Django通用视图的新视图。

修改URLconf

首先, 打开polls/urls.py URLconf ,修改代码如下:

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

详情视图需要一个来自URL的主键值,叫做‘pk’,因此我们在使用通用视图时要将 question_id 改为 pk .

修改视图

接下来,我们来移除原来的index,detail和results视图,并且使用Django通用视图代替它们。打开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.

更多关于通用视图的内容,参见“通用视图文档”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值