ValueError:无法分配“<classname:v =”“>”:“”Teachername.classname“必须是”Sectionname“实例

时间:2015-06-30 06:44:02

标签: django-models django-forms django-views

我的models.py:

class Classname(models.Model):  

    class_name = models.CharField(max_length=8) 

    def __str__(self):  
        return self.class_name  

class Sectionname(models.Model):  

    class_name = models.ForeignKey(Classname)  
    section_name = models.CharField(max_length=1, default='A')  
    def __str__(self):  
        return self.section_name  

class Teachername(models.Model):  
    classname = models.ForeignKey(Sectionname)
    secname = models.ForeignKey(Classname)  
    teachname = models.CharField(max_length=50)  
    def __str__(self):  
        return self.teachname  

my views.py:

def add_teach(request):  
    if request.method == 'POST':  
        form = TeachernameForm(request.POST)  
         if form.is_valid():  
            form.save()  
            return HttpResponseRedirect(reverse('student:listteach'))  
        else:  
            print(form.errors)  
    else:  
        form = TeachernameForm()  
    return render(request, 'add_teach.html', {'form': form},)  

my form.py:

class TeachernameForm(ModelForm):  
    classname = forms.ModelChoiceField(queryset=Classname.objects.all())  
    secname = forms.ModelChoiceField(queryset=Sectionname.objects.all())  
    class Meta:  
        model = Teachername  
        fields = ('classname', 'secname', 'teachname',)  

当我提交TeacherForm时。我收到了上述错误。我尝试了许多技巧,但没有得到解决方案。请有人建议我修复。

1 个答案:

答案 0 :(得分:0)

class Teachername(models.Model):  
    classname = models.ForeignKey(Sectionname)
    secname = models.ForeignKey(Classname) 

这应该是:

    classname = models.ForeignKey(Classname)
    secname = models.ForeignKey(Sectionname)