由下面的两个路由我们可以知道最终网页的url是 localhost\web\hello,这个url关系到后面表单提交 action 的位置
from django.urls import path,include
urlpatterns = [
path('web/',include("web.urls")),
]
from django.urls import path
from . import views
urlpatterns=[
path('hello/',views.hello),
]
writeTo是我自己写的函数。将获取的文本数据写入了名为msg.txt的文件中。
from django.shortcuts import render,HttpResponse
def hello(request):
if request.method == "POST":
postInfo=request.POST.get("msgsend")
writeTo("msg.txt",postInfo)
return render(request,'hello.html')
hello.html from表单
<form action="/web/hello/" method="post">
{% csrf_token %}
<label>提交的信息</label> <input type="text" name="msgsend"/>
<br/>
<input type="submit" value="确认提交">
</form>
下面这段 Django模板语言 必须要有
{% csrf_token %}
否则会报错
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery,
or when Django's CSRF mechanism has not been used correctly. For POST forms,
you need to ensure:
...
确认提交后在项目根文件夹多了一个文件用于保存提交的信息
def hello(request):
dir={}
if request.method == "POST":
postInfo=request.POST.get("msgsend")
writeTo("msg.txt",postInfo)
if request.method == "GET":
with open("msg.txt","r") as file:
msg=file.readlines()
dir["msg"]=msg
return render(request,'hello.html',dir)
<form action="/web/hello/" method="get" >
<label>获取的信息</label>
<br/>
<h3>{{ msg }}</h3>
<br/>
<input type="submit" value="确认获取">
</form>
Django模板语言:
用大括号括起来的是一个变量 {{ msg }}
return render(request,‘hello.html’,dir)
将dir 字典信息传到HTML文件 渲染网页 展示在浏览器中。
字典的键 dir[“msg”] 就对应到form 表单中的 {{ msg}}变量
本文地址:https://blog.csdn.net/nemo_DTT/article/details/107136460
如对本文有疑问, 点击进行留言回复!!
【现代计算机图形学 GAMES101】 第五讲:光栅化(一)
4.unittest_生成测试报告(HTMLTestRunner)
oracle12c查看版本|oracle12c查看组件|oracle12c查看模式|基本使用|慎用CREATE [PLUGGABLE|NULL] DATABASE 创建数据库
网友评论