python+html实现前后端数据交互界面显示

最近刚刚开始学习如何将python后台与html前端结合起来,现在写一篇blog记录一下,我采用的是前后端不分离形式。

话不多说,先来实现一个简单的计算功能吧,前端输入计算的数据,后端计算结果,返回结果至前端进行显示。

1.python开发工具

我选用的是pycharm专业版,因为社区版本无法创建django程序

2.项目创建

第一步:打开pycharm,创建一个django程序

蓝圈圈起来的为自定义的名字,点击右下角的create可以创建一个django项目

如下图,圈起来的名字与上图相对应

第二步:编写后端代码

①在blog文件夹下面的views.py中编写以下代码:

from django.shortcuts import render
from calculate import jisuan
# Create your views here.


def calculate(request):
    return render(request, 'hello.html')


def show(request):
    x = request.POST.get('x')
    y = request.POST.get('y')
    result = jisuan(x, y)
    return render(request, 'result.html', {'result': result})

②在csdn文件夹下面的urls.py中添加下面加粗部分那两行代码

from django.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('jisuan/', views.calculate),
    path('getdata/', views.show)
]

③新建calculate.py文件,内容为:

def jisuan(x, y):
    x = int(x)
    y = int(y)
    return (x+y)

第三步:编写前端代码

①数据输入的页面hello.html,内容为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" action="/getdata/">
    {% csrf_token %}
    <input type="text" name="x" placeholder="请输入x"/><br>
    <input type="text" name="y" placeholder="请输入y"><br>
    <input type="submit" value="进行计算">
</form>

</body>
</html>

②结果返回的页面result.html,内容为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 style="color:blue">计算结果为{{ result }}</h1>
</body>
</html>

第四步:启动后台程序

在浏览器地址栏输入http://127.0.0.1:8000/jisuan

回车可进入数据输入页面

我们输入x=10, y=20

点击进行计算按钮,页面跳转,显示计算结果

 

 好啦,一个简单的django项目就完成啦

如果想要进行复杂的计算操作,可以在calculate.py编写更加复杂的函数

源码资源链接:django学习,前后端不分离-Python文档类资源-CSDN文库https://download.csdn.net/download/thzhaopan/84989809

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>