models.py包含2个类,分别是ageGen()和group1()类,效果很好。
forms.py
from app1.models import ageGen,group1,group2,group3
from django import forms
class ageGenForm(forms.ModelForm):
class Meta():
model=ageGen
fields='__all__'
class group1form(forms.ModelForm):
class Meta():
model=group1
fields="__all__"
我想做的是.. ageGenForm将接受玩家的年龄和性别,然后将检查玩家18岁以上的天气。 如果他未满18岁,则必须填写一张表格,注明他的姓名和他想参加的比赛,并将这些数据存储在数据库中。
views.py
from django.shortcuts import render
from app1.forms import ageGenForm,group1form,group2form,group3form
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,'home.html')
def formpage(request):
form=ageGenForm()
if(request.method=='POST'):
form=ageGenForm(request.POST)
if(form.is_valid()):
age = form.cleaned_data['age']
if(age<=18):
return group1(request)
else:
return HttpResponse("adult category")
return render(request,'formpage.html',{'form':form})
def group1(request):
form=group1form()
if(request.method=='POST'):
form=group1form(request.POST)
if(form.is_valid()):
form.save()
return HttpResponse("thankyou!")
else:
return HttpResponse("invalid")
return render(request,'group1.html',{'form':form})
它呈现formpage.html,但不呈现group1.html。它返回形式无效!而且不会出现任何错误。
formpage.html和group1.html (两者具有相同的代码):
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>formpage</h1>
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="" value="SUBMIT">
</form>
</body>
</html>
答案 0 :(得分:0)
您不能直接从另一个视图调用一个视图。相反,您需要调用其网址。假设您有一个URL path,如下所示:
path('group1/', views.group1, name="group1")
然后从formpage
,您可以redirect到有效表单上的URL路径,如下所示(使用reverse
):
from django.shortcuts import redirect
from django.urls import reverse
def formpage(request):
form=ageGenForm()
if(request.method=='POST'):
form=ageGenForm(request.POST)
if(form.is_valid()):
age = form.cleaned_data['age']
if(age<=18):
return redirect(reverse('group1')) #<-- Redirecting to group1 view
else:
return HttpResponse("adult category")
return render(request,'formpage.html',{'form':form})