Django-admin clean_fields 覆盖,在提交时保留以前的数据
我的问题很简单,我的应用程序模型中有一个继承自 models.Model
的类。
我正在重写 django-admin 的 clean_fields 方法,以便对我的表单执行一些自定义验证。 问题是,当它从我的自定义验证中引发 ValidationError
时,如果用户尝试使用正确的信息再次提交表单,它始终会保留上次提交的数据。
class SignedOffModelValidation(models.Model):
class Meta:
abstract = True
def clean_fields(self, exclude = None):
super(SignedOffModelValidation, self).clean_fields(exclude)
errors = {}
if getattr(self, self._meta.immutable_sign_off_field, False):
relation_fields = [
f for f in self._meta.fields
if isinstance(f,(models.ForeignKey,models.ManyToManyField,))
and not f.name.endswith('_ptr')
]
for field in relation_fields:
try:
field_value = getattr(self, field.name)
signed_off = getattr(
field_value,
field_value._meta.immutable_sign_off_field
)
except (AttributeError, ObjectDoesNotExist,):
continue
else:
if not signed_off:
msg = u'In order to signeoff, %s needs to be Signed Off' % \
(str(field_value),)
errors[field.name] = ([msg])
if errors:
raise ValidationError(errors)
任何帮助将不胜感激!
此致
My question is quiet simple, I have a class in my app model that inherits from models.Model
.
I'm overriding the clean_fields
method of the django-admin, in order to execute some custom validation to my form.
The problem is that when it raises a ValidationError
from my custom validation, if the user tries to submit the form again with the correct information, it always keeps the data from the previous submit.
class SignedOffModelValidation(models.Model):
class Meta:
abstract = True
def clean_fields(self, exclude = None):
super(SignedOffModelValidation, self).clean_fields(exclude)
errors = {}
if getattr(self, self._meta.immutable_sign_off_field, False):
relation_fields = [
f for f in self._meta.fields
if isinstance(f,(models.ForeignKey,models.ManyToManyField,))
and not f.name.endswith('_ptr')
]
for field in relation_fields:
try:
field_value = getattr(self, field.name)
signed_off = getattr(
field_value,
field_value._meta.immutable_sign_off_field
)
except (AttributeError, ObjectDoesNotExist,):
continue
else:
if not signed_off:
msg = u'In order to signeoff, %s needs to be Signed Off' % \
(str(field_value),)
errors[field.name] = ([msg])
if errors:
raise ValidationError(errors)
Any help would be appreciated!
Best Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用
clean()
方法而不是clean_fields()
。这在 Django 文档。You should use the
clean()
method rather thanclean_fields()
. This is pretty clear in the Django documentation.