網站首頁 編程語言 正文
前言
最近剛剛開始學習如何將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學習,前后端不分離
總結
原文鏈接:https://blog.csdn.net/thzhaopan/article/details/123513504
相關推薦
- 2023-05-07 C語言中大小端問題實例探索解決方法_C 語言
- 2022-11-17 WPF利用DrawingContext實現繪制溫度計_C#教程
- 2023-07-22 Spring的編程式事務TransactionTemplate
- 2024-03-24 MyBatis-Plus:條件構造器Wrapper
- 2022-05-01 Python類的定義和使用詳情_python
- 2022-07-16 Electron項目打包
- 2022-09-24 C#/VB.NET實現PPT或PPTX轉換為圖像功能_C#教程
- 2022-07-03 Python基礎教程之錯誤和異常的處理方法_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支