提交了表单后,我们需要从获取表单中的数据
#views.py
def index(request):
if request.method == "GET":
nameform = NameModelForm()
return render(request, "form/index.html",locals())
if request.method == "POST":
nameform = NameModelForm(request.POST)
if nameform.is_valid():
firstname = nameform.cleaned_data["firstname"]
secondname = nameform.cleaned_data["secondname"]
a = Name(firstname = firstname,secondname = secondname)
a.save()
print(firstname+secondname)
return HttpResponse("提交成功")
else:
error_msg = nameform.errors.as_json()
print(error_msg)
return HttpResponse(error_msg)
首先引入了自定义的表单类
如果request.method == “GET”
然后实例化表单类,render返回
如果request.method == “POST”
就先实例化接受了POST消息的表单类
如果表单类的数据是可获取的
我们使用一个变量接收nameform.cleaned.cleaned_data[“firstname”],就是从表单的firstname字段获取的信息。然后提交给数据库。这样就完成了一次提交记录表单的操作。