Django ModelForm 验证 [英] Django ModelForm Validation
问题描述
现在正在尝试解决一个有趣的问题.
Trying to solve an interesting problem right now.
我有一个带有 image
字段的 Django 模型,该字段不是必需的,但在创建新模型实例时设置为默认值.
I have a Django model with an image
field that's not required, but is set to a default value when a new model instance is created.
class Product(models.Model):
image = models.ImageField(upload_to='/image/directory/', default='/default/image/path/', blank=True)
我还有一个基于该模型的 ModelForm,其中包括 image
字段,并且有一些自定义验证.
I also have a ModelForm based on that model, that includes the image
field, and that has some custom validation.
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ('image',)
def clean_image(self):
image = self.cleaned_data.get('image', False)
if image:
# validate image
return None
问题在于 根据文档,在 ModelForm
上调用 is_valid()
会触发模型验证以及表单验证,因此当用户提交没有图像的模型表单时,我的自定义表单验证代码尝试验证默认模型图像,而不是像预期的那样什么都不做.
The problem is that per the docs, calling is_valid()
on a ModelForm
triggers model validation in addition to form validation, so when a user submits the model form without an image, my custom form validation code attempts to validate the default model image, rather than just doing nothing as it's supposed to.
除非表单本身具有 image
字段的值,否则我如何让它不做任何事情?
How do I get it to not do anything unless the form itself has a value for the image
field?
推荐答案
刚刚以非常简单的方式解决了它.在这里添加答案,以防对其他人有帮助.
Just solved it in pretty simple way. Adding the answer here in case it's helpful to anyone else.
...绑定到模型对象的模型表单实例将包含一个 self.instance
属性,该属性使模型表单方法可以访问该特定模型实例.
...a model form instance bound to a model object will contain a
self.instance
attribute that gives model form methods access to that specific model instance.
因此,与其检查 ModelForm
是否具有图像值,我只是检查图像值是否已从保存的实例更改.表单验证现在看起来像这样:
So rather than check if the ModelForm
has an image value, I just check whether the image value has changed from the saved instance. The form validation now looks like this:
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ('image',)
def clean_image(self):
image = self.cleaned_data.get('image', False)
if not self.instance.image == image:
# validate image
return None
问题解决了!
这篇关于Django ModelForm 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!