【问题标题】:django form with customer parameter and validation not getting clean function具有客户参数和验证的 Django 表单没有获得干净的功能
【发布时间】:2013-09-17 03:43:24
【问题描述】:

我有以下表格:

class GroupForm(forms.ModelForm):
    class Meta:
        model = Group

    def __init__(self, customer):
        self.customer = customer
        super(GroupForm, self).__init__()

    def clean(self):
        cleaned_data = super(GroupForm, self).clean()
        email = cleaned_data.get('email')

        print email

        try:
            groups = Group.objects.filter(email=email, customer=self.customer)
            if groups:
                messsge = u"That email already exists"
                self._errors['email'] = self.error_class([messsge])
        except:
            pass

        return cleaned_data 

我像这样从视图中调用表单:

if request.method == "POST":
    form = GroupForm(request.POST, customer, instance=group)
    if form.is_valid():
        form.save()

问题是验证永远不会被触发。此外,电子邮件的打印永远不会被点击,这意味着 clean 功能永远不会被点击。

为什么会这样?

【问题讨论】:

    标签: django django-forms django-validation


    【解决方案1】:

    我在 SO 上经常看到这个问题,原因通常是相同的。您已覆盖 init 方法并更改了签名,因此第一个元素现在是 customer,而不是 data。但是当您在视图中实例化它时,您首先传递request.POST,因此参数与正确的变量不匹配。

    另外,你没有将参数传递给 super 方法,所以根本看不到 POST。

    改为这样做:

    class GroupForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            self.customer = kwargs.pop('customer', None)
            super(GroupForm, self).__init__(*args, **kwargs)
    

    在视图中:

    form = GroupForm(request.POST, customer=customer, instance=group)
    

    【讨论】:

    • 这背后我花了8个多小时!非常感谢
    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2019-11-01
    • 2020-02-17
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多