50
You can do this since Django 1.7
from django.forms import ModelForm
from django.core.exceptions import NON_FIELD_ERRORS
class ArticleForm(ModelForm):
class Meta:
error_messages = {
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}
28
Update 2016/10/20: See jifeng-yin‘s even nicer answer below for Django >= 1.7
The nicest way to override these error messages might be to override the unique_error_message
method on your model. Django calls this method to get the error message whenever it encounters a uniqueness issue during validation.
You can just handle the specific case you want and let all other cases be handled by Django as usual:
def unique_error_message(self, model_class, unique_check):
if model_class == type(self) and unique_check == ('field1', 'field2'):
return 'My custom error message'
else:
return super(Project, self).unique_error_message(model_class, unique_check)
- [Django]-Django. TemplateDoesNotExist in case of a custom widget
- [Django]-ImportError: Could not import settings
- [Django]-How to automatically run tests when there's any change in my project (Django)?
7
For DRF serializers you can use this
from rest_framework import serializers
class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = Some
validators = [
serializers.UniqueTogetherValidator(
queryset=model.objects.all(),
fields=('field1', 'field2'),
message="Some custom message."
)
]
Here is the original source.
- [Django]-Django: implementing JOIN using Django ORM?
- [Django]-How to see details of Django errors with Gunicorn?
- [Django]-Detect mobile, tablet or Desktop on Django
2
After a quick check, it seems that unique_together
validation errors are hard-coded deep in django.db.models.Model.unique_error_message
:
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
model_name = capfirst(opts.verbose_name)
# A unique field
if len(unique_check) == 1:
field_name = unique_check[0]
field_label = capfirst(opts.get_field(field_name).verbose_name)
# Insert the error into the error dict, very sneaky
return _(u"%(model_name)s with this %(field_label)s already exists.") % {
'model_name': unicode(model_name),
'field_label': unicode(field_label)
}
# unique_together
else:
field_labels = map(lambda f: capfirst(opts.get_field(f).verbose_name), unique_check)
field_labels = get_text_list(field_labels, _('and'))
return _(u"%(model_name)s with this %(field_label)s already exists.") % {
'model_name': unicode(model_name),
'field_label': unicode(field_labels)
}
So maybe you should try to override this method from your model, to insert your own message !?
However, I haven’t tried, and it seems a rather brutal solution ! But if you don’t have something better, you might try…
- [Django]-Django REST framework: type object X has no attribute 'get_extra_actions'
- [Django]-How can I use Django OAuth Toolkit with Python Social Auth?
- [Django]-Using django-rest-interface
0
Notice: A lot had changed in Django since this answer. So better check other answers…
If what sebpiq is true( since i do not check source code), then there is one
possible solution you can do, but it is the hard way…
You can define a validation rule in your form, as it described here
You can see examples of validation with more than one field, so by using this method, you can define a unique together check before standard django unique check executed…
Or the worst one, you can do a validation in your view before you try to save the objects…
- [Django]-Set Django IntegerField by choices=… name
- [Django]-Convert string array to array in javascript
- [Django]-Django – Render CheckboxSelectMultiple() widget individually in template (manually)
0
A better solution could be using validate_unique to raise a ValidationError
to replace the error message:
class ModelName(models.Model):
...
class Meta:
unique_together = ['field_1', 'field_2']
def validate_unique(self, *args, **kwargs):
super().validate_unique(*args, **kwargs)
if ModelName.objects.filter(field_1=self.field_1, field_2=self.field_2).exists():
raise ValidationError(
...
)
Validating objects
There are four steps involved in validating a model:
- Validate the model fields – Model.clean_fields()
- Validate the model as a whole – Model.clean()
- Validate the field uniqueness – Model.validate_unique()
- Validate the constraints – Model.validate_constraints()
All four steps are performed when you call a model’s full_clean()
method.When you use a ModelForm, the call to is_valid() will perform these
validation steps for all the fields that are included on the form. See
the ModelForm documentation for more information. You should only need
to call a model’s full_clean() method if you plan to handle validation
errors yourself, or if you have excluded fields from the ModelForm
that require validation.
- [Django]-Django – How to specify which field a validation fails on?
- [Django]-How do I add a custom column with a hyperlink in the django admin interface?
- [Django]—fake-initial vs –fake in Django migration?
-1
You might take a look at overriding django/db/models/base.py:Model._perform_unique_checks() in your model.
In that method you can get the “original” errors:
errors = super(MyModel, self)._perform_unique_checks(unique_checks)
— then modify and return them upwards.
- [Django]-How to save pillow image object to Django ImageField?
- [Django]-Cannot set Django to work with smtp.gmail.com
- [Django]-Allowing RabbitMQ-Server Connections