mirror of
https://github.com/django/django.git
synced 2025-10-31 09:41:08 +00:00
Fixed #16192 -- Made unique error messages in ModelForm customizable.
Overriding the error messages now works for both unique fields, unique_together and unique_for_date. This patch changed the overriding logic to allow customizing NON_FIELD_ERRORS since previously only fields' errors were customizable. Refs #20199. Thanks leahculver for the suggestion.
This commit is contained in:
@@ -8,7 +8,7 @@ from collections import OrderedDict
|
||||
import copy
|
||||
import warnings
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
|
||||
from django.forms.fields import Field, FileField
|
||||
from django.forms.utils import flatatt, ErrorDict, ErrorList
|
||||
from django.forms.widgets import Media, MediaDefiningClass, TextInput, Textarea
|
||||
@@ -21,8 +21,6 @@ from django.utils import six
|
||||
|
||||
__all__ = ('BaseForm', 'Form')
|
||||
|
||||
NON_FIELD_ERRORS = '__all__'
|
||||
|
||||
|
||||
def pretty_name(name):
|
||||
"""Converts 'first_name' to 'First name'"""
|
||||
|
||||
@@ -373,15 +373,21 @@ class BaseModelForm(BaseForm):
|
||||
|
||||
def _update_errors(self, errors):
|
||||
# Override any validation error messages defined at the model level
|
||||
# with those defined on the form fields.
|
||||
# with those defined at the form level.
|
||||
opts = self._meta
|
||||
for field, messages in errors.error_dict.items():
|
||||
if field not in self.fields:
|
||||
if (field == NON_FIELD_ERRORS and opts.error_messages and
|
||||
NON_FIELD_ERRORS in opts.error_messages):
|
||||
error_messages = opts.error_messages[NON_FIELD_ERRORS]
|
||||
elif field in self.fields:
|
||||
error_messages = self.fields[field].error_messages
|
||||
else:
|
||||
continue
|
||||
field = self.fields[field]
|
||||
|
||||
for message in messages:
|
||||
if (isinstance(message, ValidationError) and
|
||||
message.code in field.error_messages):
|
||||
message.message = field.error_messages[message.code]
|
||||
message.code in error_messages):
|
||||
message.message = error_messages[message.code]
|
||||
|
||||
self.add_error(None, errors)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user