根据当前登录的用户自定义django表单

时间:2017-12-22 07:10:00

标签: python django django-forms django-views

这是我的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对象,但我想只呈现用户订阅的那些板。如何让用户获得表单并进行操作?

1 个答案:

答案 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})