这是我的forms.py
的一部分class SubjectForm(forms.ModelForm):
title=forms.CharField(label='',widget=forms.TextInput(attrs={'maxlength':150,
'placeholder':'Write here. . .'}))
body=forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder':'Extend here. . .'}))
board=forms.ModelChoiceField(label='',queryset=Board.objects.all(), empty_label='Select Board')
class Meta:
model = Subject
fields = ('title','body','board')
现在它在板表单字段中呈现所有Board对象,但我想只呈现用户订阅的那些板。如何让用户获得表单并进行操作?
答案 0 :(得分:2)
forms.py:
class SubjectForm(forms.ModelForm):
title=forms.CharField(label='',widget=forms.TextInput(attrs={'maxlength':150,
'placeholder':'Write here. . .'}))
body=forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder':'Extend here. . .'}))
board=forms.ModelChoiceField(label='',queryset=Board.objects.all(), empty_label='Select Board')
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(SubjectForm, self).__init__(*args, **kwargs)
if user is not None:
self.fields['board'].queryset = Board.objects.filter(user=user)
class Meta:
model = Subject
fields = ('title','body','board')
views.py:
使用CreateView进行演示:
class SubjectCreateView(CreateView):
form_class = SubjectForm
template_name = 'subject/create.html'
success_url = '/'
def get_form_kwargs(self):
kwargs = super(SubjectCreateView, self).get_form_kwargs()
if self.request.method == 'GET':
kwargs.update({
'user': self.request.user,
})
return kwargs
或
form = SubjectForm(**{'user': request.user})