A
A
albertalexandrov2019-11-20 09:49:24
Django
albertalexandrov, 2019-11-20 09:49:24

How to override the default unique_together message?

Hello!
Suppose there is a model:

class RuleNode(models.Model):
    rule = ...
    node = ....
    field = ...

    class Meta:
        unique_together = 

The default message when inserting duplicate values ​​will look something like this:
{
"non_field_errors": [
"The fields rule, field must make a unique set."
]
}

How can it be overridden? Do not offer in the serializer)
Thank you

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2019-11-20
@deepblack

https://docs.djangoproject.com/en/2.1/topics/forms...

from django.core.exceptions import NON_FIELD_ERRORS
from django.forms import ModelForm

class ArticleForm(ModelForm):
    class Meta:
        error_messages = {
            NON_FIELD_ERRORS: {
                'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
            }
        }

A
alternativshik, 2019-11-20
@alternativshik

Override the unique_error_message method in the model, native looks like this, then, I hope you can handle it

def unique_error_message(self, model_class, unique_check):
        opts = model_class._meta

        params = {
            'model': self,
            'model_class': model_class,
            'model_name': capfirst(opts.verbose_name),
            'unique_check': unique_check,
        }

        # A unique field
        if len(unique_check) == 1:
            field = opts.get_field(unique_check[0])
            params['field_label'] = capfirst(field.verbose_name)
            return ValidationError(
                message=field.error_messages['unique'],
                code='unique',
                params=params,
            )

        # unique_together
        else:
            field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
            params['field_labels'] = get_text_list(field_labels, _('and'))
            return ValidationError(
                message=_("%(model_name)s with this %(field_labels)s already exists."),
                code='unique_together',
                params=params,
            )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question