Django动态ModelChoiceField字段

时间:2014-12-05 06:53:29

标签: python django

尝试传入变量以帮助ModelChoiceField所需的查询集。得到错误TypeError: __init__() takes at least 2 arguments (1 given),我不知道为什么。请参阅下面的代码。

forms.py

class uploadForm(forms.Form):

    def __init__(self, trainer, *args, **kwargs):
        super(uploadForm, self).__init__(trainer, *args, **kwargs)
        self.fields["client"] = forms.ModelChoiceField(
                      queryset=Trainee.objects.filter(trainer=trainer),
                      widget=forms.Select(attrs={'class': 'signup-form-input'})
                   )

views.py

uploadForm = uploadForm(trainer)

1 个答案:

答案 0 :(得分:1)

您收到此异常是因为以下代码行错误:

super(uploadForm, self).__init__(trainer, *args, **kwargs)

在init方法中。它应该只是

super(uploadForm, self).__init__(*args, **kwargs)

在超类的构造函数trainer中不是一个参数。

无论如何,你做的方式是错的!你应该实现你的表单类,如下所示:

forms.py:

class UploadForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(UploadForm, self).__init__(*args, **kwargs)
        self.fields["client"] = forms.ModelChoiceField(
            queryset=Trainee.objects.filter(trainer=kwargs['trainer']),
            widget=forms.Select(
                attrs={
                    'class': 'signup-form-input'
                }
            ))

views.py:

uploadform = UploadForm(trainer=trainer)

还有一点需要注意:如果trainer不是表单中的字段,则在调用超类构造函数之前弹出trainer

class UploadForm(forms.Form):
    def __init__(self, *args, **kwargs):
        trainer = kwargs.pop('trainer', None)  
        super(UploadForm, self).__init__(*args, **kwargs)
        self.fields["client"] = forms.ModelChoiceField(
            queryset=Trainee.objects.filter(trainer=trainer),
            widget=forms.Select(
                attrs={
                    'class': 'signup-form-input'
                }
            ))
views.py就像我在答案中给出的那样。