Django(5)-视图函数和模板渲染

Django 中的视图的概念是「一类具有相同功能和模板的网页的集合」
在我们的投票应用中,我们需要下列几个视图:

问题索引页——展示最近的几个投票问题。
问题详情页——展示某个投票的问题和不带结果的选项列表。
问题结果页——展示某个投票的结果。
投票处理器——用于响应用户为某个问题的特定选项投票的操作。
在 Django 中,网页和其他内容都是从视图派生而来。每一个视图表现为一个 Python 函数(或者说方法,如果是在基于类的视图里的话)。Django 将会根据用户请求的 URL 来选择使用哪个视图

添加视图

polls/view.py

def detail(request, question_id):return HttpResponse("You're looking at question %s." % question_id)def results(request, question_id):response = "You're looking at the results of question %s."return HttpResponse(response % question_id)def vote(request, question_id):return HttpResponse("You're voting on question %s." % question_id)

这段代码是一个基本的 Django 视图函数,它接受一个 HTTP 请求对象 request 和一个 question_id 参数,然后返回一个 HTTP 响应。

  • HttpResponse 是 Django 提供的一个用于构建 HTTP 响应的类。
  • response 是一个字符串,其中包含了一个占位符 %s,用于展示 question_id 的值。
  • 通过 % 运算符,将 question_id 的值插入到 response 字符串中,形成最终的响应内容。
  • 最后,用 return 语句返回该响应对象。

添加url

polls/urls.py

from django.urls import path
from . import views
urlpatterns=[path("",views.index,name="index"),path("<int:question_id>/",views.detail,name="detail"),path("<int:question_id>/results",views.detail,name="detail"),path("<int:question_id>/vote",views.detail,name="detail"),
]

运行并访问

在这里插入图片描述
每个视图必须要做的只有两件事:返回一个包含被请求页面内容的 HttpResponse 对象,或者抛出一个异常,比如 Http404 。至于你还想干些什么,随便你。

你的视图可以从数据库里读取记录,可以使用一个模板引擎(比如 Django 自带的,或者其他第三方的),可以生成一个 PDF 文件,可以输出一个 XML,创建一个 ZIP 文件,你可以做任何你想做的事,使用任何你想用的 Python 库。

Django 只要求返回的是一个 HttpResponse ,或者抛出一个异常。

获取最近5个投票问题

修改视图,在index() 函数里插入了一些新内容,让它能展示数据库里以发布日期排序的最近 5 个投票问题,以空格分割
polls/view.py

from django.http import HttpResponsefrom .models import Questiondef index(request):latest_question_list = Question.objects.order_by("-pub_date")[:5]output = ", ".join([q.question_text for q in latest_question_list])return HttpResponse(output)# Leave the rest of the views (detail, results, vote) unchanged

在这里插入图片描述

使用模板

创建文件polls/templates/polls/index.html

{% if latest_question_list %}<ul>{% for question in latest_question_list %}<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>{% endfor %}</ul>
{% else %}<p>No polls are available.</p>
{% endif %}

修改polls/view.py中index函数

from django.http import HttpResponse
from django.template import loaderfrom .models import Questiondef index(request):latest_question_list = Question.objects.order_by("-pub_date")[:5]template = loader.get_template("polls/index.html")context = {"latest_question_list": latest_question_list,}return HttpResponse(template.render(context, request))

载入 polls/index.html 模板文件,并且向它传递一个上下文(context)。这个上下文是一个字典,它将模板内的变量映射为 Python 对象
也可以直接使用render方法,该方法将模板渲染。

from django.shortcuts import renderfrom .models import Questiondef index(request):latest_question_list = Question.objects.order_by("-pub_date")[:5]context = {"latest_question_list": latest_question_list}return render(request, "polls/index.html", context)

latest_question_list 为对象列表,传给模板后,模板取出对象中的信息
查看效果
在这里插入图片描述
点击名称进入详情
在这里插入图片描述

抛出404错误

当访问到不存在的id时,可以抛出404错误
polls/view.py

from django.http import Http404
from django.shortcuts import renderfrom .models import Question# ...
def detail(request, question_id):try:question = Question.objects.get(pk=question_id)except Question.DoesNotExist:raise Http404("Question does not exist")return render(request, "polls/detail.html", {"question": question})

创建polls/templates/polls/detail.html

{{ question }}

在这里插入图片描述

快捷函数get_object_or_404

尝试用 get() 函数获取一个对象,如果不存在就抛出 Http404 错误也是一个普遍的流程

from django.shortcuts import get_object_or_404, renderfrom .models import Question# ...
def detail(request, question_id):question = get_object_or_404(Question, pk=question_id)return render(request, "polls/detail.html", {"question": question})

表单处理

poll/templates/polls/detailhtml

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

这个模板页面包含表单form,
添加url
polls/urls.py

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

polls/view.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reversefrom .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 += 1selected_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,)))from django.shortcuts import get_object_or_404, renderdef results(request, question_id):question = get_object_or_404(Question, pk=question_id)return render(request, "polls/results.html", {"question": question})

如果id不存在,返回404,如果存在,则对应问题选票+1,投票后跳转result页面
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>

在这里插入图片描述

选中选项,点击vote,进入results页面。
在这里插入图片描述
代码:https://github.com/2504973175/mysite_django/tree/main

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/57987.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SVN 项目管理笔记

SVN 项目管理笔记 主要是介绍 SVN 管理项目的常用操作&#xff0c;方便以后查阅&#xff01;&#xff01;&#xff01; 一、本地项目提交到SVN流程 在SVN仓库下创建和项目名同样的文件夹目录&#xff1b;选中本地项目文件&#xff0c;选择SVN->checkout,第一个是远程仓库项…

大数据Flink实时计算技术

1、架构 2、应用场景 Flink 功能强大&#xff0c;支持开发和运行多种不同种类的应用程序。它的主要特性包括&#xff1a;批流一体化、精密的状态管理、事件时间支持以及精确一次的状态一致性保障等。在启用高可用选项的情况下&#xff0c;它不存在单点失效问题。事实证明&#…

vue 学习笔记 简单实验

1.代码(html) <script src"https://unpkg.com/vuenext" rel"external nofollow" ></script> <div id"counter">Counter: {{ counter }} </div> <script> const Counter {data() {return {counter: 5}} } Vue.cr…

java-便签

--其实最痛的。不是离别。而是离别后的那些回忆。 java length( ) javalength中文占多长 1.一个中文字符或符号 2 个字节&#xff0c;一个英文字符或符号 1 个字节。 System.out.println("abc你好&#xff0c;".getBytes("gbk").length); System.out.pr…

【Linux】【驱动】驱动挂载的时候给驱动传递参数

【Linux】【驱动】驱动挂载的时候给驱动传递参数 绪论1.什么是驱动传参驱动传参就是传递参数给我们的驱动举例:2.驱动传参数有什么作用呢?3. 传递单个参数使用如下的数组4. 传递数组使用以下函数&#xff1a; 传递数字值代码指令 传递数组代码传递数组指令 绪论 1.什么是驱动…

C语言(第二十九天)

1.2.2 文件结构设计 之前学习了多文件的形式对函数的声明和定义&#xff0c;这里我们实践一下&#xff0c;我们设计三个文件&#xff1a; test.c //文件中写游戏的测试逻辑 game.c //文件中写游戏中函数的实现等 game.h //文件中写游戏需要的数据类型和函数声明等 2. 扫雷游戏的…

如何拼接两个视频在一起?

如何拼接两个视频在一起&#xff1f;在度过一个美好周末的时候&#xff0c;我和朋友一起拍摄了两组视频&#xff0c;准备将两个视频合并成一个并发布到朋友圈。这个想法非常棒&#xff0c;但是我在第一步就遇到了麻烦&#xff1a;如何将这两个视频拼接在一起&#xff1f;这听起…

Go 自学:struct结构体

以下代码展示如何建立一个结构体struct。 我们可以使用%v查看结构体的详情。 package mainimport ("fmt" )func main() {Jeff : User{"Jeff", "Jeffgo.dev", true, 16}fmt.Println((Jeff))fmt.Printf("Jeff details are: %v\n", Jeff…

7天GMV达220万美元!TikTok Shop爆品榜出炉。

7天GMV达220万美元&#xff01;TikTok Shop爆品榜出炉 8月28日消息&#xff0c;据跨境指南联合TikTok数据分析平台EchoTik发布的数据&#xff0c;监测了上周TikTok Shop印尼、马来西亚、泰国、美国市场GMV前10的商品。上周在印尼市场GMV排名前10的商品中&#xff1a;FREE ONGK…

RPA是什么样的机器人技术?RPA可以实现哪些流程的自动化?

一、RPA是什么样的机器人技术&#xff1f; RPA&#xff08;Robotic Process Automation&#xff09;即机器人流程自动化&#xff0c;是一种通过模拟人类在计算机系统上的操作&#xff0c;实现流程自动化的技术。RPA机器人可以代替人工执行各种重复性任务&#xff0c;如数据输入…

基于微服务、Java、Springcloud、Vue、MySQL开发的智慧工地管理系统源码

智慧工地聚焦施工现场岗位一线&#xff0c;围绕“人、机、料、法、环”五大要素&#xff0c;数字化工地平台与现场多个子系统的互联实现了工地业务间的互联互通和协同共享。数字化工地管理平台能够盘活工地各大项目之间孤立的信息系统&#xff0c;实现数据的统一接入、处理与维…

【Spring Boot】Spring Boot实现完整论坛功能示例代码

以下是一个简单的Spring Boot论坛系统示例代码&#xff1a; 首先是数据库设计&#xff0c;我们创建以下几张表&#xff1a; user表&#xff0c;存储用户信息&#xff0c;包括id、username、password、email、create_time等字段。topic表&#xff0c;存储帖子信息&#xff0c;…

迅睿系统二开自定义函数和插件的自定义函数

全局的自定义函数&#xff1a; 全局的自定义函数文件&#xff1a;dayrui/My/Helper.php 此文件用于放网站自定义函数&#xff0c;程序会自动加载 当前站点的自定义函数文件&#xff1a;网站主目录/config/custom.php 插件的自定义函数&#xff1a; 基于App目录下的插件或模块…

辉瑞乡村振兴战略下传统村落文化旅游设计小红书中美德少许

辉瑞乡村振兴战略下传统村落文化旅游设计小红书中美德少许

你会使用druid数据库连接池吗???

1.下载架包。下载地址&#xff1a;https://note.youdao.com/ynoteshare/index.html?id61e2cc939390acc9c7e5017907e98044&typenote&_time1693296531722 2.将架包加入项目文件。 创建一个lib目录&#xff0c;将架包复制进去 右键点击lib目录&#xff0c;将其添加为库。…

前端 -- 基础 VSCode 工具生成骨架标签新增代码 解释详解

目录 文档类型声明标签 Lang 语言种类 字符集 文档类型声明标签 <!DOCTYPE> 文档类型声明&#xff0c;作用就是告诉浏览器 当前的页面是 使用哪种 HTML 版本 来显示的网页 HTML 版本也很多呀 &#xff0c;比如 &#xff1a; HTML5 ,HTML4&#xff0c;XHTML 等…

【infiniband】rdma-core中的ibmad_port结构体

ibmad_port在rdma-core\libibmad\mad_internal.h文件中定义的结构体是&#xff1a; struct ibmad_port { int port_id; /* file descriptor returned by umad_open() */ int class_agents[MAX_CLASS]; /* class2agent mapper */ int timeout, retries; …

自动化PLC工程师能否转到c#上位机开发?

成功从自动化PLC工程师转向C#上位机开发的经历可能因人而异&#xff0c;以下是一些分享的思路和建议&#xff1a;扩展编程技能&#xff1a;学习C#语言和相关的开发工具和框架&#xff0c;掌握语言的基础知识和常用的编程技巧。可以通过在线教程、培训课程、书籍等途径进行学习&…

vue3:使用:批量删除功能

场景&#xff1a;vue中使用el-table,常需要记住上一页所勾选的数据&#xff0c;批量删除操作&#xff0c;或者弹窗分页勾选&#xff0c;进行第一页勾选&#xff0c;在调后端接口选择第二页勾选其他数据。 1、element-ui 的table表格可以轻松实现多选的功能&#xff0c;只要在表…

一文速学-让神经网络不再神秘,一天速学神经网络基础-前向传播(三)

前言 思索了很久到底要不要出深度学习内容&#xff0c;毕竟在数学建模专栏里边的机器学习内容还有一大半算法没有更新&#xff0c;很多坑都没有填满&#xff0c;而且现在深度学习的文章和学习课程都十分的多&#xff0c;我考虑了很久决定还是得出神经网络系列文章&#xff0c;…