Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: form validation for a form with tabular inline

Hello i have registered models like that

# 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)

and:

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

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

admin.site.register(Property, PropertyAdmin)

The is front picture is boolean so I know which will be the picture to be shown on the announces

Problem

I don't know how to make validation so I can throw an eror If 0 or more that 1 picture were chosen as is_front can you please help me with the admin form validation?

Thank you!

like image 595
ThunderHorn Avatar asked Feb 14 '26 02:02

ThunderHorn


1 Answers

One way you can do it is to create a clean method on PropertyImage which will be used to validate the data in the admin.

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.")
like image 88
schillingt Avatar answered Feb 16 '26 00:02

schillingt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!