我正在写一个用无线电输入做的调查。在CMD中,每次单击无线电输入都会导致请求= POST,但是form.is_valid是假的,因为并非所有必需的按钮都被按下。我现在更改了它,没有任何效果,它现在甚至不会请求。
下面是我的代码:
forms.py
class introForm(forms.ModelForm):
class Meta:
model = Intro
fields = ['name','education','sex',]
models.py
class Intro(models.Model):
EDUCATION_CHOICES = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('G','Graduate'),
('P','Professor')
)
SEX_CHOICES = (
('M','Male'),
('F','Female'),
)
name = models.CharField(max_length = 10)
education = models.CharField(max_length = 1,choices = EDUCATION_CHOICES)
sex = models.CharField( max_length = 1, choices = SEX_CHOICES)
views.py
def get_User_Info(request):
#form_class = introForm(request.POST)
if request.method == 'POST':
if form_class.is_valid():
name = request.POST['name']
print(name)
sex = request.POST['sex']
education = request.POST['education']
intro.objects.create(
name = name,
sex = sex,
education = education
)
intro.save()
print (connection.queries)
return HttpResponseRedirect("/vote/") #Save data and redirect
else:
form = introForm()
return render(request, 'Intro.html', {'introForm': form})
简介.html#匆忙写,因为形式由于某种原因无法呈现自己...
<!-- Survey/templates/Intro.html -->
<!DOCTYPE html>
{% load staticfiles %}
<html>
<body>
<form action="" method="post" id = "introForm">
<p><label for="name">Name:</label>
<input id=name type="text" name="subject" maxlength="15" required /></p>
<p><label for="sex">Sex:</label>
<input type="radio" name="Sex" value="M" required>Male
<input type="radio" name="Sex" value="F" required>Female</p>
<p><label for="education">Education:</label>
<input type="radio" name="Education" value="1" required>1
<input type="radio" name="Education" value="2" required>2
<input type="radio" name="Education" value="3" required>3
<input type="radio" name="Education" value="4" required>4
<input type="radio" name="Education" value="G" required>Graduate
<input type="radio" name="Education" value="P" required>Professor</p>
</form>
<input type="submit" value="Next" id = "next"/>
</body>
</html>
提前感谢!
form_class = introForm(request.POST)
您已将此变量命名为 form_class 而不是 form。您应该将其命名为 else 语句中的表单,以便可以实现所需的功能。此外,它应该是 if 语句中的第一行,如下所示:
if request.method == 'POST':
form = introForm(request.POST)
if form.is_valid():
....
您是否像这样在模板中使用表单标签...
{{ introForm }}