在modelformset_factory中,属性未传递给modelform构造函数

时间:2016-03-03 16:38:23

标签: python django django-models django-forms

我有一个表单,我试图限制字段中显示的选项'问题' (在这种情况下,我只想要用户创建的问题)。这种方法与其他形式一起使用,但这次没有用 - 可能是因为它是ModelFormset而不仅仅是ModelForm

确切的错误是 - ' NoneType'对象没有属性'用户名' ,我怀疑这意味着'用户' object没有被传递给AnswerForm的构造函数。问题是,我不知道为什么没有通过

#views.py
def add_answer(request):
        a_form = modelformset_factory(Answer, form=AnswerForm(user=request.user), fields='__all__', min_num=2, max_num=4, validate_min=True)
        if request.method == "POST":
            form = a_form(request.POST)
            if form.is_valid():
                #Do something
        return render(request, 'site/addanswer.html', {'a_form': a_form})

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

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(AnswerForm, self).__init__(*args, **kwargs)
        self.fields['question'] = forms.ModelChoiceField(queryset=Question.objects.filter(user__username=self.user.username))

    class Meta:
        model = Answer
        fields = ('question', 'answer', 'correct')

#models.py
class Question(models.Model):
    user = models.ManyToManyField(User)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    question = models.TextField(max_length=1000)

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

class Answer(models.Model):
    question = models.ForeignKey(Question)
    answer = models.TextField(max_length=1000)
    correct = models.BooleanField()

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

1 个答案:

答案 0 :(得分:0)

self.user可能会覆盖super。此外,无需查询user.username

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

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(AnswerForm, self).__init__(*args, **kwargs)
        self.fields['question'] = forms.ModelChoiceField(queryset=Question.objects.filter(user=user))

    class Meta:
        model = Answer
        fields = ('question', 'answer', 'correct')