将数据传递给django表单字段清理方法

时间:2014-06-16 19:52:25

标签: django django-models django-forms django-validation

我有这样的形式:

class TitlePropose(forms.Form):
    title = forms.CharField(max_length=128)
    code= forms.CharField(max_length=32)
    def __init__(self, contest, *args, **kwargs):
        super(TitlePropose, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = self.__class__.__name__.lower()
        self.helper.form_action = ''
        self.helper.layout = Layout(,
            Field('title'),
            Field('code'),
        )


    def clean_title(self):
        if OtherModel.objects.filter(contest=contest, title=self.cleaned_data['title']).count() > 0:
            raise forms.ValidationError("Title unavailable")
        else:
            return self.cleaned_data['title']

我尝试从clean_title方法访问变量“contest”,但没有任何成功。我在表单类contructor中传递了这个变量:

#contest is just some object
new_title_form = TitlePropose(contest=contest.uuid)

任何建议,如何在clean_title中获取“竞赛”?

1 个答案:

答案 0 :(得分:2)

这是标准的Python类。如果要存储对象以便其他方法可以访问它,可以通过将其添加到self来使其成为实例属性。

def __init__(self, *args, **kwargs):
    self.contest = kwargs.pop('contest')
    super(TitlePropose, self).__init__(*args, **kwargs)

def clean_title(self):
    if OtherModel.objects.filter(contest=self.contest, ...