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

devtools/2024/10/19 23:35:29/

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

一、重定向
二、表单提交

先看第一种方式,重定向

首先需要了解客户端发起请求的过程
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.ppmy.cn/devtools/34250.html

相关文章

力扣每日一题112:路径总和

题目 简单 给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径&#xff0c;这条路径上所有节点值相加等于目标和 targetSum 。如果存在&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 叶子节点 是…

QPS(Queries Per Second)和TPS(Transactions Per Second)的介绍和区别

QPS&#xff08;Queries Per Second&#xff09;和TPS&#xff08;Transactions Per Second&#xff09;是衡量计算系统性能的两个指标&#xff0c;它们分别代表了系统每秒可以处理的查询数和事务数。虽然这两个术语在某些情况下可以互换使用&#xff0c;但它们在技术上有所区别…

【软件开发规范篇】JAVA后端开发编程规范

作者介绍&#xff1a;本人笔名姑苏老陈&#xff0c;从事JAVA开发工作十多年了&#xff0c;带过大学刚毕业的实习生&#xff0c;也带过技术团队。最近有个朋友的表弟&#xff0c;马上要大学毕业了&#xff0c;想从事JAVA开发工作&#xff0c;但不知道从何处入手。于是&#xff0…

关于YOLO8学习(四)模型转换为ncnn

前文 关于YOLO8学习(一)环境搭建,官方检测模型部署到手机 关于YOLO8学习(二)数据集收集,处理 关于YOLO8学习(三)训练自定义的数据集 简介 本文将会讲解: (1)如何通过PyCharm,进行pt模型的转换,最后输出一个适合手机端使用的模型 开发环境 win10、python 3.11…

【机器学习】BK- SDM与LCM的融合策略在文本到图像生成中的应用

突破边缘设备限制&#xff1a;BK-SDM与LCM的融合策略在文本到图像生成中的应用 一、引言二、稳定扩散算法的挑战与现状三、BK-SDM与LCM的融合策略利用高质量图像-文本对进行训练为LCM量身定制高级蒸馏过程 四、结论与展望 一、引言 随着人工智能技术的飞速发展&#xff0c;文本…

安卓中常见的UI控件

TextView&#xff08;文本视图&#xff09;EditText&#xff08;编辑文本&#xff09;Button&#xff08;按钮&#xff09;ImageView&#xff08;图像视图&#xff09;ImageButton&#xff08;图像按钮&#xff09;CheckBox&#xff08;复选框&#xff09;RadioButton&#xff…

java里的i/o流

在Java中&#xff0c;I/O&#xff08;输入/输出&#xff09;流是用于处理输入和输出操作的抽象概念。Java的I/O库提供了许多类和方法&#xff0c;用于从各种来源&#xff08;如文件、网络、内存等&#xff09;读取数据&#xff08;输入流&#xff09;&#xff0c;以及将数据写入…

Python实战开发及案例分析(7)—— 排序算法

排序算法是计算机科学中的基础&#xff0c;用于将数据元素按照特定的顺序排列。Python 提供了多种方式来实现排序算法&#xff0c;包括内置的排序函数和手动实现各种经典排序算法。 Python 内置排序函数 Python 的内置函数 sorted() 和列表的 sort() 方法提供了高效的排序功能…