我有一个django表单,我想自定义清理。我不想仅仅像这里一样指定错误消息(Django form and field validation),而是想自己改变字段。我尝试了一些方法,但一直遇到错误,就像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
答案 0 :(得分: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
答案 1 :(得分:5)
So, I found this recently having googled about possibly the same problem, whereby in a ModelForm instance of a form, I was trying to edit the data post-validation to provide a suggestion for the end user as to something that would be a valid response (computed from another value they enter into the form).
The TL:DR; is that if you are dealing with a ModelForm descendent specifically, there are two things that are important:
super(YourModelFormClass, self).clean()
so that unique fields are checked.That (most relevant to this question) that if you are editing cleaned_data
, you must also edit the same field on the instance of your model which is attached to your 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
Documentation source for this behaviour
EDIT:
Contrary to the documentation, I have just found that this does not work. you have to edit the form's self.data
in order to get the changes to show up when the form displays.
答案 2 :(得分:3)
我认为您的问题是您已调用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
对于您的代码,这应该有用。
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
答案 3 :(得分:0)
“此方法应返回从cleaning_data获取的已清理值,无论其是否发生任何变化。”来自https://docs.djangoproject.com/en/dev/ref/forms/validation/