Showing custom model validation exceptions in the Django admin site

后端 未结 4 1272
悲&欢浪女
悲&欢浪女 2021-02-07 00:27

I have a booking model that needs to check if the item being booked out is available. I would like to have the logic behind figuring out if the item is available centralised so

4条回答
  •  走了就别回头了
    2021-02-07 00:27

    In django 1.2, model validation has been added.

    You can now add a "clean" method to your models which raise ValidationError exceptions, and it will be called automatically when using the django admin.

    The clean() method is called when using the django admin, but NOT called on save().

    If you need to use the clean() method outside of the admin, you will need to explicitly call clean() yourself.

    http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#validating-objects

    So your clean method could be something like this:

    from django.core.exceptions import ValidationError
    
    class MyModel(models.Model):
    
        def is_available(self):
            #do check here
            return result
    
        def clean(self):
            if not self.is_available():
                raise ValidationError('Item already booked for those dates')
    

    I haven't made use of it extensively, but seems like much less code than having to create a ModelForm, and then link that form in the admin.py file for use in django admin.

提交回复
热议问题