空Django表单选择字段

时间:2019-02-05 07:54:13

标签: django django-models django-forms django-templates django-views

在发送到模板之前,我想要空白job_users字段。因为job_groupsjob_users是依赖的。选择组后,我正在呼叫ajax呼叫,该组的用户将显示在job_users内。但是现在所有用户都显示在job_users选择字段中。

class JobForm(forms.ModelForm):

    job_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':15}))
    job_users = None
    class Meta:
        model = Jobs
        fields = [  
                    'job_name', 
                    'job_group',
                    'job_users',
                ]

    def __init__(self, *args, **kwargs):
        self.user_company = kwargs.pop('user_company', None)
        super().__init__(*args, **kwargs)
        self.fields['job_group'].queryset = None

self.fields['job_group'].queryset = None我正在使用它,但这给了我错误

1 个答案:

答案 0 :(得分:0)

也许您可以这样:

class JobForm(forms.ModelForm):
    job_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':15}))
    class Meta:
        model = Jobs
        fields = [  
                    'job_name', 
                    'job_group',
                ]

    def __init__(self, *args, **kwargs):
        self.user_company = kwargs.pop('user_company', None)
        super().__init__(*args, **kwargs)
        self.fields['job_group'].queryset = Jobgroup.objects.none()

但是,当您尝试使用form.is_valid()验证表单时,它将引发错误。因此,在执行此操作之前,请像这样更新视图中的queryset:

def some_view_def(request):
    form = JobForm(request.POST)
    form.fields['job_group'].queryset = JobGroup.objects.filter(...)  # <-- here 
    if form.is_valid():
       # rest of the code