表格不生成/形成is_valid = 0表示无线电输入表格

时间:2017-08-05 22:28:18

标签: python html django forms

我正在撰写一份使用无线电输入进行的调查。在CMD中,每次点击无线电输入都会在request = POST时产生,但是form.is_valid为false,因为没有按下所有必需的按钮。我已经改变它现在没有任何作用,它现在甚至都不会要求。

以下是我的代码:

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})

Intro.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>  

提前致谢!

1 个答案:

答案 0 :(得分:0)

form_class = introForm(request.POST)

您已将此变量命名为form_class而非form。您应该将其命名为与else语句中的表单相同,以便您可以实现所需的功能。此外,它应该是if语句中的第一行,如下所示:

if request.method == 'POST':
    form = introForm(request.POST)
    if form.is_valid():
        ....

您是否正在使用模板中的表单标签......

{{ introForm }}