What is the right way to override Django's Model.validate_unique? I tried overriding it and raising my own ValidationError
, but got this error:
AttributeError: 'ValidationError' object has no attribute 'message_dict'
save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically.
The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.
The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.
create() will automatically save, so even if you fix your error - you will still have to make sure the arguments to create fulfill the database requirements to save a record.
Django expects your ValidationErrors to be instantiated with a dictionary instead of a string:
from django.db.models import Model
from django.core.exceptions import ValidationError
from django.core.exceptions import NON_FIELD_ERRORS
class Person(Model):
...
def validate_unique(self, *args, **kwargs):
super(Person, self).validate_unique(*args, **kwargs)
if not self.id:
if self.__class__.objects.filter(...).exists():
raise ValidationError(
{
NON_FIELD_ERRORS: [
'Person with same ... already exists.',
],
}
)
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