项目结构:
URL文件内容:
from django.contrib import admin from django.urls import path from django.conf.urls import url; from formdemo import views urlpatterns = [ #path('admin/', admin.site.urls), url(r'admin/$', admin.site.urls), url(r'^$', views.index), url(r'^add/',views.add ), ]
View文件内容
from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'index.html') def add(request): a = request.GET['a'] b = request.GET['b'] a = int(a) b = int(b) result = str(a+b) return render(request,'index.html',context={'var1': result,'a':a,'b':b}) #return HttpResponse(str(a + b))
模板内容
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>请输入两个数字</p> <form action="/add/" method="get"> 数1: <input type="text" name="a" value="{{ a }}"> <br> 数2: <input type="text" name="b" value="{{ b }}"> <br> 结果:<input type="text" name="c" value="{{ var1 }}"> <br> <input type="submit" value="提交"> </form> </body> </html>
结果: