django用干净的方法改变表格数据

ric*_*ich 10 forms django

我有一个django表单,我想自定义清理.我不想仅仅像这里那样指定错误消息(Django表单和字段验证),而是想自己改变字段.我尝试了一些方法,但一直遇到错误,就像cleaning_data是不可变的一样.

所以为了解决这个问题,我制作了一份副本,对其进行了修改并重新分配给了自己.这是最好的方法吗?可以/我应该在视图中处理这个吗?制作副本似乎很糟糕,但我一直遇到"不可变"的障碍.下面的示例代码我只是检查主题是否在末尾有'--help',如果没有添加它.谢谢

def clean(self):
        cleaned_data=self.cleaned_data.copy()
        subject=cleaned_data.get['subject']
        if not subject.endswith('--help'):
            cleaned_data['subject']=subject+='--help'
        self.cleaned_data=cleaned_data
        return self.cleaned_data
Run Code Online (Sandbox Code Playgroud)

Yuj*_*ita 12

处理这个问题的正确方法是使用特定于字段的清理方法.

无论您从该clean_FOO方法返回什么,cleaned_data它将在到达该clean函数时填充.

请执行以下操作:

def clean_subject(self):
        data = self.cleaned_data.get('subject', '')
        if not data:
             raise forms.ValidationError("You must enter a subject")
             # if you don't want this functionality, just remove it.

        if not data.endswith('--help'):
             return data += '--help'
        return data
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的,但只有在只涉及一个领域时才能做到。如果需要另一个值,则必须使用 `clean`。 (2认同)

jon*_*scb 5

我认为您的问题是您调用了self.cleaned_data.get['subject'],然后稍后将其用作数组。

我有一个消息应用程序的代码,用“无主题”替换空主题

def clean(self):
    super(forms.ModelForm, self).clean()
    subject = self.cleaned_data['subject']
    if subject.isspace():
        self.cleaned_data['subject'] = 'No Subject'
    return self.cleaned_data
Run Code Online (Sandbox Code Playgroud)

对于您的代码,这应该有效。

def clean(self):
    super(forms.Form, self).clean() #I would always do this for forms.
    subject = self.cleaned_data['subject']
    if not subject.endswith('--help'):
        subject += '--help'
        self.cleaned_data['subject'] = subject
    return self.cleaned_data
Run Code Online (Sandbox Code Playgroud)

  • 太好了!我在 clean 方法中更改它,但是当它返回到视图时。该字段未更改。也许这就是一直以来的问题?你能看看我是如何设置视图的吗? (2认同)

Phi*_*ler 5

因此,我发现这最近在谷歌上搜索了可能存在的相同问题,即在表单的ModelForm实例中,我试图编辑数据验证后的数据,以便为最终用户提供有关有效响应的建议(从他们输入表单的另一个值计算得出)。

TL; DR

如果要专门处理ModelForm后代,则有两点很重要:

  1. 您必须致电super(YourModelFormClass, self).clean()以便检查唯一字段。
  2. 如果您正在编辑cleaned_data,那么还必须在附加到ModelForm的模型实例上编辑相同的字段:

    def clean(self)
      self.cleaned_data = super(MyModelFormClass, self).clean()
      self.cleaned_data['name']='My suggested value'
      self.instance.name = 'My suggested value'
      return self.cleaned_data
    
    Run Code Online (Sandbox Code Playgroud)

此行为的文档来源

编辑:

与文档相反,我刚刚发现这行不通。您必须编辑表单的内容self.data才能使更改显示在表单显示时。

  • 顺便说一句,如果修改 self.data ,你应该小心,因为它可能是只读对象(例如 django.http.QueryDict )。如果您想修改它,您应该在表单的构造函数中创建一个副本。 (2认同)