现在正在尝试解决一个有趣的问题。
我有一个带有 image
的 Django 模型字段不是必需的,但在创建新模型实例时设置为默认值。
class Product(models.Model):
image = models.ImageField(upload_to='/image/directory/', default='/default/image/path/', blank=True)
我还有一个基于该模型的 ModelForm,其中包括
image
字段,并且有一些自定义验证。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
问题是 per the docs , 调用
is_valid()
在 ModelForm
除了表单验证之外,还会触发模型验证,因此当用户提交没有图像的模型表单时,我的自定义表单验证代码会尝试验证默认模型图像,而不是像预期的那样什么都不做。我如何让它不做任何事情,除非表单本身具有
image
的值 field ?
最佳答案
只是以非常简单的方式解决了它。在此处添加答案,以防对其他人有帮助。
The Django docs state that
...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
有一个图像值,我只是检查图像值是否从保存的实例中发生了变化。表单验证现在看起来像这样: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 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12806771/