Changed django.forms.ValidationError imports to django.core.exceptions.ValidationError.

Co-Authored-By: Mariusz Felisiak <felisiak.mariusz@gmail.com>
This commit is contained in:
François Freitag 2020-02-12 14:48:49 +01:00 committed by Mariusz Felisiak
parent 2788de95e3
commit 9ef4a18dbe
48 changed files with 164 additions and 133 deletions

View File

@ -1,5 +1,5 @@
from django import forms
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
@ -19,7 +19,7 @@ class AdminAuthenticationForm(AuthenticationForm):
def confirm_login_allowed(self, user): def confirm_login_allowed(self, user):
super().confirm_login_allowed(user) super().confirm_login_allowed(user)
if not user.is_staff: if not user.is_staff:
raise forms.ValidationError( raise ValidationError(
self.error_messages['invalid_login'], self.error_messages['invalid_login'],
code='invalid_login', code='invalid_login',
params={'username': self.username_field.verbose_name} params={'username': self.username_field.verbose_name}

View File

@ -10,6 +10,7 @@ from django.contrib.auth.hashers import (
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives from django.core.mail import EmailMultiAlternatives
from django.template import loader from django.template import loader
from django.utils.encoding import force_bytes from django.utils.encoding import force_bytes
@ -113,7 +114,7 @@ class UserCreationForm(forms.ModelForm):
password1 = self.cleaned_data.get("password1") password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2") password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2: if password1 and password2 and password1 != password2:
raise forms.ValidationError( raise ValidationError(
self.error_messages['password_mismatch'], self.error_messages['password_mismatch'],
code='password_mismatch', code='password_mismatch',
) )
@ -127,7 +128,7 @@ class UserCreationForm(forms.ModelForm):
if password: if password:
try: try:
password_validation.validate_password(password, self.instance) password_validation.validate_password(password, self.instance)
except forms.ValidationError as error: except ValidationError as error:
self.add_error('password2', error) self.add_error('password2', error)
def save(self, commit=True): def save(self, commit=True):
@ -226,12 +227,12 @@ class AuthenticationForm(forms.Form):
allow login by active users, and reject login by inactive users. allow login by active users, and reject login by inactive users.
If the given user cannot log in, this method should raise a If the given user cannot log in, this method should raise a
``forms.ValidationError``. ``ValidationError``.
If the given user may log in, this method should return None. If the given user may log in, this method should return None.
""" """
if not user.is_active: if not user.is_active:
raise forms.ValidationError( raise ValidationError(
self.error_messages['inactive'], self.error_messages['inactive'],
code='inactive', code='inactive',
) )
@ -240,7 +241,7 @@ class AuthenticationForm(forms.Form):
return self.user_cache return self.user_cache
def get_invalid_login_error(self): def get_invalid_login_error(self):
return forms.ValidationError( return ValidationError(
self.error_messages['invalid_login'], self.error_messages['invalid_login'],
code='invalid_login', code='invalid_login',
params={'username': self.username_field.verbose_name}, params={'username': self.username_field.verbose_name},
@ -354,7 +355,7 @@ class SetPasswordForm(forms.Form):
password2 = self.cleaned_data.get('new_password2') password2 = self.cleaned_data.get('new_password2')
if password1 and password2: if password1 and password2:
if password1 != password2: if password1 != password2:
raise forms.ValidationError( raise ValidationError(
self.error_messages['password_mismatch'], self.error_messages['password_mismatch'],
code='password_mismatch', code='password_mismatch',
) )
@ -392,7 +393,7 @@ class PasswordChangeForm(SetPasswordForm):
""" """
old_password = self.cleaned_data["old_password"] old_password = self.cleaned_data["old_password"]
if not self.user.check_password(old_password): if not self.user.check_password(old_password):
raise forms.ValidationError( raise ValidationError(
self.error_messages['password_incorrect'], self.error_messages['password_incorrect'],
code='password_incorrect', code='password_incorrect',
) )
@ -429,7 +430,7 @@ class AdminPasswordChangeForm(forms.Form):
password2 = self.cleaned_data.get('password2') password2 = self.cleaned_data.get('password2')
if password1 and password2: if password1 and password2:
if password1 != password2: if password1 != password2:
raise forms.ValidationError( raise ValidationError(
self.error_messages['password_mismatch'], self.error_messages['password_mismatch'],
code='password_mismatch', code='password_mismatch',
) )

View File

@ -1,6 +1,7 @@
from django import forms from django import forms
from django.conf import settings from django.conf import settings
from django.contrib.flatpages.models import FlatPage from django.contrib.flatpages.models import FlatPage
from django.core.exceptions import ValidationError
from django.utils.translation import gettext, gettext_lazy as _ from django.utils.translation import gettext, gettext_lazy as _
@ -38,12 +39,12 @@ class FlatpageForm(forms.ModelForm):
def clean_url(self): def clean_url(self):
url = self.cleaned_data['url'] url = self.cleaned_data['url']
if not url.startswith('/'): if not url.startswith('/'):
raise forms.ValidationError( raise ValidationError(
gettext("URL is missing a leading slash."), gettext("URL is missing a leading slash."),
code='missing_leading_slash', code='missing_leading_slash',
) )
if self._trailing_slash_required() and not url.endswith('/'): if self._trailing_slash_required() and not url.endswith('/'):
raise forms.ValidationError( raise ValidationError(
gettext("URL is missing a trailing slash."), gettext("URL is missing a trailing slash."),
code='missing_trailing_slash', code='missing_trailing_slash',
) )
@ -60,7 +61,7 @@ class FlatpageForm(forms.ModelForm):
if sites and same_url.filter(sites__in=sites).exists(): if sites and same_url.filter(sites__in=sites).exists():
for site in sites: for site in sites:
if same_url.filter(sites=site).exists(): if same_url.filter(sites=site).exists():
raise forms.ValidationError( raise ValidationError(
_('Flatpage with url %(url)s already exists for site %(site)s'), _('Flatpage with url %(url)s already exists for site %(site)s'),
code='duplicate_url', code='duplicate_url',
params={'url': url, 'site': site}, params={'url': url, 'site': site},

View File

@ -1,6 +1,6 @@
import struct import struct
from django.forms import ValidationError from django.core.exceptions import ValidationError
from .const import ( from .const import (
BANDTYPE_FLAG_HASNODATA, BANDTYPE_PIXTYPE_MASK, GDAL_TO_POSTGIS, BANDTYPE_FLAG_HASNODATA, BANDTYPE_PIXTYPE_MASK, GDAL_TO_POSTGIS,

View File

@ -1,6 +1,7 @@
from django import forms from django import forms
from django.contrib.gis.gdal import GDALException from django.contrib.gis.gdal import GDALException
from django.contrib.gis.geos import GEOSException, GEOSGeometry from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from .widgets import OpenLayersWidget from .widgets import OpenLayersWidget
@ -47,7 +48,7 @@ class GeometryField(forms.Field):
except (GEOSException, ValueError, TypeError): except (GEOSException, ValueError, TypeError):
value = None value = None
if value is None: if value is None:
raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom') raise ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')
# Try to set the srid # Try to set the srid
if not value.srid: if not value.srid:
@ -71,14 +72,14 @@ class GeometryField(forms.Field):
# Ensuring that the geometry is of the correct type (indicated # Ensuring that the geometry is of the correct type (indicated
# using the OGC string label). # using the OGC string label).
if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY': if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
raise forms.ValidationError(self.error_messages['invalid_geom_type'], code='invalid_geom_type') raise ValidationError(self.error_messages['invalid_geom_type'], code='invalid_geom_type')
# Transforming the geometry if the SRID was set. # Transforming the geometry if the SRID was set.
if self.srid and self.srid != -1 and self.srid != geom.srid: if self.srid and self.srid != -1 and self.srid != geom.srid:
try: try:
geom.transform(self.srid) geom.transform(self.srid)
except GEOSException: except GEOSException:
raise forms.ValidationError( raise ValidationError(
self.error_messages['transform_error'], code='transform_error') self.error_messages['transform_error'], code='transform_error')
return geom return geom
@ -89,7 +90,7 @@ class GeometryField(forms.Field):
try: try:
data = self.to_python(data) data = self.to_python(data)
initial = self.to_python(initial) initial = self.to_python(initial)
except forms.ValidationError: except ValidationError:
return True return True
# Only do a geographic comparison if both values are available # Only do a geographic comparison if both values are available

View File

@ -1,6 +1,7 @@
import json import json
from django import forms from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
__all__ = ['JSONField'] __all__ = ['JSONField']
@ -30,7 +31,7 @@ class JSONField(forms.CharField):
try: try:
converted = json.loads(value) converted = json.loads(value)
except json.JSONDecodeError: except json.JSONDecodeError:
raise forms.ValidationError( raise ValidationError(
self.error_messages['invalid'], self.error_messages['invalid'],
code='invalid', code='invalid',
params={'value': value}, params={'value': value},

View File

@ -18,8 +18,9 @@ other hooks.
Although the primary way you'll use ``Field`` classes is in ``Form`` classes, Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
you can also instantiate them and use them directly to get a better idea of you can also instantiate them and use them directly to get a better idea of
how they work. Each ``Field`` instance has a ``clean()`` method, which takes how they work. Each ``Field`` instance has a ``clean()`` method, which takes
a single argument and either raises a ``django.forms.ValidationError`` a single argument and either raises a
exception or returns the clean value:: ``django.core.exceptions.ValidationError`` exception or returns the clean
value::
>>> from django import forms >>> from django import forms
>>> f = forms.EmailField() >>> f = forms.EmailField()

View File

@ -305,6 +305,7 @@ don't want to put it into the general ``MultiEmailField`` class. Instead, we
write a cleaning method that operates on the ``recipients`` field, like so:: write a cleaning method that operates on the ``recipients`` field, like so::
from django import forms from django import forms
from django.core.exceptions import ValidationError
class ContactForm(forms.Form): class ContactForm(forms.Form):
# Everything as before. # Everything as before.
@ -313,7 +314,7 @@ write a cleaning method that operates on the ``recipients`` field, like so::
def clean_recipients(self): def clean_recipients(self):
data = self.cleaned_data['recipients'] data = self.cleaned_data['recipients']
if "fred@example.com" not in data: if "fred@example.com" not in data:
raise forms.ValidationError("You have forgotten about Fred!") raise ValidationError("You have forgotten about Fred!")
# Always return a value to use as the new cleaned data, even if # Always return a value to use as the new cleaned data, even if
# this method didn't change it. # this method didn't change it.
@ -346,6 +347,7 @@ an error, you can raise a ``ValidationError`` from the ``clean()`` method. For
example:: example::
from django import forms from django import forms
from django.core.exceptions import ValidationError
class ContactForm(forms.Form): class ContactForm(forms.Form):
# Everything as before. # Everything as before.
@ -359,7 +361,7 @@ example::
if cc_myself and subject: if cc_myself and subject:
# Only do something if both fields are valid so far. # Only do something if both fields are valid so far.
if "help" not in subject: if "help" not in subject:
raise forms.ValidationError( raise ValidationError(
"Did not send for 'help' in the subject despite " "Did not send for 'help' in the subject despite "
"CC'ing yourself." "CC'ing yourself."
) )

View File

@ -1100,6 +1100,7 @@ code would be required in the app's ``admin.py`` file::
from django.contrib.auth.models import Group from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.core.exceptions import ValidationError
from customauth.models import MyUser from customauth.models import MyUser
@ -1119,7 +1120,7 @@ code would be required in the app's ``admin.py`` file::
password1 = self.cleaned_data.get("password1") password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2") password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2: if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match") raise ValidationError("Passwords don't match")
return password2 return password2
def save(self, commit=True): def save(self, commit=True):

View File

@ -1508,12 +1508,12 @@ provides several built-in forms located in :mod:`django.contrib.auth.forms`:
class PickyAuthenticationForm(AuthenticationForm): class PickyAuthenticationForm(AuthenticationForm):
def confirm_login_allowed(self, user): def confirm_login_allowed(self, user):
if not user.is_active: if not user.is_active:
raise forms.ValidationError( raise ValidationError(
_("This account is inactive."), _("This account is inactive."),
code='inactive', code='inactive',
) )
if user.username.startswith('b'): if user.username.startswith('b'):
raise forms.ValidationError( raise ValidationError(
_("Sorry, accounts starting with 'b' aren't welcome here."), _("Sorry, accounts starting with 'b' aren't welcome here."),
code='no_b_users', code='no_b_users',
) )

View File

@ -220,7 +220,7 @@ this management data, an exception will be raised::
>>> formset.is_valid() >>> formset.is_valid()
Traceback (most recent call last): Traceback (most recent call last):
... ...
django.forms.utils.ValidationError: ['ManagementForm data is missing or has been tampered with'] django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with']
It is used to keep track of how many form instances are being displayed. If It is used to keep track of how many form instances are being displayed. If
you are adding new forms via JavaScript, you should increment the count fields you are adding new forms via JavaScript, you should increment the count fields
@ -261,6 +261,7 @@ Custom formset validation
A formset has a ``clean`` method similar to the one on a ``Form`` class. This A formset has a ``clean`` method similar to the one on a ``Form`` class. This
is where you define your own validation that works at the formset level:: is where you define your own validation that works at the formset level::
>>> from django.core.exceptions import ValidationError
>>> from django.forms import BaseFormSet >>> from django.forms import BaseFormSet
>>> from django.forms import formset_factory >>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm >>> from myapp.forms import ArticleForm
@ -277,7 +278,7 @@ is where you define your own validation that works at the formset level::
... continue ... continue
... title = form.cleaned_data.get('title') ... title = form.cleaned_data.get('title')
... if title in titles: ... if title in titles:
... raise forms.ValidationError("Articles in a set must have distinct titles.") ... raise ValidationError("Articles in a set must have distinct titles.")
... titles.append(title) ... titles.append(title)
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet) >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)

View File

@ -454,6 +454,7 @@ integer as the ``number`` argument. Then ``number`` will be looked up in the
dictionary under that key during string interpolation. Here's example:: dictionary under that key during string interpolation. Here's example::
from django import forms from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ngettext_lazy from django.utils.translation import ngettext_lazy
class MyForm(forms.Form): class MyForm(forms.Form):
@ -463,7 +464,7 @@ dictionary under that key during string interpolation. Here's example::
def clean(self): def clean(self):
# ... # ...
if error: if error:
raise forms.ValidationError(self.error_message % {'num': number}) raise ValidationError(self.error_message % {'num': number})
If the string contains exactly one unnamed placeholder, you can interpolate If the string contains exactly one unnamed placeholder, you can interpolate
directly with the ``number`` argument:: directly with the ``number`` argument::
@ -477,7 +478,7 @@ directly with the ``number`` argument::
def clean(self): def clean(self):
# ... # ...
if error: if error:
raise forms.ValidationError(self.error_message % number) raise ValidationError(self.error_message % number)
Formatting strings: ``format_lazy()`` Formatting strings: ``format_lazy()``

View File

@ -1,5 +1,6 @@
from django import forms from django import forms
from django.contrib import admin from django.contrib import admin
from django.core.exceptions import ValidationError
from django.db import models from django.db import models
from .models import ( from .models import (
@ -102,7 +103,7 @@ class TitleForm(forms.ModelForm):
title1 = cleaned_data.get("title1") title1 = cleaned_data.get("title1")
title2 = cleaned_data.get("title2") title2 = cleaned_data.get("title2")
if title1 != title2: if title1 != title2:
raise forms.ValidationError("The two titles must be the same") raise ValidationError("The two titles must be the same")
return cleaned_data return cleaned_data

View File

@ -223,7 +223,7 @@ class BasePersonModelFormSet(BaseModelFormSet):
person = person_dict.get('id') person = person_dict.get('id')
alive = person_dict.get('alive') alive = person_dict.get('alive')
if person and alive and person.name == "Grace Hopper": if person and alive and person.name == "Grace Hopper":
raise forms.ValidationError("Grace is not a Zombie") raise ValidationError("Grace is not a Zombie")
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):

View File

@ -4,6 +4,7 @@ A custom AdminSite for AdminViewPermissionsTest.test_login_has_permission().
from django.contrib import admin from django.contrib import admin
from django.contrib.auth import get_permission_codename from django.contrib.auth import get_permission_codename
from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.forms import AuthenticationForm
from django.core.exceptions import ValidationError
from . import admin as base_admin, models from . import admin as base_admin, models
@ -12,9 +13,8 @@ PERMISSION_NAME = 'admin_views.%s' % get_permission_codename('change', models.Ar
class PermissionAdminAuthenticationForm(AuthenticationForm): class PermissionAdminAuthenticationForm(AuthenticationForm):
def confirm_login_allowed(self, user): def confirm_login_allowed(self, user):
from django import forms
if not user.is_active or not (user.is_staff or user.has_perm(PERMISSION_NAME)): if not user.is_active or not (user.is_staff or user.has_perm(PERMISSION_NAME)):
raise forms.ValidationError('permission denied') raise ValidationError('permission denied')
class HasPermissionAdmin(admin.AdminSite): class HasPermissionAdmin(admin.AdminSite):

View File

@ -1,6 +1,6 @@
from django import forms
from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.admin.helpers import ActionForm from django.contrib.admin.helpers import ActionForm
from django.core.exceptions import ValidationError
class CustomAdminAuthenticationForm(AdminAuthenticationForm): class CustomAdminAuthenticationForm(AdminAuthenticationForm):
@ -11,7 +11,7 @@ class CustomAdminAuthenticationForm(AdminAuthenticationForm):
def clean_username(self): def clean_username(self):
username = self.cleaned_data.get('username') username = self.cleaned_data.get('username')
if username == 'customform': if username == 'customform':
raise forms.ValidationError('custom form error') raise ValidationError('custom form error')
return username return username

View File

@ -2,7 +2,6 @@ import datetime
import re import re
from unittest import mock from unittest import mock
from django import forms
from django.contrib.auth.forms import ( from django.contrib.auth.forms import (
AdminPasswordChangeForm, AuthenticationForm, PasswordChangeForm, AdminPasswordChangeForm, AuthenticationForm, PasswordChangeForm,
PasswordResetForm, ReadOnlyPasswordHashField, ReadOnlyPasswordHashWidget, PasswordResetForm, ReadOnlyPasswordHashField, ReadOnlyPasswordHashWidget,
@ -12,6 +11,7 @@ from django.contrib.auth.models import User
from django.contrib.auth.signals import user_login_failed from django.contrib.auth.signals import user_login_failed
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.core import mail from django.core import mail
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives from django.core.mail import EmailMultiAlternatives
from django.forms.fields import CharField, Field, IntegerField from django.forms.fields import CharField, Field, IntegerField
from django.test import SimpleTestCase, TestCase, override_settings from django.test import SimpleTestCase, TestCase, override_settings
@ -372,13 +372,13 @@ class AuthenticationFormTest(TestDataMixin, TestCase):
form = AuthenticationFormWithInactiveUsersOkay(None, data) form = AuthenticationFormWithInactiveUsersOkay(None, data)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
# If we want to disallow some logins according to custom logic, # Raise a ValidationError in the form to disallow some logins according
# we should raise a django.forms.ValidationError in the form. # to custom logic.
class PickyAuthenticationForm(AuthenticationForm): class PickyAuthenticationForm(AuthenticationForm):
def confirm_login_allowed(self, user): def confirm_login_allowed(self, user):
if user.username == "inactive": if user.username == "inactive":
raise forms.ValidationError("This user is disallowed.") raise ValidationError("This user is disallowed.")
raise forms.ValidationError("Sorry, nobody's allowed in.") raise ValidationError("Sorry, nobody's allowed in.")
form = PickyAuthenticationForm(None, data) form = PickyAuthenticationForm(None, data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
@ -496,7 +496,7 @@ class AuthenticationFormTest(TestDataMixin, TestCase):
def test_get_invalid_login_error(self): def test_get_invalid_login_error(self):
error = AuthenticationForm().get_invalid_login_error() error = AuthenticationForm().get_invalid_login_error()
self.assertIsInstance(error, forms.ValidationError) self.assertIsInstance(error, ValidationError)
self.assertEqual( self.assertEqual(
error.message, error.message,
'Please enter a correct %(username)s and password. Note that both ' 'Please enter a correct %(username)s and password. Note that both '

View File

@ -1,6 +1,7 @@
import pickle import pickle
from django.forms import BooleanField, ValidationError from django.core.exceptions import ValidationError
from django.forms import BooleanField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,6 +1,6 @@
from django.core.exceptions import ValidationError
from django.forms import ( from django.forms import (
CharField, HiddenInput, PasswordInput, Textarea, TextInput, CharField, HiddenInput, PasswordInput, Textarea, TextInput,
ValidationError,
) )
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,4 +1,5 @@
from django.forms import ChoiceField, Form, ValidationError from django.core.exceptions import ValidationError
from django.forms import ChoiceField, Form
from django.test import SimpleTestCase from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin from . import FormFieldAssertionsMixin

View File

@ -1,4 +1,5 @@
from django.forms import CharField, ComboField, EmailField, ValidationError from django.core.exceptions import ValidationError
from django.forms import CharField, ComboField, EmailField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,8 +1,7 @@
from datetime import date, datetime from datetime import date, datetime
from django.forms import ( from django.core.exceptions import ValidationError
DateField, Form, HiddenInput, SelectDateWidget, ValidationError, from django.forms import DateField, Form, HiddenInput, SelectDateWidget
)
from django.test import SimpleTestCase, override_settings from django.test import SimpleTestCase, override_settings
from django.utils import translation from django.utils import translation

View File

@ -1,6 +1,7 @@
from datetime import date, datetime from datetime import date, datetime
from django.forms import DateTimeField, ValidationError from django.core.exceptions import ValidationError
from django.forms import DateTimeField
from django.test import SimpleTestCase from django.test import SimpleTestCase
from django.utils.timezone import get_fixed_timezone, utc from django.utils.timezone import get_fixed_timezone, utc

View File

@ -1,6 +1,7 @@
import decimal import decimal
from django.forms import DecimalField, NumberInput, ValidationError, Widget from django.core.exceptions import ValidationError
from django.forms import DecimalField, NumberInput, Widget
from django.test import SimpleTestCase, override_settings from django.test import SimpleTestCase, override_settings
from django.utils import formats, translation from django.utils import formats, translation

View File

@ -1,4 +1,5 @@
from django.forms import EmailField, ValidationError from django.core.exceptions import ValidationError
from django.forms import EmailField
from django.test import SimpleTestCase from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin from . import FormFieldAssertionsMixin

View File

@ -1,7 +1,8 @@
import pickle import pickle
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import FileField, ValidationError from django.forms import FileField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,6 +1,7 @@
import os.path import os.path
from django.forms import FilePathField, ValidationError from django.core.exceptions import ValidationError
from django.forms import FilePathField
from django.test import SimpleTestCase from django.test import SimpleTestCase
PATH = os.path.dirname(os.path.abspath(__file__)) PATH = os.path.dirname(os.path.abspath(__file__))

View File

@ -1,4 +1,5 @@
from django.forms import FloatField, NumberInput, ValidationError from django.core.exceptions import ValidationError
from django.forms import FloatField, NumberInput
from django.test import SimpleTestCase from django.test import SimpleTestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import formats, translation from django.utils import formats, translation

View File

@ -1,4 +1,5 @@
from django.forms import GenericIPAddressField, ValidationError from django.core.exceptions import ValidationError
from django.forms import GenericIPAddressField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,12 +1,11 @@
import os import os
import unittest import unittest
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import ( from django.core.files.uploadedfile import (
SimpleUploadedFile, TemporaryUploadedFile, SimpleUploadedFile, TemporaryUploadedFile,
) )
from django.forms import ( from django.forms import ClearableFileInput, FileInput, ImageField, Widget
ClearableFileInput, FileInput, ImageField, ValidationError, Widget,
)
from django.test import SimpleTestCase from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin from . import FormFieldAssertionsMixin

View File

@ -1,4 +1,5 @@
from django.forms import IntegerField, Textarea, ValidationError from django.core.exceptions import ValidationError
from django.forms import IntegerField, Textarea
from django.test import SimpleTestCase from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin from . import FormFieldAssertionsMixin

View File

@ -1,4 +1,5 @@
from django.forms import MultipleChoiceField, ValidationError from django.core.exceptions import ValidationError
from django.forms import MultipleChoiceField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,9 +1,9 @@
from datetime import datetime from datetime import datetime
from django.core.exceptions import ValidationError
from django.forms import ( from django.forms import (
CharField, Form, MultipleChoiceField, MultiValueField, MultiWidget, CharField, Form, MultipleChoiceField, MultiValueField, MultiWidget,
SelectMultiple, SplitDateTimeField, SplitDateTimeWidget, TextInput, SelectMultiple, SplitDateTimeField, SplitDateTimeWidget, TextInput,
ValidationError,
) )
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,6 +1,7 @@
import re import re
from django.forms import RegexField, ValidationError from django.core.exceptions import ValidationError
from django.forms import RegexField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,6 +1,7 @@
import datetime import datetime
from django.forms import SplitDateTimeField, ValidationError from django.core.exceptions import ValidationError
from django.forms import SplitDateTimeField
from django.forms.widgets import SplitDateTimeWidget from django.forms.widgets import SplitDateTimeWidget
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,6 +1,7 @@
import datetime import datetime
from django.forms import TimeField, ValidationError from django.core.exceptions import ValidationError
from django.forms import TimeField
from django.test import SimpleTestCase from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin from . import FormFieldAssertionsMixin

View File

@ -1,6 +1,7 @@
import decimal import decimal
from django.forms import TypedChoiceField, ValidationError from django.core.exceptions import ValidationError
from django.forms import TypedChoiceField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,6 +1,7 @@
import decimal import decimal
from django.forms import TypedMultipleChoiceField, ValidationError from django.core.exceptions import ValidationError
from django.forms import TypedMultipleChoiceField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,4 +1,5 @@
from django.forms import URLField, ValidationError from django.core.exceptions import ValidationError
from django.forms import URLField
from django.test import SimpleTestCase from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin from . import FormFieldAssertionsMixin

View File

@ -1,6 +1,7 @@
import uuid import uuid
from django.forms import UUIDField, ValidationError from django.core.exceptions import ValidationError
from django.forms import UUIDField
from django.test import SimpleTestCase from django.test import SimpleTestCase

View File

@ -1,10 +1,11 @@
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import ( from django.forms import (
BooleanField, CharField, ChoiceField, DateField, DateTimeField, BooleanField, CharField, ChoiceField, DateField, DateTimeField,
DecimalField, EmailField, FileField, FloatField, Form, DecimalField, EmailField, FileField, FloatField, Form,
GenericIPAddressField, IntegerField, ModelChoiceField, GenericIPAddressField, IntegerField, ModelChoiceField,
ModelMultipleChoiceField, MultipleChoiceField, RegexField, ModelMultipleChoiceField, MultipleChoiceField, RegexField,
SplitDateTimeField, TimeField, URLField, ValidationError, utils, SplitDateTimeField, TimeField, URLField, utils,
) )
from django.template import Context, Template from django.template import Context, Template
from django.test import SimpleTestCase, TestCase, ignore_warnings from django.test import SimpleTestCase, TestCase, ignore_warnings

View File

@ -3359,7 +3359,7 @@ Good luck picking a username that doesn&#x27;t already exist.</p>
self.assertIsInstance(e, list) self.assertIsInstance(e, list)
self.assertIn('Foo', e) self.assertIn('Foo', e)
self.assertIn('Foo', forms.ValidationError(e)) self.assertIn('Foo', ValidationError(e))
self.assertEqual( self.assertEqual(
e.as_text(), e.as_text(),

View File

@ -2,9 +2,10 @@ import datetime
from collections import Counter from collections import Counter
from unittest import mock from unittest import mock
from django.core.exceptions import ValidationError
from django.forms import ( from django.forms import (
BaseForm, CharField, DateField, FileField, Form, IntegerField, BaseForm, CharField, DateField, FileField, Form, IntegerField,
SplitDateTimeField, ValidationError, formsets, SplitDateTimeField, formsets,
) )
from django.forms.formsets import BaseFormSet, all_valid, formset_factory from django.forms.formsets import BaseFormSet, all_valid, formset_factory
from django.forms.utils import ErrorList from django.forms.utils import ErrorList

View File

@ -1,6 +1,7 @@
from datetime import date, datetime, time from datetime import date, datetime, time
from django import forms from django import forms
from django.core.exceptions import ValidationError
from django.test import SimpleTestCase, override_settings from django.test import SimpleTestCase, override_settings
from django.utils.translation import activate, deactivate from django.utils.translation import activate, deactivate
@ -19,7 +20,7 @@ class LocalizedTimeTests(SimpleTestCase):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
f = forms.TimeField() f = forms.TimeField()
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM') f.clean('1:30:05 PM')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -46,7 +47,7 @@ class LocalizedTimeTests(SimpleTestCase):
"Localized TimeFields act as unlocalized widgets" "Localized TimeFields act as unlocalized widgets"
f = forms.TimeField(localize=True) f = forms.TimeField(localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM') f.clean('1:30:05 PM')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -69,9 +70,9 @@ class LocalizedTimeTests(SimpleTestCase):
"TimeFields with manually specified input formats can accept those formats" "TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM') f.clean('1:30:05 PM')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05') f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -94,9 +95,9 @@ class LocalizedTimeTests(SimpleTestCase):
"Localized TimeFields with manually specified input formats can accept those formats" "Localized TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM') f.clean('1:30:05 PM')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05') f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -122,7 +123,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
f = forms.TimeField() f = forms.TimeField()
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05') f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -145,7 +146,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
"Localized TimeFields act as unlocalized widgets" "Localized TimeFields act as unlocalized widgets"
f = forms.TimeField(localize=True) f = forms.TimeField(localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05') f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -168,9 +169,9 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
"TimeFields with manually specified input formats can accept those formats" "TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM') f.clean('1:30:05 PM')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05') f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -193,9 +194,9 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
"Localized TimeFields with manually specified input formats can accept those formats" "Localized TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM') f.clean('1:30:05 PM')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05') f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -220,7 +221,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
f = forms.TimeField() f = forms.TimeField()
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM') f.clean('1:30:05 PM')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -243,7 +244,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
"Localized TimeFields in a non-localized environment act as unlocalized widgets" "Localized TimeFields in a non-localized environment act as unlocalized widgets"
f = forms.TimeField() f = forms.TimeField()
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM') f.clean('1:30:05 PM')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -266,7 +267,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
"TimeFields with manually specified input formats can accept those formats" "TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"]) f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"])
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05') f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -289,7 +290,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
"Localized TimeFields with manually specified input formats can accept those formats" "Localized TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True) f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05') f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
@ -321,7 +322,7 @@ class LocalizedDateTests(SimpleTestCase):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
f = forms.DateField() f = forms.DateField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21/12/2010') f.clean('21/12/2010')
# ISO formats are accepted, even if not specified in formats.py # ISO formats are accepted, even if not specified in formats.py
@ -347,7 +348,7 @@ class LocalizedDateTests(SimpleTestCase):
"Localized DateFields act as unlocalized widgets" "Localized DateFields act as unlocalized widgets"
f = forms.DateField(localize=True) f = forms.DateField(localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21/12/2010') f.clean('21/12/2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -370,11 +371,11 @@ class LocalizedDateTests(SimpleTestCase):
"DateFields with manually specified input formats can accept those formats" "DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21') f.clean('2010-12-21')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21/12/2010') f.clean('21/12/2010')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21.12.2010') f.clean('21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -397,11 +398,11 @@ class LocalizedDateTests(SimpleTestCase):
"Localized DateFields with manually specified input formats can accept those formats" "Localized DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21') f.clean('2010-12-21')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21/12/2010') f.clean('21/12/2010')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21.12.2010') f.clean('21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -427,7 +428,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
f = forms.DateField() f = forms.DateField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21') f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -450,7 +451,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
"Localized DateFields act as unlocalized widgets" "Localized DateFields act as unlocalized widgets"
f = forms.DateField(localize=True) f = forms.DateField(localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21') f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -473,9 +474,9 @@ class CustomDateInputFormatsTests(SimpleTestCase):
"DateFields with manually specified input formats can accept those formats" "DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21.12.2010') f.clean('21.12.2010')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21') f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -498,9 +499,9 @@ class CustomDateInputFormatsTests(SimpleTestCase):
"Localized DateFields with manually specified input formats can accept those formats" "Localized DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21.12.2010') f.clean('21.12.2010')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21') f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -525,7 +526,7 @@ class SimpleDateFormatTests(SimpleTestCase):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
f = forms.DateField() f = forms.DateField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21.12.2010') f.clean('21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -548,7 +549,7 @@ class SimpleDateFormatTests(SimpleTestCase):
"Localized DateFields in a non-localized environment act as unlocalized widgets" "Localized DateFields in a non-localized environment act as unlocalized widgets"
f = forms.DateField() f = forms.DateField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('21.12.2010') f.clean('21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -571,7 +572,7 @@ class SimpleDateFormatTests(SimpleTestCase):
"DateFields with manually specified input formats can accept those formats" "DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"]) f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21') f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -594,7 +595,7 @@ class SimpleDateFormatTests(SimpleTestCase):
"Localized DateFields with manually specified input formats can accept those formats" "Localized DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True) f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21') f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -626,7 +627,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"
f = forms.DateTimeField() f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM 21/12/2010') f.clean('1:30:05 PM 21/12/2010')
# ISO formats are accepted, even if not specified in formats.py # ISO formats are accepted, even if not specified in formats.py
@ -652,7 +653,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
"Localized DateTimeFields act as unlocalized widgets" "Localized DateTimeFields act as unlocalized widgets"
f = forms.DateTimeField(localize=True) f = forms.DateTimeField(localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM 21/12/2010') f.clean('1:30:05 PM 21/12/2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -675,11 +676,11 @@ class LocalizedDateTimeTests(SimpleTestCase):
"DateTimeFields with manually specified input formats can accept those formats" "DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"]) f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010-12-21 13:30:05 13:30:05') f.clean('2010-12-21 13:30:05 13:30:05')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM 21/12/2010') f.clean('1:30:05 PM 21/12/2010')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05 21.12.2010') f.clean('13:30:05 21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -702,11 +703,11 @@ class LocalizedDateTimeTests(SimpleTestCase):
"Localized DateTimeFields with manually specified input formats can accept those formats" "Localized DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True) f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010/12/21 13:30:05') f.clean('2010/12/21 13:30:05')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('1:30:05 PM 21/12/2010') f.clean('1:30:05 PM 21/12/2010')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05 21.12.2010') f.clean('13:30:05 21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -736,7 +737,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"
f = forms.DateTimeField() f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010/12/21 13:30:05') f.clean('2010/12/21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -759,7 +760,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
"Localized DateTimeFields act as unlocalized widgets" "Localized DateTimeFields act as unlocalized widgets"
f = forms.DateTimeField(localize=True) f = forms.DateTimeField(localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010/12/21 13:30:05') f.clean('2010/12/21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -782,9 +783,9 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
"DateTimeFields with manually specified input formats can accept those formats" "DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"]) f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05 21.12.2010') f.clean('13:30:05 21.12.2010')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010/12/21 13:30:05') f.clean('2010/12/21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -807,9 +808,9 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
"Localized DateTimeFields with manually specified input formats can accept those formats" "Localized DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True) f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05 21.12.2010') f.clean('13:30:05 21.12.2010')
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010/12/21 13:30:05') f.clean('2010/12/21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -834,7 +835,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"
f = forms.DateTimeField() f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05 21.12.2010') f.clean('13:30:05 21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -857,7 +858,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
"Localized DateTimeFields in a non-localized environment act as unlocalized widgets" "Localized DateTimeFields in a non-localized environment act as unlocalized widgets"
f = forms.DateTimeField() f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('13:30:05 21.12.2010') f.clean('13:30:05 21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -880,7 +881,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
"DateTimeFields with manually specified input formats can accept those formats" "DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"]) f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010/12/21 13:30:05') f.clean('2010/12/21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
@ -903,7 +904,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
"Localized DateTimeFields with manually specified input formats can accept those formats" "Localized DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True) f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
f.clean('2010/12/21 13:30:05') f.clean('2010/12/21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result

View File

@ -3,7 +3,7 @@ import re
from django.contrib.gis import forms from django.contrib.gis import forms
from django.contrib.gis.forms import BaseGeometryWidget, OpenLayersWidget from django.contrib.gis.forms import BaseGeometryWidget, OpenLayersWidget
from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.geos import GEOSGeometry
from django.forms import ValidationError from django.core.exceptions import ValidationError
from django.test import SimpleTestCase, override_settings from django.test import SimpleTestCase, override_settings
from django.utils.html import escape from django.utils.html import escape
@ -39,7 +39,7 @@ class GeometryFieldTest(SimpleTestCase):
"Testing GeometryField's handling of null (None) geometries." "Testing GeometryField's handling of null (None) geometries."
# Form fields, by default, are required (`required=True`) # Form fields, by default, are required (`required=True`)
fld = forms.GeometryField() fld = forms.GeometryField()
with self.assertRaisesMessage(forms.ValidationError, "No geometry value provided."): with self.assertRaisesMessage(ValidationError, "No geometry value provided."):
fld.clean(None) fld.clean(None)
# This will clean None as a geometry (See #10660). # This will clean None as a geometry (See #10660).
@ -64,7 +64,7 @@ class GeometryFieldTest(SimpleTestCase):
pnt_fld.to_python('LINESTRING(0 0, 1 1)') pnt_fld.to_python('LINESTRING(0 0, 1 1)')
) )
# but rejected by `clean` # but rejected by `clean`
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
pnt_fld.clean('LINESTRING(0 0, 1 1)') pnt_fld.clean('LINESTRING(0 0, 1 1)')
def test_to_python(self): def test_to_python(self):
@ -92,7 +92,7 @@ class GeometryFieldTest(SimpleTestCase):
# but raises a ValidationError for any other string # but raises a ValidationError for any other string
for geo_input in bad_inputs: for geo_input in bad_inputs:
with self.subTest(geo_input=geo_input): with self.subTest(geo_input=geo_input):
with self.assertRaises(forms.ValidationError): with self.assertRaises(ValidationError):
fld.to_python(geo_input) fld.to_python(geo_input)
def test_to_python_different_map_srid(self): def test_to_python_different_map_srid(self):

View File

@ -1,7 +1,7 @@
import datetime import datetime
from django import forms from django import forms
from django.core.validators import ValidationError from django.core.exceptions import ValidationError
from django.forms.models import ModelChoiceIterator from django.forms.models import ModelChoiceIterator
from django.forms.widgets import CheckboxSelectMultiple from django.forms.widgets import CheckboxSelectMultiple
from django.template import Context, Template from django.template import Context, Template

View File

@ -5,10 +5,9 @@ from unittest import mock, skipUnless
from django import forms from django import forms
from django.core.exceptions import ( from django.core.exceptions import (
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
) )
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.validators import ValidationError
from django.db import connection, models from django.db import connection, models
from django.db.models.query import EmptyQuerySet from django.db.models.query import EmptyQuerySet
from django.forms.models import ( from django.forms.models import (
@ -2619,7 +2618,7 @@ class CustomCleanTests(TestCase):
def clean(self): def clean(self):
if not self.cleaned_data['left'] == self.cleaned_data['right']: if not self.cleaned_data['left'] == self.cleaned_data['right']:
raise forms.ValidationError('Left and right should be equal') raise ValidationError('Left and right should be equal')
return self.cleaned_data return self.cleaned_data
form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1}) form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1})

View File

@ -4,8 +4,9 @@ from xml.dom.minidom import parseString
from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.decorators import login_required, permission_required
from django.core import mail from django.core import mail
from django.core.exceptions import ValidationError
from django.forms import fields from django.forms import fields
from django.forms.forms import Form, ValidationError from django.forms.forms import Form
from django.forms.formsets import BaseFormSet, formset_factory from django.forms.formsets import BaseFormSet, formset_factory
from django.http import ( from django.http import (
HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed,