【问题标题】:Pass data to django form's field clean method将数据传递给 django 表单的字段清理方法
【发布时间】:2014-08-06 17:13:47
【问题描述】:

我有这样的表格:

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”,但没有成功。我在表单类构造函数中传递这个变量:

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

任何建议,我如何才能访问 clean_title 中的“竞赛”?

【问题讨论】:

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


【解决方案1】:

这是标准的 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, ...

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 2017-12-31
    • 2021-05-05
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多