最近在学习Django后台开发,以一个简单的页面来记录一下知识点
1、创建Django项目
项目结构如下
配置服务器
2、views.py文件
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render
# 计算器
def test_mycount(request):
if request.method == 'GET':
return render(request,'computer.html')
elif request.method == 'POST':
#处理计算
x = int(request.POST['x'])
y = int(request.POST['y'])
op = request.POST['op']
result = 0
if op == 'add':
result = x + y
elif op == 'sub':
result = x - y
elif op == 'mul':
result = x * y
elif op == 'div':
result = x / y
return render(request,'computer.html',locals()) #locals()表示将原本请求的数据重新返回
3、urls.py文件
from django.contrib import admin
from django.urls import path
from djangoProject import views
urlpatterns = [
path('admin/', admin.site.urls),
path('count',views.test_mycount)
]
4、html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算器</title>
</head>
<body>
<form action="/count" method="post">
<input type="text" name="x" value="{{ x }}">
<select name="op">
<option value="add" {% if op == 'add' %}selected{% endif %}>+加</option>
<option value="sub" {% if op == 'sub' %}selected{% endif %}>-减</option>
<option value="mul" {% if op == 'mul' %}selected{% endif %}>*乘</option>
<option value="div" {% if op == 'div' %}selected{% endif %}>/除</option>
</select>
<input type="text" name="y" value="{{ y }}">=
<span>{{ result }}</span>
<div><input type="submit" value="开始计算"></div>
</form>
</body>
</html>
5、运行结果