目录
- 前言
- 1.python开发工具
- 2.项目创建
- 总结
前言
最近刚刚开始学习如何将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.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})
③新建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学习,前后端不分离
总结
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)