无法分配 - 必须是实例

时间:2016-03-02 18:32:33

标签: django django-models django-forms

我的django应用程序中有以下表格。我覆盖了构造函数,因此我可以限制字段'类中出现的选择。这样只会出现学生注册的课程。

#forms.py
class TestForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(TestForm, self).__init__(*args, **kwargs)
        classes = [Classes.objects.filter(students__username=self.user.username)]
        class_list = list()
        for c in classes:
            for single_class in c:
                cl = Classes.objects.get(id=single_class.id)
                class_list.append([cl, single_class])
        self.fields['classes'] = forms.ChoiceField(choices=class_list)

    class Meta:
        model = Test
        fields = ('classes', 'name')

但是,这样做会给我一个不能分配" Class1234:测试类" - " Test.classes"必须是一个"课程"实例。当我打印class_list时,我得到了这个:

[[<Classes: Class1234: Test class>, <Classes: Class1234: Test class>],[<Classes: Testing: 2nd class>, <Classes: Testing: 2nd class>],[<Classes: 3rd: Class>, <Classes: 3rd: Class>]]

对我来说,这看起来像实际的课堂对象,所以我不明白为什么这不起作用。作为参考,这是我的模型和视图:

#models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    teacher = models.BooleanField(default=False)

    def __str__(self):
        return "{0} {1}".format(self.user.first_name, self.user.last_name)


class Classes(models.Model):
    classcode = models.CharField(max_length=15)
    classname = models.TextField()
    students = models.ManyToManyField(User)

    def __str__(self):
        return "{0}: {1}".format(self.classcode, self.classname)


class Test(models.Model):
    classes = models.ForeignKey(Classes, on_delete=models.CASCADE)
    name = models.TextField(max_length=100)
    points = models.ManyToManyField(User, default=0)

    def __str__(self):
        return "{0}".format(self.name)

#views.py
def add_test(request):
    added = False
    form = TestForm(user=request.user)
    if request.method == "POST":
        form = TestForm(request.POST, user=request.user)
        if form.is_valid():
            form.save()
            added = True
    return render(request, 'site/addtest.html', {'form': form, 'added': added})

1 个答案:

答案 0 :(得分:1)

[[<Classes: Class1234: Test class>, <Classes: Class1234: Test class>],[<Classes: Testing: 2nd class>, <Classes: Testing: 2nd class>],[<Classes: 3rd: Class>, <Classes: 3rd: Class>]]

这是列表清单,这可能是它失败的原因。但无论如何,你的问题有一个更优雅的解决方案。

无需在__init__中执行此操作。只需覆盖表单中的classes字段并定义查询集即可。阅读更多相关信息here

如果这也是应该在数据库级别应用的限制,请考虑使用limit_choices_to。阅读它here