Django 表单:对象没有属性清理数据

Django forms: object has no attribute cleaned data

我是 Django 的新手。当我尝试使用 form.cleaned_data 时出现此错误。我在网上查过的所有地方都说这是因为您可能没有使用我正在使用的 is_valid 功能。我的 objective 是创建一组记录,将学生 ID 和主题 ID 作为外键存储在名为 Sub_and_stu 的模型中。我对实现此目标的任何其他(简单?)方法持开放态度。

views.py

@csrf_protect
def select_subs(request):
   form1 = Sub_selection1(request.POST)
   form2 = Sub_selection2(request.POST)
   form3 = Sub_selection3(request.POST)
   form4 = Sub_selection4(request.POST)
   user = request.user

   if form1.is_valid  and form2.is_valid and form3.is_valid and form4.is_valid:
       data1 = form1.cleaned_data
       sub1=data1['subject_id']
       Sub_and_stu.objects.create(student_id=user,subject_id=sub1)
       data2 = form2.cleaned_data
       sub2=data2['subject_id']
       Sub_and_stu.objects.create(student_id=user,subject_id=sub2)
       data3 = form3.cleaned_data
       sub3=data3['subject_id']
       Sub_and_stu.objects.create(student_id=user,subject_id=sub3)
       data4 = form4.cleaned_data
       sub4=data4['subject_id']
       Sub_and_stu.objects.create(student_id=user,subject_id=sub4)


   context={'form1':form1,'form2':form2,'form3':form3,'form4':form4}
   return render(request,'select_subs.html',context)

models.py

class Subject(models.Model):                       
   subject_id=AutoSlugField(unique=True)
   name = models.CharField(max_length=50)

   def __str__(self):
       return self.name

class Sub_and_stu(models.Model):
    record_id=AutoSlugField(unique=True)
    student_id=models.ForeignKey(User,on_delete=models.CASCADE)
    subject_id=models.ForeignKey(Subject,on_delete=models.CASCADE)

class Sub_and_teachers(models.Model):
   record_id=AutoSlugField(unique=True)
   teacher_id=models.ForeignKey(User,on_delete=models.CASCADE)
   subject_id=models.ForeignKey(Subject,on_delete=models.CASCADE)

forms.py

class Sub_selection1(ModelForm):
class Meta:
    model = Sub_and_stu
    fields=['subject_id']
#Other subject selection forms are basically a copy of this. I need the user to pick multiple subejcts at the same time

来自 select_subs.html

的片段
<form>
{%csrf_token%}
<h3>Subject 1</h3>
{% render_field form1.subject_id class='pure-input-1 pure-input-rounded'  }
<h3>Subject 2</h3>
{% render_field form2.subject_id class='pure-input-1 pure-input-rounded'  }
<h3>Subject 3</h3>
{% render_field form3.subject_id class='pure-input-1 pure-input-rounded'  }
<h3>Subject 4</h3>
{% render_field form4.subject_id class='pure-input-1 pure-input-rounded'  }
<button type="submit" class="pure-button pure-button-primary" 
name='subjects'>Submit</button>
</form>

你应该用括号调用 is_valid()

现在你只是检查是否有一个属性 is_valid,方法的存在意味着它是 True。

is_valid是方法

is_valid() 括号是您调用该方法以实际查看表单是否有效的方式。当您调用该方法时,它会为您生成 cleaned_data

您可以在文档 https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form.is_valid

中阅读有关 is_valid 方法的更多信息