Django5 -----表单与通用视图系统

(一). HTML表单

现在admin.py文件下加一行代码,把choice注册进去

admin.site.register(Choice)

然后打开网页,增加三个Choice选项
在这里插入图片描述
然后修改poll/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>

具体的内容可以去学习H5前端知识,接下来创建一个视图来处理一波表单的信息。

def vote(request, question_id):
    question = get_object_or_404(Question, id=question_id)
    try:
        selected_choice = question.choice_set.get(id=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'poll/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,)))

修改results的视图和results.html

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

<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 'poll:detail' question.id %}">Vote again?</a>

到现在为止,一个简单的投票系统就做好了,打开页面。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

因为我试过几次,所以次数是10,第一次进入这个页面应该就一次。

(二).通用视图系统

我们观察detial()和results()这两个视图可以发现,十分的相似,因此Django提供了一个通用视图系统(generic views system)来提高编代码效率。

(1). 修改polls/url.py

from django.urls import path
from . import views


app_name = 'poll'
urlpatterns = [
    path('', views.index, 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). 修改polls/views.py

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

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


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


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

(三).自动化测试

在软件正式上线前都应该进行测试,确保软件的质量。随着现代软件规模的越来越庞大,业务逻辑越来越复杂,因此自动化测试成了必不可少的工具。

(1). 第一个测试案例

在poll/tests.py添加如下代码:

import datetime

from django.test import TestCase
from django.utils import timezone

from .models import Question


class QuestionModelTests(TestCase):

    def test_was_published_recently_with_future_question(self):
        """
        was_published_recently() returns False for questions whose pub_date
        is in the future.
        """
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

在命令行输入以下命令:

python3 manage.py test poll

就会发现出现了一个fail
在这里插入图片描述
这时候发现前面代码中存在bug,即当 pub_date 为未来某天时, Question.was_published_recently() 应该返回 False,实际却返回True。
因此,我们需要修改was_published_recently()这个方法,如下:

    def was_published_recently(self):
        now = timezone.now()
        return now + datetime.timedelta(days=-1) <= self.pub_date <= now
        

重新执行测试案例,就会发现在这里插入图片描述
诶,变成了OK,说明通过了测试

(2). 边界性测试

因为这个问卷给的限制条件是"一天内发布的问卷",因此边界性条件就是”比前一天早一秒“和"比前一天晚一秒“。
添加两个测试方法:

def test_was_published_recently_with_old_question(self):
        """
        was_published_recently() returns False for questions whose pub_date
        is older than 1 day.
        """
        time = timezone.now() - datetime.timedelta(days=1, seconds=1)
        old_question = Question(pub_date=time)
        self.assertIs(old_question.was_published_recently(), False)

    def test_was_published_recently_with_recent_question(self):
        """
        was_published_recently() returns True for questions whose pub_date
        is within the last day.
        """
        time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
        recent_question = Question(pub_date=time)
        self.assertIs(recent_question.was_published_recently(), True)
        

再次运行命令行,发现返回OK。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WFForstar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值