当前位置: 首页 > news >正文

Django 入门学习总结5

修改polls/detail.html文件,写一个表单:

<form action="{% url 'polls:vote' question.id %}" method="post">
    {% csrf_token %}
    <fieldset>
        <legend><h1>{{ question.question_text }}</h1></legend>
        {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
        {% 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 %}
    </fieldset>
    <input type="submit" value="Vote">
    </form>

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

和结果方法:

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

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"

可以重新在网址上测试下。

http://www.lryc.cn/news/240240.html

相关文章:

  • FileNotFoundError: [Errno 2] No such file or directory: ‘patchelf‘: ‘patchelf‘
  • 『new Date 在 IOS 失效 の bug』
  • macos创建xcframework及签名
  • Oracle与Redis Enterprise协同,作为企业缓存解决方案
  • 局部保持投影(Locality preserving projections,LPP)
  • Flutter:引领移动开发新潮流,跨平台应用程序的终极解决方案
  • 开源免费的流程设计器如何选型
  • 设置pdb自动启动
  • 抖店入驻成功后,新手需要怎么做?7天起店流程教会你!
  • RTS 客户端-服务器网络
  • python连接数据库的方式
  • 【腾讯云云上实验室-向量数据库】探索腾讯云向量数据库:全方位管理与高效利用多维向量数据的引领者
  • 二、sql手工注入
  • day61 layui和分页原理
  • Rust开发——变量、静态变量与常量
  • javascript Math相关计算取值属性方法
  • git reset hard,mixed,soft
  • Cookie与Session知识
  • Vue批量全局处理undefined和null转为““ 空字符串
  • 【2023年APMCM亚太杯C题】完整数据与解题思路
  • 嵌入式单片机方向和Linux驱动开发方向哪个发展前景好?
  • 如何搭建Zblog网站并通过内网穿透将个人博客发布到公网
  • 2:kotlin集合(Collections)
  • 小诺2.0开源版工程启动
  • idea手动导入maven包
  • 2、单片机及开发板介绍
  • Leetcode 第 372 场周赛题解
  • mysql查询统计最近12个月的数据
  • 14.Python 模块
  • 三十分钟学会Linux的基本操作