Django 2021年最新版教程6前台传递数据到后台处理 POST方法

Posted 软件工程小施同学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django 2021年最新版教程6前台传递数据到后台处理 POST方法相关的知识,希望对你有一定的参考价值。

 

1. 前台add.html

<!DOCTYPE html>
<html>
<body>
<p>请输入两个数字</p>
<form action="/doadd" method="post">
    {%csrf_token%}
    a: <input type="text" name="a"> <br>
    b: <input type="text" name="b"> <br>
    <input type="submit" value="提交">
</form>
</body>
</html>

一定要在html页面的form标签下加上

{%csrf_token%}

否则会报下面的错

2.后台views.py

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, './userWeb/index.html')

# 加法页面
def add(request):
    return render(request, './userWeb/add.html')

# 执行加法
def doadd(request):
    a = request.POST['a']
    b = request.POST['b']
    a = int(a)
    b = int(b)
    result = a + b
    return HttpResponse(str(result))

3. 将页面路径添加到urls.py

    path("add", add),
    path("doadd", doadd),

4. 效果

 

 

 

 

 

以上是关于Django 2021年最新版教程6前台传递数据到后台处理 POST方法的主要内容,如果未能解决你的问题,请参考以下文章