gpt4 book ai didi

Django:表格内联表单的表单验证

转载 作者:行者123 更新时间:2023-12-05 05:13:41 26 4
gpt4 key购买 nike

你好,我已经注册了这样的模型

# models.py
class Property(models.Model):
address = models.TextField()
...

class PropertyImage(models.Model):
property = models.ForeignKey(Property, related_name='images')
image = models.ImageField()
is_front = models.BooleanField(default=False)

和:

# admin.py
class PropertyImageInline(admin.TabularInline):
model = PropertyImage
extra = 3

class PropertyAdmin(admin.ModelAdmin):
inlines = [ PropertyImageInline, ]

admin.site.register(Property, PropertyAdmin)

前面的图片是 bool 值,所以我知道哪张图片将显示在公告上

问题

我不知道如何进行验证,所以我可以抛出一个错误如果 0 或更多的 1 张图片被选为 is_front 你能帮我进行管理表单验证吗?

谢谢!

最佳答案

您可以这样做的一种方法是在 PropertyImage 上创建一个 clean 方法,该方法将用于验证管理中的数据。

from django.core.exceptions import ValidationError

class PropertyImage(models.Model):
property = models.ForeignKey(Property, related_name='images')
image = models.ImageField()
is_front = models.BooleanField(default=False)

# Clean will only be called within the Admin.
# If you have other places this needs to be verified,
# you'll need to call it manually or move this logic into a ModelForm.
def clean(self):
images = self.property.images.all()
# If we're editing, we want to exclude ourselves from the check.
if self.id:
images = images.exclude(id=self.id)
if self.is_front and images.filter(is_front=True).exists():
raise ValidationError("Only one image can have is_front set.")

关于Django:表格内联表单的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53303217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com