1
我有一個表單,我試圖限制出現在字段'問題'(在這種情況下,我只想要用戶創建的問題)的選擇。這種方法與其他形式的工作,但它不工作這一次 - 可能是因爲它是一個ModelFormset,而不僅僅是一個的ModelForm屬性沒有被傳遞到modelform構造函數,當modelformset_factory
確切的錯誤是 - 「NoneType」對象有沒有屬性「用戶名」,我懷疑這意味着'用戶'對象沒有被傳遞給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)
沒有答案,但你爲什麼使用'user.username'? 'queryset = Question.objects.filter(user = self.user)'應該足夠了。 – ilse2005
也許'self.user'被'super'覆蓋。嘗試'user = kwargs.pop('user',None)''和'self.fields ['question'] = forms.ModelChoiceField(queryset = Question.objects.filter(user = user))' – ilse2005
@ ilse2005這很奏效,但現在它給了我一個不同的錯誤 - **'AnswerForm'對象沒有屬性'__name __'** – user2151557