Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: overriding Model.validate_unique

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'
like image 206
Jian Avatar asked Dec 28 '12 20:12

Jian


People also ask

How do I override a save in Django?

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.

What is __ str __ in Django?

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.

How Django knows to update VS insert?

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.

Does create call save Django?

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.


1 Answers

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.',
                        ],
                    }
                )
like image 113
Jian Avatar answered Sep 20 '22 19:09

Jian