在app目录下创建forms.py文件: from django import forms #导入相关模块 class AddForm(forms.Form): #必须继承forms.Form a = forms.EmailField() #电子邮箱格式 b = forms.GenericIPAddressField() #IP地址格式 url.py文件: urlpatterns = [ url(r‘^index/$‘, index), url(r‘^$‘, index), ] views.py文件: from django.shortcuts import render from django.http import HttpResponse from .forms import AddForm #导入forms里面定义的类 def index(request): if request.method == ‘POST‘: form = AddForm(request.POST) #form提交的数据 if form.is_valid(): #如果提交的数据合法 a = form.cleaned_data[‘a‘] #取出a里面包含的数据 b = form.cleaned_data[‘b‘] #取出b里面包含的数据 print a,b #打印a和b的内容 return HttpResponse(‘OK‘) #返回页面 elif request.method == ‘GET‘: form = AddForm() #调用指定forms类 return render(request, ‘index.html‘, {‘form‘: form}) #将定义的类传递给html页面 index.html文件: <body> <form method=‘POST‘ action="/app01/index/"> {% csrf_token %} {% for i in form %} #循环传递的forms {{ i }} #输出forms的内容 <br/> #换行 {% endfor %} #结束循环 <input type="submit" value="提交"> </form> </body>
时间: 2024-10-05 10:19:10