Django中如何让页面之间建立关系

今天给大家讲解两种让页面建立联系的方式

一、重定向
二、表单提交

先看第一种方式,重定向

首先需要了解客户端发起请求的过程
1、客户端向服务端发起请求,比如请求地址是:http://127.0.0.1:8000/lili/submit/


2、程序根据路由找到视图函数
3、执行视图函数,比如视图函数是要求打开submit.html
4、操作视图函数返回的html中的按钮,点击页面中 的按钮,如图


5、调用这个按钮绑定的方法,重点来了

在方法中这样写:

 window.location.href = 'http://127.0.0.1:8000/lili/result/'

查看图片:

6、加载新的代码,然后重新访问:http://127.0.0.1:8000/lili/submit/

7、点击submit这个按钮,这样就跳转成功了

二、表单提交
 

1、创建模型,代码如下

from django.db import models
from django.contrib.auth.models import Userclass Feedback(models.Model):quality = models.IntegerField('商品质量', default=1)attitude = models.IntegerField('客服态度', default=1)speed = models.IntegerField('物流速度', default=1)text = models.TextField('评论内容', max_length=150, default='')anonymous = models.BooleanField('是否匿名', default=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)name: str = "lili"objects: models.QuerySet  # 普通的属性

2、生成迁移脚本:

python .\manage.py makemigrations
python .\manage.py migrate    

3、编辑views.py,编写视频函数,代码如下
 

import json
import osfrom django.contrib.auth import login, logout
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.template.loader import render_to_string
from django.urls import reversefrom lili.models import Feedbackdef submit(request):if request.method == 'GET':html = open("submit.html", encoding="utf-8").read()return HttpResponse(html)elif request.method == 'POST':# 获取提交的表单数据data = json.loads(request.body)print(data)obj = Feedback()obj.quality = data.get('quality', 0)obj.attitude = data.get('attitude', 0)obj.speed = data.get('speed', 0)obj.text = data.get('text', '')obj.anonymous = data.get('anonymous', False)obj.save()request.session['feedback_data'] = datareturn JsonResponse({'status': 'success'})def result(request):html = open("result.html",encoding="utf-8").read()return HttpResponse(html)def submit_5524(request):if request.method == 'POST':data = json.loads(request.body)print(data)return JsonResponse({'status': 'success','data':data})html = open("submit.html",encoding="utf-8").read()return HttpResponse(html)

4、编辑html文件,通过这个文件实现先后端的交互,比如点击操作,以下是submit.py的示例代码

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" /><title>VForm Demo</title><link rel="stylesheet" href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/element-plus/2.0.4/index.min.css" /><link rel="stylesheet" href="https://ks3-cn-beijing.ksyun.com/vform3/render.style.css?t=20220129"><style type="text/css"></style>
</head>
<body><div id="app"><v-form-render :form-json="formJson" :form-data="formData" :option-data="optionData" ref="vFormRef"></v-form-render><el-button type="primary" @click="submitForm">Submit</el-button></div><script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/3.2.30/vue.global.min.js"></script>
<script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/element-plus/2.0.4/index.full.min.js"></script>
<script src="https://ks3-cn-beijing.ksyun.com/vform3/render.umd.js?t=20220129"></script>
<script>const { createApp } = Vue;const app = createApp({data() {return {formJson: {"widgetList":[{"key":40214,"type":"rate","icon":"rate-field","formItemFlag":true,"options":{"name":"quality","label":"商品质量","labelAlign":"","defaultValue":null,"columnWidth":"200px","labelWidth":null,"labelHidden":false,"disabled":false,"hidden":false,"required":false,"requiredHint":"","validation":"","validationHint":"","customClass":[],"labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"max":5,"lowThreshold":2,"highThreshold":4,"allowHalf":false,"showText":false,"showScore":false,"onCreated":"","onMounted":"","onChange":"","onValidate":""},"id":"rate73475"},{"key":40214,"type":"rate","icon":"rate-field","formItemFlag":true,"options":{"name":"attitude","label":"客服态度","labelAlign":"","defaultValue":null,"columnWidth":"200px","labelWidth":null,"labelHidden":false,"disabled":false,"hidden":false,"required":false,"requiredHint":"","validation":"","validationHint":"","customClass":"","labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"max":5,"lowThreshold":2,"highThreshold":4,"allowHalf":false,"showText":false,"showScore":false,"onCreated":"","onMounted":"","onChange":"","onValidate":""},"id":"rate59589"},{"key":40214,"type":"rate","icon":"rate-field","formItemFlag":true,"options":{"name":"speed","label":"物流速度","labelAlign":"","defaultValue":null,"columnWidth":"200px","labelWidth":null,"labelHidden":false,"disabled":false,"hidden":false,"required":false,"requiredHint":"","validation":"","validationHint":"","customClass":"","labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"max":5,"lowThreshold":2,"highThreshold":4,"allowHalf":false,"showText":false,"showScore":false,"onCreated":"","onMounted":"","onChange":"","onValidate":""},"id":"rate28142"},{"key":116462,"type":"input","icon":"text-field","formItemFlag":true,"options":{"name":"text","label":"评论","labelAlign":"","type":"text","defaultValue":"","placeholder":"","columnWidth":"200px","size":"","labelWidth":null,"labelHidden":false,"readonly":false,"disabled":false,"hidden":false,"clearable":true,"showPassword":false,"required":false,"requiredHint":"","validation":"","validationHint":"","customClass":"","labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"minLength":null,"maxLength":null,"showWordLimit":false,"prefixIcon":"","suffixIcon":"","appendButton":false,"appendButtonDisabled":false,"buttonIcon":"custom-search","onCreated":"","onMounted":"","onInput":"","onChange":"","onFocus":"","onBlur":"","onValidate":"","onAppendButtonClick":""},"id":"input110400"},{"key":25114,"type":"switch","icon":"switch-field","formItemFlag":true,"options":{"name":"anonymous","label":"是否匿名","labelAlign":"","defaultValue":false,"columnWidth":"200px","labelWidth":null,"labelHidden":false,"disabled":false,"hidden":false,"customClass":"","labelIconClass":null,"labelIconPosition":"rear","labelTooltip":null,"switchWidth":40,"activeText":"","inactiveText":"","activeColor":null,"inactiveColor":null,"onCreated":"","onMounted":"","onChange":"","onValidate":""},"id":"switch99841"}],"formConfig":{"modelName":"formData","refName":"vForm","rulesName":"rules","labelWidth":80,"labelPosition":"left","size":"","labelAlign":"label-left-align","cssCode":"","customClass":[],"functions":"","layoutType":"PC","jsonVersion":3,"onFormCreated":"","onFormMounted":"","onFormDataChange":""}},formData: {},optionData: {}}},methods: {submitForm() {this.$refs.vFormRef.getFormData().then( (formData) => {// Form Validation OK// alert( JSON.stringify(formData) )fetch('/lili/submit/',{method: 'POST',headers:{'Content-Type': 'application/json'},body: JSON.stringify(formData)}).then(data => {// document.open();// document.write(data.html);// document.close();window.location.href ='http://127.0.0.1:8000/lili/result/'})}).catch( function(error) {// Form Validation Failedalert(error)})}}});app.use(ElementPlus)app.use(VFormRender)app.mount("#app");
</script>
</body>
</html>

持续不断的总结输出,一定可以厚积薄发,如果觉得我的文章有帮助到你,望你关注,笔芯
 

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

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

相关文章

sqlserver中替换空格和换行

sqlserver 中换行符&#xff0c;如下&#xff1a; sql语句如下&#xff08;只是在window系统中&#xff09;&#xff1a; //替换换行-使用char(10)或者char(13) select REPLACE(F_CNKITitle ,char(10),) title from tzkj_CNKIContent tc where --F_CnkiContentID ffdc7412-41…

AI智剪新风尚:一键操作,批量视频剪辑轻松入门

随着科技的飞速进步&#xff0c;人工智能(AI)已逐渐渗透到我们生活的各个领域&#xff0c;其中&#xff0c;AI视频剪辑技术的出现&#xff0c;为视频制作带来了革命性的变革。如今&#xff0c;一键操作、批量处理的AI智剪正成为视频剪辑的新风尚&#xff0c;让剪辑工作变得前所…

Mysql进阶-索引篇

Mysql进阶 存储引擎前言特点对比 索引介绍常见的索引结构索引分类索引语法sql分析索引使用原则索引失效的几种情况sql提示覆盖索引前缀索引索引设计原则 存储引擎 前言 Mysql的体系结构&#xff1a; 连接层 最上层是一些客户端和链接服务&#xff0c;主要完成一些类似于连接…

访问网络附加存储:nfs

文章目录 访问网络附加存储一、网络附加存储1.1、存储类型1.3、通过NFS挂载NAS1.4、NFS挂载过程服务端客户端 二、实验&#xff1a;搭建NFS服务端及挂载到nfs客户端服务端客户端测试命令合集服务端客户端 访问网络附加存储 一、网络附加存储 1.1、存储类型 DAS&#xff1a;Di…

零代码编程:用Kimichat从PDF文件中批量提取图片

一个PDF文件中&#xff0c;有很多图片&#xff0c;想批量提取出来&#xff0c;可以借助kimi智能助手。 在借助kimi智能助手中输入提示词&#xff1a; 你是一个Python编程专家&#xff0c;要完成一个网页爬取Python脚本的任务&#xff0c;具体步骤如下&#xff1a; 打开文件夹…

2024年融资融券利率最新变化,又降低了?

最近有很多朋友在问我问融资融券的业务&#xff0c;都是比较关心这个利率的问题。确实&#xff0c;做融资融券最重要的利率&#xff0c;利率低会节省很大一笔资金&#xff0c;今天在这边给大家对接一个上市券商&#xff0c;可以给到大家万一的交易佣金和5%的融资利率&#xff0…

乡村振兴规划设计一站式资料大全,能为乡村振兴从业者带来什么帮助?

乡村振兴规划设计一站式资料大全对于乡村振兴从业者来说&#xff0c;具有非常重要的帮助作用。这种资料大全通常包含了从政策解读、市场分析、规划设计、到实施策略等各个方面的详尽信息&#xff0c;能够极大地提升从业者的工作效率和专业能力。 具体来说&#xff0c;乡村振兴规…

Python selenium

1.搭建环境 1.安装&#xff1a; pip install msedge-selenium-tools 不要使用pip install selenium&#xff0c;我的电脑上没法运行 2.下载驱动 Microsoft Edge WebDriver |Microsoft Edge 开发人员 edge浏览器点设置---关于即可找到版本号&#xff0c;一定要下载对应版…

实践精益理念:精益生产培训助力企业持续增长

在日益激烈的市场竞争中&#xff0c;企业如何寻找持续增长的动力&#xff0c;提升整体创新能力和核心竞争力&#xff1f;张驰咨询通过多年来的深入研究和实践&#xff0c;结合众多企业的实际情况&#xff0c;带来了精益生产培训的全新视角。 在近期举办的一次精益生产培训中&am…

五种算法(BWO、RUN、SO、HO、GWO)求解复杂城市地形下无人机路径规划,可以修改障碍物及起始点(MATLAB)

一、算法介绍 &#xff08;1&#xff09;白鲸优化算法BWO 参考文献&#xff1a;Zhong C, Li G, Meng Z. Beluga whale optimization: A novel nature-inspired metaheuristic algorithm[J]. Knowledge-Based Systems, 2022, 109215. &#xff08;2&#xff09;龙格-库塔优化…

服务器数据恢复—RAID5磁盘阵列两块盘离线的数据恢复过程

服务器故障&#xff1a; 服务器中有一组由多块硬盘组建的raid5磁盘阵列&#xff0c;服务器阵列中2块硬盘先后掉线导致服务器崩溃。 服务器数据恢复过程&#xff1a; 1、将故障服务器中所有磁盘编号后取出&#xff0c;由硬件工程师对掉线的两块磁盘进行物理故障检测&#xff0c…

二层交换机与路由器连通上网实验

华为二层交换机与路由器连通上网实验 二层交换机是一种网络设备&#xff0c;用于在局域网&#xff08;LAN&#xff09;中转发数据帧。它工作在OSI模型的第二层&#xff0c;即数据链路层。二层交换机通过学习和维护MAC地址表&#xff0c;实现了数据的快速转发和广播域的隔离。 实…

java数据结构之数组系统了解

1.数组介绍 数组就是一个存储数据的容器&#xff0c;容器的长度固定、存储元素的数据类型固定。 跟变量加以区分&#xff1a;变量也可以存储数据&#xff0c;但是只能存一个值。当要存的数据比较多的时候&#xff0c;用变量就不方便了。我们就可以使用数组来存储。 1.1数组…

并发编程实现

一、并行编程 1、Parallel 类 Parallel类是System.Threading.Tasks命名空间中的一个重要类&#xff0c;它提供数据并行和任务并行的高级抽象。 For和ForEach Parallel类下的For和ForEach对应着普通的循环和遍历(普通的for和foreach)&#xff0c;但执行时会尝试在多个线程上…

安防视频/视频汇聚系统EasyCVR视频融合云平台助力智能化酒店安防体系的搭建

一、背景需求 2024年“五一”假期&#xff0c;全国文化和旅游市场总体平稳有序。文化和旅游部6日发布数据显示&#xff0c;据文化和旅游部数据中心测算&#xff0c;全国国内旅游出游合计2.95亿人次。“五一”假期县域市场酒店预订订单同比增长68%&#xff0c;而酒店作为一个高…

SpringCloudAlibaba:4.3云原生网关higress的JWT 认证

概述 简介 JWT是一种用于双方之间传递安全信息的简洁的、URL安全的声明规范。 定义了一种简洁的&#xff0c;自包含的方法用于通信双方之间以Json对象的形式安全的传递信息&#xff0c;特别适用于分布式站点的单点登录&#xff08;SSO&#xff09;场景 session认证的缺点 1.安…

简单数据结构——栈和队列1(栈超全)(初始化,销毁,出栈入栈销毁实现,例题运用)

知识特点 类似数据表链表&#xff0c;在逻辑上依次存储&#xff0c;但对比顺序表和链表有所限制&#xff0c;不能随便存储 一定要先掌握顺序表的实现&#xff0c;本人博客有顺序表专栏大家可以自行查看&#xff0c;看懂顺序表专栏之后再来了解栈的实现会更容易懂。 如果还没…

使用DBeaver连接postgreSql提示缺少驱动

重新安装电脑之后用dbeaver链接数据库的时候&#xff0c;链接PG库一直提示缺少驱动&#xff0c;当选择下载驱动的时候又非常非常慢经常失败&#xff0c;尝试了一下更改源然后下载库驱动就非常快了&#xff0c;当然也包括dbeaver的自动更新。 方法&#xff1a;点击菜单栏【窗口…

闲来装个虚拟机Ubuntu24.04和硬盘分区及挂载

简述 最近ubuntu出新版本了&#xff0c;ubuntu24.04&#xff0c; 俗称高贵食蚁兽。5年前进行Android或者linux开发基本是在windows下的虚拟机中进行。目前&#xff0c;虽然物质基础提高了&#xff0c;功能有独立进行编译、代码管理的服务器了。可以通过ssh登录&#xff0c;但是…

Seata之AT 模式的使用

系列文章目录 文章目录 系列文章目录前言 前言 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站&#xff0c;这篇文章男女通用&#xff0c;看懂了就去分享给你的码吧。 Seata 是一款开源的…