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 that no matter where I save the instance this code validates that it can be saved.
At the moment I have this code in a custom save function of my model class:
def save(self): if self.is_available(): # my custom check availability function super(MyObj, self).save() else: # this is the bit I'm stuck with.. raise forms.ValidationError('Item already booked for those dates')
This works fine - the error is raised if the item is unavailable, and my item is not saved. I can capture the exception from my front end form code, but what about the Django admin site? How can I get my exception to be displayed like any other validation error in the admin site?
To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.
To automate this process, we can programmatically fetch all the models in the project and register them with the admin interface. Open admin.py file and add this code to it. This will fetch all the models in all apps and registers them with the admin interface.
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 callclean()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With