0

I want that a field be required for the user when making a blog post just if other field(BooleanField) is True. If it's False, it would be okay if the user doesn't complete anything. How can I do it?

Let's say I have this model

class Post(models.Model): 
    name = models.CharField(max_lenght=50)  
    is_female = models.BooleanField()  
    age = models.IntegerField()

So, I want that the age attribute be required just if the is_female is True

Thanks!

Rubico
  • 374
  • 2
  • 12
  • 1
    Does this answer your question? [Adding Custom Django Model Validation](https://stackoverflow.com/questions/7366363/adding-custom-django-model-validation) – AKX Mar 30 '22 at 17:40

1 Answers1

0

You can override the clean method:

from django.core.exceptions import ValidationError


class Post(models.Model): 
    name = models.CharField(max_lenght=50)  
    is_female = models.BooleanField()  
    age = models.IntegerField(blank=True, null=True)

    def clean(self, *args, **kwargs):
        if self.is_fermale and self.age == None:
            raise ValidationError('age cannot be None')
 
        super().clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super().save(*args, **kwargs)
Alain Bianchini
  • 3,883
  • 1
  • 7
  • 27