hash
stringlengths
64
64
content
stringlengths
0
1.51M
aa971cdc4478d8ab032511c797894e408b165ffe93baca1c4224cde1c0969467
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("conflicting_app_with_dependencies", "0001_initial"), ("migrated_app", "0001_initial"), ] operations = [ migrations.DeleteModel("Tribble"), migrations.RemoveField("Author", "silly_field"), migrations.AddField("Author", "rating", models.IntegerField(default=0)), migrations.CreateModel( "Book", [ ("id", models.AutoField(primary_key=True)), ], ) ]
b3270ad386a55f4f7bf02cb65e485740e6c44f76f29b1cea09089aec496b42ba
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): operations = [ migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=255)), ("slug", models.SlugField(null=True)), ("age", models.IntegerField(default=0)), ("silly_field", models.BooleanField(default=False)), ], ), migrations.CreateModel( "Tribble", [ ("id", models.AutoField(primary_key=True)), ("fluffy", models.BooleanField(default=True)), ], ) ]
7166b3b5a43b862d2a3752f39c4c27354fb1a06584b570b1a69f96a45aeb94af
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mutate_state_b', '0001_initial'), ] operations = [ migrations.SeparateDatabaseAndState([], [ migrations.CreateModel( name='A', fields=[ ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)), ], ), ]) ]
ded09af220e4cd074b75ff187a35901c5921d0ef657f98ac6b097fc19fd0c12b
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookuperror_a', '0002_a2'), ('lookuperror_b', '0001_initial'), ] operations = [ migrations.CreateModel( name='B2', fields=[ ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)), ('a1', models.ForeignKey('lookuperror_a.A1', models.CASCADE)), ], ), ]
2828f02132e8d5daacf74dac5cc2c703bd9acefbba74663d7aa586559e366f44
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookuperror_b', '0002_b2'), ] operations = [ migrations.CreateModel( name='B3', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)), ], ), ]
130397246c8c20cca9e5bf0a2260c5b69aba580522bdebea3ec21399105637b7
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='B1', fields=[ ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')), ], ), ]
58dbf314e296f73480bc0f10c51efbd013a0f52f551c896615f81111b15abaea
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookuperror_a', '0001_initial'), ] operations = [ migrations.CreateModel( name='A2', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), ], ), ]
25df62864fac58f026ed4ec635f9d16461992896b4df9fdff4876b4c7b95df49
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookuperror_a', '0003_a3'), ] operations = [ migrations.CreateModel( name='A4', fields=[ ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)), ], ), ]
d3fcf8f3573990e3d12ede793c3de1d70de071293fa3f6ce96d96e238ed39d56
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='A1', fields=[ ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)), ], ), ]
1ee07f632b560769a6d82a89dae626eadc8aeab05a52f78a68b7abc0f9a6165d
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookuperror_c', '0002_c2'), ('lookuperror_b', '0002_b2'), ('lookuperror_a', '0002_a2'), ] operations = [ migrations.CreateModel( name='A3', fields=[ ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')), ('b2', models.ForeignKey('lookuperror_b.B2', models.CASCADE)), ('c2', models.ForeignKey('lookuperror_c.C2', models.CASCADE)), ], ), ]
2888b512765877603fc9ac1a6d80e073e3efc31971d1dacdf738d348a5658bba
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mutate_state_b', '0001_initial'), ] operations = [ migrations.SeparateDatabaseAndState([], [ migrations.AddField( model_name='B', name='added', field=models.TextField(), ), ]) ]
18eba42b117b38e33217293929c7b0eb01ab1976a8173df1b16eaaaaeec14fb7
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.SeparateDatabaseAndState([], [ migrations.CreateModel( name='B', fields=[ ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)), ], ), ]) ]
c093f10bbe799a899344880b90bbd197330392260fdc8695e30dc160e2909407
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookuperror_a', '0002_a2'), ('lookuperror_c', '0001_initial'), ] operations = [ migrations.CreateModel( name='C2', fields=[ ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)), ('a1', models.ForeignKey('lookuperror_a.A1', models.CASCADE)), ], ), ]
705b6c44cc0c1378a961aa742e360fd135e618cf9df58b09bff9469b8f5824cd
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookuperror_c', '0002_c2'), ] operations = [ migrations.CreateModel( name='C3', fields=[ ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)), ], ), ]
90f674d3cd61329abd26e59bb0d314141c542de0c2d7e508b3fef42859efd4b4
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='C1', fields=[ ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)), ], ), ]
b528ef8b20f479ffd8de32c0253dab91c88897c8e3a28ab519d6e2d5cb86615f
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app1", "1_auto")]
1f66923b9c22e1265a9eaf92ca65fb5c459d77b9bb95ac6913718a8356facf3e
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app1", "2_squashed_3")]
8f8a664def046090160754f2b67fce6dfef84c87f196e79e204eef68cb61ffb0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): replaces = [ ("app1", "2_auto"), ("app1", "3_auto"), ] dependencies = [("app1", "1_auto"), ("app2", "1_squashed_2")]
1f060d2a0317b35a09d08d9d1580c6cad4797cb4c6a486d0a1e1b31ad9f3ef2f
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app1", "2_auto"), ("app2", "2_auto")]
786b901b76c5b4a888cde0501715f2d87b1acb6b102049b92b81b0715f4e0e53
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app2", "1_auto")]
9c8c42898fdb6094a92be54be6d4063cacac2c8f646abe6ebe8568fdddc59174
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): replaces = [ ("app2", "1_auto"), ("app2", "2_auto"), ] dependencies = [("app1", "1_auto")]
77eecdd4cd611e33efe57d9278fea30647ce5ce57af35ba0908356b61d500704
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app1", "1_auto")] operations = [ migrations.RunPython(migrations.RunPython.noop) ]
e680942e818dd895ff410bf9bff8267137ff10970adb051284081bea60410589
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app1", "3_auto")] operations = [ migrations.RunPython(migrations.RunPython.noop) ]
2060135bb6a6956cffe0e98d41ac85ceb49a1512f5fd68c12e74fb691f305c1c
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): replaces = [ ("app1", "2_auto"), ("app1", "3_auto"), ] dependencies = [("app1", "1_auto"), ("app2", "2_auto")] operations = [ migrations.RunPython(migrations.RunPython.noop) ]
3e23487f44b9562c110f94071e4bee69ac6055fc33d343569b5ce17db94e4793
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app1", "2_auto"), ("app2", "2_auto")] operations = [ migrations.RunPython(migrations.RunPython.noop) ]
bdb3d91965f1f47e5e249561f643a72a4ccfb20eed8322d1c6f459131841aba6
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app2", "1_auto")] operations = [ migrations.RunPython(migrations.RunPython.noop) ]
09339336079f0baca10206a86baf73802d4b6d14af5444d0a74389d7611218ef
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): replaces = [ ("app2", "1_auto"), ("app2", "2_auto"), ] dependencies = [("app1", "1_auto")] operations = [ migrations.RunPython(migrations.RunPython.noop) ]
06c7788417ecbb1ad46e828cec0a3dfea79bc3d0f4ae4d0d46ebe8905e7cdb72
from .custom_permissions import CustomPermissionsUser from .custom_user import ( CustomUser, CustomUserWithoutIsActiveField, ExtensionUser, ) from .invalid_models import CustomUserNonUniqueUsername from .is_active import IsActiveTestUser1 from .uuid_pk import UUIDUser from .with_foreign_key import CustomUserWithFK, Email from .with_integer_username import IntegerUsernameUser __all__ = ( 'CustomUser', 'CustomUserWithoutIsActiveField', 'CustomPermissionsUser', 'CustomUserWithFK', 'Email', 'ExtensionUser', 'IsActiveTestUser1', 'UUIDUser', 'CustomUserNonUniqueUsername', 'IntegerUsernameUser' )
d0907bcb2550fef1339d8fca1466b79b26e049a5a988f91ec2c54ae43c4bbf9f
from django.contrib.auth.models import ( AbstractBaseUser, AbstractUser, BaseUserManager, Group, Permission, PermissionsMixin, UserManager, ) from django.db import models from django.utils.encoding import python_2_unicode_compatible # The custom User uses email as the unique identifier, and requires # that every user provide a date of birth. This lets us test # changes in username datatype, and non-text required fields. class CustomUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, date_of_birth): u = self.create_user(email, password=password, date_of_birth=date_of_birth) u.is_admin = True u.save(using=self._db) return u @python_2_unicode_compatible class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) date_of_birth = models.DateField() custom_objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email # Maybe required? def get_group_permissions(self, obj=None): return set() def get_all_permissions(self, obj=None): return set() def has_perm(self, perm, obj=None): return True def has_perms(self, perm_list, obj=None): return True def has_module_perms(self, app_label): return True # Admin required fields @property def is_staff(self): return self.is_admin class RemoveGroupsAndPermissions(object): """ A context manager to temporarily remove the groups and user_permissions M2M fields from the AbstractUser class, so they don't clash with the related_name sets. """ def __enter__(self): self._old_au_local_m2m = AbstractUser._meta.local_many_to_many self._old_pm_local_m2m = PermissionsMixin._meta.local_many_to_many groups = models.ManyToManyField(Group, blank=True) groups.contribute_to_class(PermissionsMixin, "groups") user_permissions = models.ManyToManyField(Permission, blank=True) user_permissions.contribute_to_class(PermissionsMixin, "user_permissions") PermissionsMixin._meta.local_many_to_many = [groups, user_permissions] AbstractUser._meta.local_many_to_many = [groups, user_permissions] def __exit__(self, exc_type, exc_value, traceback): AbstractUser._meta.local_many_to_many = self._old_au_local_m2m PermissionsMixin._meta.local_many_to_many = self._old_pm_local_m2m class CustomUserWithoutIsActiveField(AbstractBaseUser): username = models.CharField(max_length=150, unique=True) email = models.EmailField(unique=True) objects = UserManager() USERNAME_FIELD = 'username' # The extension user is a simple extension of the built-in user class, # adding a required date_of_birth field. This allows us to check for # any hard references to the name "User" in forms/handlers etc. with RemoveGroupsAndPermissions(): class ExtensionUser(AbstractUser): date_of_birth = models.DateField() custom_objects = UserManager() REQUIRED_FIELDS = AbstractUser.REQUIRED_FIELDS + ['date_of_birth']
e8d6270646dff629b76b6a0e8dc6c1f4cabe0b545edeb8d5e6acccaed2cc050b
""" The CustomPermissionsUser users email as the identifier, but uses the normal Django permissions model. This allows us to check that the PermissionsMixin includes everything that is needed to interact with the ModelBackend. """ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils.encoding import python_2_unicode_compatible from .custom_user import CustomUserManager, RemoveGroupsAndPermissions class CustomPermissionsUserManager(CustomUserManager): def create_superuser(self, email, password, date_of_birth): u = self.create_user(email, password=password, date_of_birth=date_of_birth) u.is_superuser = True u.save(using=self._db) return u with RemoveGroupsAndPermissions(): @python_2_unicode_compatible class CustomPermissionsUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) date_of_birth = models.DateField() custom_objects = CustomPermissionsUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email
3554740bf93dd1a1b3ca0a75432139c963c067a57e546c634706e90eeaddb3b4
from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import BaseUserManager from django.db import models class CustomEmailFieldUserManager(BaseUserManager): def create_user(self, username, password, email): user = self.model(username=username) user.set_password(password) user.email_address = email user.save(using=self._db) return user class CustomEmailField(AbstractBaseUser): username = models.CharField(max_length=255) password = models.CharField(max_length=255) email_address = models.EmailField() is_active = models.BooleanField(default=True) EMAIL_FIELD = 'email_address' objects = CustomEmailFieldUserManager()
7089414d0d6474570d7dc5a3b6f94b5220b61aba28398d7bc20f4972bce8deed
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def add_book(apps, schema_editor): apps.get_model("migration_test_data_persistence", "Book").objects.using( schema_editor.connection.alias, ).create( title="I Love Django", ) class Migration(migrations.Migration): dependencies = [("migration_test_data_persistence", "0001_initial")] operations = [ migrations.RunPython( add_book, ), ]
66d8b342169acee7d11570ba8ed5e7aa5edb8c941955cf473f5cbef8de7bfc78
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), ('title', models.CharField(max_length=100)), ], options={ }, bases=(models.Model,), ), ]
8f76654c180c8a39e9605a30934c04038c085339cc9451f54ed02ef4ac81f5ff
from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = "Dance around like a madman." args = '' requires_system_checks = True def add_arguments(self, parser): parser.add_argument("integer", nargs='?', type=int, default=0) parser.add_argument("-s", "--style", default="Rock'n'Roll") parser.add_argument("-x", "--example") parser.add_argument("--opt-3", action='store_true', dest='option3') def handle(self, *args, **options): example = options["example"] if example == "raise": raise CommandError() if options['verbosity'] > 0: self.stdout.write("I don't feel like dancing %s." % options["style"]) self.stdout.write(','.join(options.keys())) if options['integer'] > 0: self.stdout.write("You passed %d as a positional argument." % options['integer'])
9993da253dbd36a38e63ec0863e51a68c66968c589a93b58288f5afac12e0dce
from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = "Useless command." def add_arguments(self, parser): parser.add_argument('args', metavar='app_label', nargs='*', help='Specify the app label(s) to works on.') parser.add_argument('--empty', action='store_true', dest='empty', default=False, help="Do nothing.") def handle(self, *app_labels, **options): app_labels = set(app_labels) if options['empty']: self.stdout.write("Dave, I can't do that.") return if not app_labels: raise CommandError("I'm sorry Dave, I'm afraid I can't do that.") # raise an error if some --parameter is flowing from options to args for app_label in app_labels: if app_label.startswith('--'): raise CommandError("Sorry, Dave, I can't let you do that.") self.stdout.write("Dave, my mind is going. I can feel it. I can feel it.")
05c7d032bd53b58f78cb568e374756340e1acacfe978651e77b871a97ab28b0c
from django.core.management.base import BaseCommand from django.utils import translation class Command(BaseCommand): leave_locale_alone = True def handle(self, *args, **options): return translation.get_language()
274c7eaee27e15c15f7028cf1aa6d92041a7f8dc8fbcab8ae00edc32544f5da3
from django.core.management.base import BaseCommand from django.utils import translation class Command(BaseCommand): leave_locale_alone = False def handle(self, *args, **options): return translation.get_language()
618e3c6cb02cc209e9103c75ba817a42a74a9b2c5d00f15720645d68b71869ce
import os from django.apps import AppConfig from django.utils._os import upath class NSAppConfig(AppConfig): name = 'nsapp' path = upath(os.path.dirname(__file__))
abc1e6dcda908077f30ff47a70da51acf71898cf79542514fa54c574f3539bba
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations try: from django.contrib.postgres.operations import ( BtreeGinExtension, CITextExtension, CreateExtension, HStoreExtension, TrigramExtension, UnaccentExtension, ) except ImportError: from django.test import mock BtreeGinExtension = mock.Mock() CreateExtension = mock.Mock() HStoreExtension = mock.Mock() TrigramExtension = mock.Mock() UnaccentExtension = mock.Mock() CITextExtension = mock.Mock() class Migration(migrations.Migration): operations = [ BtreeGinExtension(), # Ensure CreateExtension quotes extension names by creating one with a # dash in its name. CreateExtension('uuid-ossp'), HStoreExtension(), TrigramExtension(), UnaccentExtension(), CITextExtension(), ]
4cf5903878beb64d21b2974083b5ebb95d7abe62f436089826170a226ad7fb23
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.serializers.json import DjangoJSONEncoder from django.db import migrations, models from ..fields import ( ArrayField, BigIntegerRangeField, CITextField, DateRangeField, DateTimeRangeField, FloatRangeField, HStoreField, IntegerRangeField, JSONField, SearchVectorField, ) from ..models import TagField class Migration(migrations.Migration): dependencies = [ ('postgres_tests', '0001_setup_extensions'), ] operations = [ migrations.CreateModel( name='CharArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', ArrayField(models.CharField(max_length=10), size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='DateTimeArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('datetimes', ArrayField(models.DateTimeField(), size=None)), ('dates', ArrayField(models.DateField(), size=None)), ('times', ArrayField(models.TimeField(), size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='HStoreModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', HStoreField(blank=True, null=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='OtherTypesArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('ips', ArrayField(models.GenericIPAddressField(), size=None)), ('uuids', ArrayField(models.UUIDField(), size=None)), ('decimals', ArrayField(models.DecimalField(max_digits=5, decimal_places=2), size=None)), ('tags', ArrayField(TagField(), blank=True, null=True, size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='IntegerArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', ArrayField(models.IntegerField(), size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='NestedIntegerArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', ArrayField(ArrayField(models.IntegerField(), size=None), size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='NullableIntegerArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', ArrayField(models.IntegerField(), size=None, null=True, blank=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='CharFieldModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', models.CharField(max_length=16)), ], options=None, bases=None, ), migrations.CreateModel( name='TextFieldModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', models.TextField()), ], options=None, bases=None, ), migrations.CreateModel( name='Scene', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scene', models.CharField(max_length=255)), ('setting', models.CharField(max_length=255)), ], options=None, bases=None, ), migrations.CreateModel( name='Character', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=255)), ], options=None, bases=None, ), migrations.CreateModel( name='CITextTestModel', fields=[ ('name', CITextField(primary_key=True, max_length=255)), ], options={ 'required_db_vendor': 'postgresql', }, bases=None, ), migrations.CreateModel( name='Line', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scene', models.ForeignKey('postgres_tests.Scene', on_delete=models.SET_NULL)), ('character', models.ForeignKey('postgres_tests.Character', on_delete=models.SET_NULL)), ('dialogue', models.TextField(blank=True, null=True)), ('dialogue_search_vector', SearchVectorField(blank=True, null=True)), ('dialogue_config', models.CharField(max_length=100, blank=True, null=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=None, ), migrations.CreateModel( name='AggregateTestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('boolean_field', models.NullBooleanField()), ('char_field', models.CharField(max_length=30, blank=True)), ('integer_field', models.IntegerField(null=True)), ] ), migrations.CreateModel( name='StatTestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('int1', models.IntegerField()), ('int2', models.IntegerField()), ('related_field', models.ForeignKey( 'postgres_tests.AggregateTestModel', models.SET_NULL, null=True, )), ] ), migrations.CreateModel( name='NowTestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('when', models.DateTimeField(null=True, default=None)), ] ), migrations.CreateModel( name='RangesModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('ints', IntegerRangeField(null=True, blank=True)), ('bigints', BigIntegerRangeField(null=True, blank=True)), ('floats', FloatRangeField(null=True, blank=True)), ('timestamps', DateTimeRangeField(null=True, blank=True)), ('dates', DateRangeField(null=True, blank=True)), ], options={ 'required_db_vendor': 'postgresql' }, bases=(models.Model,) ), migrations.CreateModel( name='RangeLookupsModel', fields=[ ('parent', models.ForeignKey( 'postgres_tests.RangesModel', models.SET_NULL, blank=True, null=True, )), ('integer', models.IntegerField(blank=True, null=True)), ('big_integer', models.BigIntegerField(blank=True, null=True)), ('float', models.FloatField(blank=True, null=True)), ('timestamp', models.DateTimeField(blank=True, null=True)), ('date', models.DateField(blank=True, null=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='JSONModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', JSONField(null=True, blank=True)), ('field_custom', JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)), ], options={ 'required_db_features': {'has_jsonb_datatype'}, }, bases=(models.Model,), ), ]
e670bc7eb93292629b4333ecd5d556d482c31b6a8e718d5cff10c00a64079f92
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('postgres_tests', '0001_initial'), ] operations = [ migrations.AddField( model_name='integerarraydefaultmodel', name='field_2', field=django.contrib.postgres.fields.ArrayField(models.IntegerField(), default=[], size=None), preserve_default=False, ), ]
ed1b367cb88a089c7580863cd1362fc635e891a5731a1cf19eb7cc630cc9bb18
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='IntegerArrayDefaultModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', django.contrib.postgres.fields.ArrayField(models.IntegerField(), size=None)), ], options={ }, bases=(models.Model,), ), ]
a401ce7ee4bf59862b2f7c0518767693965ff3f77081207609c060eead4910f4
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='CharTextArrayIndexModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('char', django.contrib.postgres.fields.ArrayField( models.CharField(max_length=10), db_index=True, size=100) ), ('char2', models.CharField(max_length=11, db_index=True)), ('text', django.contrib.postgres.fields.ArrayField(models.TextField(), db_index=True)), ], options={ }, bases=(models.Model,), ), ]
768992bee2e1bca9e9ff631036d4f485b0a10a956f8bb0d1690dfb76339ac721
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def assert_foo_contenttype_not_cached(apps, schema_editor): ContentType = apps.get_model('contenttypes', 'ContentType') try: content_type = ContentType.objects.get_by_natural_key('contenttypes_tests', 'foo') except ContentType.DoesNotExist: pass else: if not ContentType.objects.filter(app_label='contenttypes_tests', model='foo').exists(): raise AssertionError('The contenttypes_tests.Foo ContentType should not be cached.') elif content_type.model != 'foo': raise AssertionError( "The cached contenttypes_tests.Foo ContentType should have " "its model set to 'foo'." ) class Migration(migrations.Migration): dependencies = [ ('contenttypes_tests', '0001_initial'), ] operations = [ migrations.RenameModel('Foo', 'RenamedFoo'), migrations.RunPython(assert_foo_contenttype_not_cached, migrations.RunPython.noop) ]
fefc64a75f313f14b3d00d619ea631bd05707ab4de3d9743d2a5b309d928a0b8
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): operations = [ migrations.CreateModel( 'Foo', [ ('id', models.AutoField(primary_key=True)), ], ), ]
054d46778adaa47a7d98349be0f172701d271b2ef7601a0a909d443bf2fe6944
from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ClearableFileInput from django.utils.encoding import python_2_unicode_compatible from .base import WidgetTest @python_2_unicode_compatible class FakeFieldFile(object): """ Quacks like a FieldFile (has a .url and unicode representation), but doesn't require us to care about storages etc. """ url = 'something' def __str__(self): return self.url class ClearableFileInputTest(WidgetTest): widget = ClearableFileInput() def test_clear_input_renders(self): """ A ClearableFileInput with is_required False and rendered with an initial value that is a file renders a clear checkbox. """ self.check_html(self.widget, 'myfile', FakeFieldFile(), html=( """ Currently: <a href="something">something</a> <input type="checkbox" name="myfile-clear" id="myfile-clear_id" /> <label for="myfile-clear_id">Clear</label><br /> Change: <input type="file" name="myfile" /> """ )) def test_html_escaped(self): """ A ClearableFileInput should escape name, filename, and URL when rendering HTML (#15182). """ @python_2_unicode_compatible class StrangeFieldFile(object): url = "something?chapter=1&sect=2&copy=3&lang=en" def __str__(self): return '''something<div onclick="alert('oops')">.jpg''' self.check_html(ClearableFileInput(), 'my<div>file', StrangeFieldFile(), html=( """ Currently: <a href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"> something&lt;div onclick=&quot;alert(&#39;oops&#39;)&quot;&gt;.jpg</a> <input type="checkbox" name="my&lt;div&gt;file-clear" id="my&lt;div&gt;file-clear_id" /> <label for="my&lt;div&gt;file-clear_id">Clear</label><br /> Change: <input type="file" name="my&lt;div&gt;file" /> """ )) def test_clear_input_renders_only_if_not_required(self): """ A ClearableFileInput with is_required=False does not render a clear checkbox. """ widget = ClearableFileInput() widget.is_required = True self.check_html(widget, 'myfile', FakeFieldFile(), html=( """ Currently: <a href="something">something</a> <br /> Change: <input type="file" name="myfile" /> """ )) def test_clear_input_renders_only_if_initial(self): """ A ClearableFileInput instantiated with no initial value does not render a clear checkbox. """ self.check_html(self.widget, 'myfile', None, html='<input type="file" name="myfile" />') def test_clear_input_checked_returns_false(self): """ ClearableFileInput.value_from_datadict returns False if the clear checkbox is checked, if not required. """ value = self.widget.value_from_datadict( data={'myfile-clear': True}, files={}, name='myfile', ) self.assertIs(value, False) def test_clear_input_checked_returns_false_only_if_not_required(self): """ ClearableFileInput.value_from_datadict never returns False if the field is required. """ widget = ClearableFileInput() widget.is_required = True field = SimpleUploadedFile('something.txt', b'content') value = widget.value_from_datadict( data={'myfile-clear': True}, files={'myfile': field}, name='myfile', ) self.assertEqual(value, field) def test_html_does_not_mask_exceptions(self): """ A ClearableFileInput should not mask exceptions produced while checking that it has a value. """ @python_2_unicode_compatible class FailingURLFieldFile(object): @property def url(self): raise ValueError('Canary') def __str__(self): return 'value' with self.assertRaisesMessage(ValueError, 'Canary'): self.widget.render('myfile', FailingURLFieldFile()) def test_url_as_property(self): @python_2_unicode_compatible class URLFieldFile(object): @property def url(self): return 'https://www.python.org/' def __str__(self): return 'value' html = self.widget.render('myfile', URLFieldFile()) self.assertInHTML('<a href="https://www.python.org/">value</a>', html) def test_return_false_if_url_does_not_exists(self): @python_2_unicode_compatible class NoURLFieldFile(object): def __str__(self): return 'value' html = self.widget.render('myfile', NoURLFieldFile()) self.assertHTMLEqual(html, '<input name="myfile" type="file" />') def test_use_required_attribute(self): # False when initial data exists. The file input is left blank by the # user to keep the existing, initial value. self.assertIs(self.widget.use_required_attribute(None), True) self.assertIs(self.widget.use_required_attribute('resume.txt'), False)
c3f3e870deeb65061db0839a342b3c89049c531c265f15b0c76223bbd22dae28
from django.forms import PasswordInput from .base import WidgetTest class PasswordInputTest(WidgetTest): widget = PasswordInput() def test_render(self): self.check_html(self.widget, 'password', '', html='<input type="password" name="password" />') def test_render_ignore_value(self): self.check_html(self.widget, 'password', 'secret', html='<input type="password" name="password" />') def test_render_value_true(self): """ The render_value argument lets you specify whether the widget should render its value. For security reasons, this is off by default. """ widget = PasswordInput(render_value=True) self.check_html(widget, 'password', '', html='<input type="password" name="password" />') self.check_html(widget, 'password', None, html='<input type="password" name="password" />') self.check_html( widget, 'password', '[email protected]', html='<input type="password" name="password" value="[email protected]" />', )
4a87be1118eda11388ebaba6ea905680a80f5d02774dae49cc9de7856f1221fd
from datetime import datetime from django.forms import DateTimeInput from django.test import override_settings from django.utils import translation from .base import WidgetTest class DateTimeInputTest(WidgetTest): widget = DateTimeInput() def test_render_none(self): self.check_html(self.widget, 'date', None, '<input type="text" name="date" />') def test_render_value(self): """ The microseconds are trimmed on display, by default. """ d = datetime(2007, 9, 17, 12, 51, 34, 482548) self.assertEqual(str(d), '2007-09-17 12:51:34.482548') self.check_html(self.widget, 'date', d, html=( '<input type="text" name="date" value="2007-09-17 12:51:34" />' )) self.check_html(self.widget, 'date', datetime(2007, 9, 17, 12, 51, 34), html=( '<input type="text" name="date" value="2007-09-17 12:51:34" />' )) self.check_html(self.widget, 'date', datetime(2007, 9, 17, 12, 51), html=( '<input type="text" name="date" value="2007-09-17 12:51:00" />' )) def test_render_formatted(self): """ Use 'format' to change the way a value is displayed. """ widget = DateTimeInput( format='%d/%m/%Y %H:%M', attrs={'type': 'datetime'}, ) d = datetime(2007, 9, 17, 12, 51, 34, 482548) self.check_html(widget, 'date', d, html='<input type="datetime" name="date" value="17/09/2007 12:51" />') @override_settings(USE_L10N=True) @translation.override('de-at') def test_l10n(self): d = datetime(2007, 9, 17, 12, 51, 34, 482548) self.check_html(self.widget, 'date', d, html=( '<input type="text" name="date" value="17.09.2007 12:51:34" />' )) @override_settings(USE_L10N=True) @translation.override('de-at') def test_locale_aware(self): d = datetime(2007, 9, 17, 12, 51, 34, 482548) with self.settings(USE_L10N=False): self.check_html( self.widget, 'date', d, html='<input type="text" name="date" value="2007-09-17 12:51:34" />', ) with translation.override('es'): self.check_html( self.widget, 'date', d, html='<input type="text" name="date" value="17/09/2007 12:51:34" />', )
70457a1103a020a6aa777e229e234b6d113aa0c07ac33aa87ae1527f040b932c
from django.forms import CheckboxSelectMultiple from .base import WidgetTest class CheckboxSelectMultipleTest(WidgetTest): widget = CheckboxSelectMultiple def test_render_value(self): self.check_html(self.widget(choices=self.beatles), 'beatles', ['J'], html=( """<ul> <li><label><input checked type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""" )) def test_render_value_multiple(self): self.check_html(self.widget(choices=self.beatles), 'beatles', ['J', 'P'], html=( """<ul> <li><label><input checked type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input checked type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""" )) def test_render_none(self): """ If the value is None, none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatles', None, html=( """<ul> <li><label><input type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""" )) def test_nested_choices(self): nested_choices = ( ('unknown', 'Unknown'), ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))), ) html = """ <ul id="media"> <li> <label for="media_0"><input id="media_0" name="nestchoice" type="checkbox" value="unknown" /> Unknown</label> </li> <li>Audio<ul id="media_1"> <li> <label for="media_1_0"> <input checked id="media_1_0" name="nestchoice" type="checkbox" value="vinyl" /> Vinyl </label> </li> <li> <label for="media_1_1"><input id="media_1_1" name="nestchoice" type="checkbox" value="cd" /> CD</label> </li> </ul></li> <li>Video<ul id="media_2"> <li> <label for="media_2_0"><input id="media_2_0" name="nestchoice" type="checkbox" value="vhs" /> VHS</label> </li> <li> <label for="media_2_1"> <input checked id="media_2_1" name="nestchoice" type="checkbox" value="dvd" /> DVD </label> </li> </ul></li> </ul> """ self.check_html( self.widget(choices=nested_choices), 'nestchoice', ('vinyl', 'dvd'), attrs={'id': 'media'}, html=html, ) def test_separate_ids(self): """ Each input gets a separate ID. """ choices = [('a', 'A'), ('b', 'B'), ('c', 'C')] html = """ <ul id="abc"> <li> <label for="abc_0"><input checked type="checkbox" name="letters" value="a" id="abc_0" /> A</label> </li> <li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1" /> B</label></li> <li> <label for="abc_2"><input checked type="checkbox" name="letters" value="c" id="abc_2" /> C</label> </li> </ul> """ self.check_html(self.widget(choices=choices), 'letters', ['a', 'c'], attrs={'id': 'abc'}, html=html) def test_separate_ids_constructor(self): """ Each input gets a separate ID when the ID is passed to the constructor. """ widget = CheckboxSelectMultiple(attrs={'id': 'abc'}, choices=[('a', 'A'), ('b', 'B'), ('c', 'C')]) html = """ <ul id="abc"> <li> <label for="abc_0"><input checked type="checkbox" name="letters" value="a" id="abc_0" /> A</label> </li> <li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1" /> B</label></li> <li> <label for="abc_2"><input checked type="checkbox" name="letters" value="c" id="abc_2" /> C</label> </li> </ul> """ self.check_html(widget, 'letters', ['a', 'c'], html=html) def test_use_required_attribute(self): widget = self.widget(choices=self.beatles) # Always False because browser validation would require all checkboxes # to be checked instead of at least one. self.assertIs(widget.use_required_attribute(None), False) self.assertIs(widget.use_required_attribute([]), False) self.assertIs(widget.use_required_attribute(['J', 'P']), False) def test_value_omitted_from_data(self): widget = self.widget(choices=self.beatles) self.assertIs(widget.value_omitted_from_data({}, {}, 'field'), False) self.assertIs(widget.value_omitted_from_data({'field': 'value'}, {}, 'field'), False)
c7b1bbea0ac31a0b9511aef0f91c865bcea426a448c15a53bce562789b222e54
from django.test import SimpleTestCase class WidgetTest(SimpleTestCase): beatles = (('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')) def check_html(self, widget, name, value, html='', attrs=None, **kwargs): output = widget.render(name, value, attrs=attrs, **kwargs) self.assertHTMLEqual(output, html)
285d62cca78551cc30577ec1889e0589c66fb98845fb812ac3b9ee4cf8af6ab1
from django.forms import FileInput from .base import WidgetTest class FileInputTest(WidgetTest): widget = FileInput() def test_render(self): """ FileInput widgets never render the value attribute. The old value isn't useful if a form is updated or an error occurred. """ self.check_html(self.widget, 'email', '[email protected]', html='<input type="file" name="email" />') self.check_html(self.widget, 'email', '', html='<input type="file" name="email" />') self.check_html(self.widget, 'email', None, html='<input type="file" name="email" />') def test_value_omitted_from_data(self): self.assertIs(self.widget.value_omitted_from_data({}, {}, 'field'), True) self.assertIs(self.widget.value_omitted_from_data({}, {'field': 'value'}, 'field'), False)
fd3103e3a8e967a9427b02f5f79964ec9fc827b2fb5914e68e3d90516383ccf1
from datetime import date from django.forms import DateInput from django.test import override_settings from django.utils import translation from .base import WidgetTest class DateInputTest(WidgetTest): widget = DateInput() def test_render_none(self): self.check_html(self.widget, 'date', None, html='<input type="text" name="date" />') def test_render_value(self): d = date(2007, 9, 17) self.assertEqual(str(d), '2007-09-17') self.check_html(self.widget, 'date', d, html='<input type="text" name="date" value="2007-09-17" />') self.check_html(self.widget, 'date', date(2007, 9, 17), html=( '<input type="text" name="date" value="2007-09-17" />' )) def test_string(self): """ Should be able to initialize from a string value. """ self.check_html(self.widget, 'date', '2007-09-17', html=( '<input type="text" name="date" value="2007-09-17" />' )) def test_format(self): """ Use 'format' to change the way a value is displayed. """ d = date(2007, 9, 17) widget = DateInput(format='%d/%m/%Y', attrs={'type': 'date'}) self.check_html(widget, 'date', d, html='<input type="date" name="date" value="17/09/2007" />') @override_settings(USE_L10N=True) @translation.override('de-at') def test_l10n(self): self.check_html( self.widget, 'date', date(2007, 9, 17), html='<input type="text" name="date" value="17.09.2007" />', )
2a850deef992c626c34becbc00854213a4e496945b5e259a947e4d878e8bd92b
from django.forms import SelectMultiple from .base import WidgetTest class SelectMultipleTest(WidgetTest): widget = SelectMultiple numeric_choices = (('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('0', 'extra')) def test_render_selected(self): self.check_html(self.widget(choices=self.beatles), 'beatles', ['J'], html=( """<select multiple="multiple" name="beatles"> <option value="J" selected>John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_multiple_selected(self): self.check_html(self.widget(choices=self.beatles), 'beatles', ['J', 'P'], html=( """<select multiple="multiple" name="beatles"> <option value="J" selected>John</option> <option value="P" selected>Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_none(self): """ If the value is None, none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatles', None, html=( """<select multiple="multiple" name="beatles"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_value_label(self): """ If the value corresponds to a label (but not to an option value), none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatles', ['John'], html=( """<select multiple="multiple" name="beatles"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_multiple_options_same_value(self): """ Multiple options with the same value can be selected (#8103). """ self.check_html(self.widget(choices=self.numeric_choices), 'choices', ['0'], html=( """<select multiple="multiple" name="choices"> <option value="0" selected>0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="0" selected>extra</option> </select>""" )) def test_multiple_values_invalid(self): """ If multiple values are given, but some of them are not valid, the valid ones are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatles', ['J', 'G', 'foo'], html=( """<select multiple="multiple" name="beatles"> <option value="J" selected>John</option> <option value="P">Paul</option> <option value="G" selected>George</option> <option value="R">Ringo</option> </select>""" )) def test_compare_string(self): choices = [('1', '1'), ('2', '2'), ('3', '3')] self.check_html(self.widget(choices=choices), 'nums', [2], html=( """<select multiple="multiple" name="nums"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" )) self.check_html(self.widget(choices=choices), 'nums', ['2'], html=( """<select multiple="multiple" name="nums"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" )) self.check_html(self.widget(choices=choices), 'nums', [2], html=( """<select multiple="multiple" name="nums"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" )) def test_optgroup_select_multiple(self): widget = SelectMultiple(choices=( ('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2'))), )) self.check_html(widget, 'nestchoice', ['outer1', 'inner2'], html=( """<select multiple="multiple" name="nestchoice"> <option value="outer1" selected>Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2" selected>Inner 2</option> </optgroup> </select>""" ))
91c6e5bd31b6683ba0720927c65ba6f4416d40a74ce0b871ec70d6123dc77e82
from datetime import date from django.forms import DateField, Form, SelectDateWidget from django.test import override_settings from django.utils import translation from django.utils.dates import MONTHS_AP from .base import WidgetTest class SelectDateWidgetTest(WidgetTest): maxDiff = None widget = SelectDateWidget( years=('2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'), ) def test_render_empty(self): self.check_html(self.widget, 'mydate', '', html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="0">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ )) def test_render_none(self): """ Rendering the None or '' values should yield the same output. """ self.assertHTMLEqual( self.widget.render('mydate', None), self.widget.render('mydate', ''), ) def test_render_string(self): self.check_html(self.widget, 'mydate', '2010-04-15', html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4" selected>April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15" selected>15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="0">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ )) def test_render_datetime(self): self.assertHTMLEqual( self.widget.render('mydate', date(2010, 4, 15)), self.widget.render('mydate', '2010-04-15'), ) def test_render_invalid_date(self): """ Invalid dates should still render the failed date. """ self.check_html(self.widget, 'mydate', '2010-02-31', html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2" selected>February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31" selected>31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="0">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ )) def test_custom_months(self): widget = SelectDateWidget(months=MONTHS_AP, years=('2013',)) self.check_html(widget, 'mydate', '', html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">Jan.</option> <option value="2">Feb.</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">Aug.</option> <option value="9">Sept.</option> <option value="10">Oct.</option> <option value="11">Nov.</option> <option value="12">Dec.</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="0">---</option> <option value="2013">2013</option> </select> """ )) def test_selectdate_required(self): class GetNotRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=False) class GetRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=True) self.assertFalse(GetNotRequiredDate().fields['mydate'].widget.is_required) self.assertTrue(GetRequiredDate().fields['mydate'].widget.is_required) def test_selectdate_empty_label(self): w = SelectDateWidget(years=('2014',), empty_label='empty_label') # Rendering the default state with empty_label setted as string. self.assertInHTML('<option value="0">empty_label</option>', w.render('mydate', ''), count=3) w = SelectDateWidget(years=('2014',), empty_label=('empty_year', 'empty_month', 'empty_day')) # Rendering the default state with empty_label tuple. self.assertHTMLEqual( w.render('mydate', ''), """ <select name="mydate_month" id="id_mydate_month"> <option value="0">empty_month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="0">empty_day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="0">empty_year</option> <option value="2014">2014</option> </select> """, ) with self.assertRaisesMessage(ValueError, 'empty_label list/tuple must have 3 elements.'): SelectDateWidget(years=('2014',), empty_label=('not enough', 'values')) @override_settings(USE_L10N=True) @translation.override('nl') def test_l10n(self): w = SelectDateWidget( years=('2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016') ) self.assertEqual( w.value_from_datadict({'date_year': '2010', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-2010', ) self.assertHTMLEqual( w.render('date', '13-08-2010'), """ <select name="date_day" id="id_date_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13" selected>13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="date_month" id="id_date_month"> <option value="0">---</option> <option value="1">januari</option> <option value="2">februari</option> <option value="3">maart</option> <option value="4">april</option> <option value="5">mei</option> <option value="6">juni</option> <option value="7">juli</option> <option value="8" selected>augustus</option> <option value="9">september</option> <option value="10">oktober</option> <option value="11">november</option> <option value="12">december</option> </select> <select name="date_year" id="id_date_year"> <option value="0">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """, ) # Even with an invalid date, the widget should reflect the entered value (#17401). self.assertEqual(w.render('mydate', '2010-02-30').count('selected'), 3) # Years before 1900 should work. w = SelectDateWidget(years=('1899',)) self.assertEqual( w.value_from_datadict({'date_year': '1899', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-1899', ) def test_value_omitted_from_data(self): self.assertIs(self.widget.value_omitted_from_data({}, {}, 'field'), True) self.assertIs(self.widget.value_omitted_from_data({'field_month': '12'}, {}, 'field'), False) self.assertIs(self.widget.value_omitted_from_data({'field_year': '2000'}, {}, 'field'), False) self.assertIs(self.widget.value_omitted_from_data({'field_day': '1'}, {}, 'field'), False) data = {'field_day': '1', 'field_month': '12', 'field_year': '2000'} self.assertIs(self.widget.value_omitted_from_data(data, {}, 'field'), False)
865a3ab849b0fdf6983e87519c352e2751faa3eee7f16ebeb70db28fe62afeee
from datetime import date, datetime, time from django.forms import SplitDateTimeWidget from .base import WidgetTest class SplitDateTimeWidgetTest(WidgetTest): widget = SplitDateTimeWidget() def test_render_empty(self): self.check_html(self.widget, 'date', '', html=( '<input type="text" name="date_0" /><input type="text" name="date_1" />' )) def test_render_none(self): self.check_html(self.widget, 'date', None, html=( '<input type="text" name="date_0" /><input type="text" name="date_1" />' )) def test_render_datetime(self): self.check_html(self.widget, 'date', datetime(2006, 1, 10, 7, 30), html=( '<input type="text" name="date_0" value="2006-01-10" />' '<input type="text" name="date_1" value="07:30:00" />' )) def test_render_date_and_time(self): self.check_html(self.widget, 'date', [date(2006, 1, 10), time(7, 30)], html=( '<input type="text" name="date_0" value="2006-01-10" />' '<input type="text" name="date_1" value="07:30:00" />' )) def test_constructor_attrs(self): widget = SplitDateTimeWidget(attrs={'class': 'pretty'}) self.check_html(widget, 'date', datetime(2006, 1, 10, 7, 30), html=( '<input type="text" class="pretty" value="2006-01-10" name="date_0" />' '<input type="text" class="pretty" value="07:30:00" name="date_1" />' )) def test_formatting(self): """ Use 'date_format' and 'time_format' to change the way a value is displayed. """ widget = SplitDateTimeWidget( date_format='%d/%m/%Y', time_format='%H:%M', ) self.check_html(widget, 'date', datetime(2006, 1, 10, 7, 30), html=( '<input type="text" name="date_0" value="10/01/2006" />' '<input type="text" name="date_1" value="07:30" />' ))
1649584349bfe2e092bfcc5e58be077141d6e0a717eb3af6e58961a3070ce02f
import copy from datetime import datetime from django.forms import ( CharField, FileInput, MultipleChoiceField, MultiValueField, MultiWidget, RadioSelect, SelectMultiple, SplitDateTimeField, SplitDateTimeWidget, TextInput, ) from .base import WidgetTest class MyMultiWidget(MultiWidget): def decompress(self, value): if value: return value.split('__') return ['', ''] class ComplexMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = ( TextInput(), SelectMultiple(choices=WidgetTest.beatles), SplitDateTimeWidget(), ) super(ComplexMultiWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: data = value.split(',') return [ data[0], list(data[1]), datetime.strptime(data[2], "%Y-%m-%d %H:%M:%S") ] return [None, None, None] def format_output(self, rendered_widgets): return '\n'.join(rendered_widgets) class ComplexField(MultiValueField): def __init__(self, required=True, widget=None, label=None, initial=None): fields = ( CharField(), MultipleChoiceField(choices=WidgetTest.beatles), SplitDateTimeField(), ) super(ComplexField, self).__init__( fields, required, widget, label, initial, ) def compress(self, data_list): if data_list: return '%s,%s,%s' % ( data_list[0], ''.join(data_list[1]), data_list[2], ) return None class DeepCopyWidget(MultiWidget): """ Used to test MultiWidget.__deepcopy__(). """ def __init__(self, choices=[]): widgets = [ RadioSelect(choices=choices), TextInput, ] super(DeepCopyWidget, self).__init__(widgets) def _set_choices(self, choices): """ When choices are set for this widget, we want to pass those along to the Select widget. """ self.widgets[0].choices = choices def _get_choices(self): """ The choices for this widget are the Select widget's choices. """ return self.widgets[0].choices choices = property(_get_choices, _set_choices) class MultiWidgetTest(WidgetTest): def test_text_inputs(self): widget = MyMultiWidget( widgets=( TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'}), ) ) self.check_html(widget, 'name', ['john', 'lennon'], html=( '<input type="text" class="big" value="john" name="name_0" />' '<input type="text" class="small" value="lennon" name="name_1" />' )) self.check_html(widget, 'name', 'john__lennon', html=( '<input type="text" class="big" value="john" name="name_0" />' '<input type="text" class="small" value="lennon" name="name_1" />' )) self.check_html(widget, 'name', 'john__lennon', attrs={'id': 'foo'}, html=( '<input id="foo_0" type="text" class="big" value="john" name="name_0" />' '<input id="foo_1" type="text" class="small" value="lennon" name="name_1" />' )) def test_constructor_attrs(self): widget = MyMultiWidget( widgets=( TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'}), ), attrs={'id': 'bar'}, ) self.check_html(widget, 'name', ['john', 'lennon'], html=( '<input id="bar_0" type="text" class="big" value="john" name="name_0" />' '<input id="bar_1" type="text" class="small" value="lennon" name="name_1" />' )) def test_value_omitted_from_data(self): widget = MyMultiWidget(widgets=(TextInput(), TextInput())) self.assertIs(widget.value_omitted_from_data({}, {}, 'field'), True) self.assertIs(widget.value_omitted_from_data({'field_0': 'x'}, {}, 'field'), False) self.assertIs(widget.value_omitted_from_data({'field_1': 'y'}, {}, 'field'), False) self.assertIs(widget.value_omitted_from_data({'field_0': 'x', 'field_1': 'y'}, {}, 'field'), False) def test_needs_multipart_true(self): """ needs_multipart_form should be True if any widgets need it. """ widget = MyMultiWidget(widgets=(TextInput(), FileInput())) self.assertTrue(widget.needs_multipart_form) def test_needs_multipart_false(self): """ needs_multipart_form should be False if no widgets need it. """ widget = MyMultiWidget(widgets=(TextInput(), TextInput())) self.assertFalse(widget.needs_multipart_form) def test_nested_multiwidget(self): """ MultiWidgets can be composed of other MultiWidgets. """ widget = ComplexMultiWidget() self.check_html(widget, 'name', 'some text,JP,2007-04-25 06:24:00', html=( """ <input type="text" name="name_0" value="some text" /> <select multiple="multiple" name="name_1"> <option value="J" selected>John</option> <option value="P" selected>Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select> <input type="text" name="name_2_0" value="2007-04-25" /> <input type="text" name="name_2_1" value="06:24:00" /> """ )) def test_deepcopy(self): """ MultiWidget should define __deepcopy__() (#12048). """ w1 = DeepCopyWidget(choices=[1, 2, 3]) w2 = copy.deepcopy(w1) w2.choices = [4, 5, 6] # w2 ought to be independent of w1, since MultiWidget ought # to make a copy of its sub-widgets when it is copied. self.assertEqual(w1.choices, [1, 2, 3])
d10c4a62158180d8f44aff9f59b768e134744ba8d5f16b4ee6f5374a2ac3b11f
from datetime import datetime from django.forms import SplitHiddenDateTimeWidget from django.test import override_settings from django.utils import translation from .base import WidgetTest class SplitHiddenDateTimeWidgetTest(WidgetTest): widget = SplitHiddenDateTimeWidget() def test_render_empty(self): self.check_html(self.widget, 'date', '', html=( '<input type="hidden" name="date_0" /><input type="hidden" name="date_1" />' )) def test_render_value(self): d = datetime(2007, 9, 17, 12, 51, 34, 482548) self.check_html(self.widget, 'date', d, html=( '<input type="hidden" name="date_0" value="2007-09-17" />' '<input type="hidden" name="date_1" value="12:51:34" />' )) self.check_html(self.widget, 'date', datetime(2007, 9, 17, 12, 51, 34), html=( '<input type="hidden" name="date_0" value="2007-09-17" />' '<input type="hidden" name="date_1" value="12:51:34" />' )) self.check_html(self.widget, 'date', datetime(2007, 9, 17, 12, 51), html=( '<input type="hidden" name="date_0" value="2007-09-17" />' '<input type="hidden" name="date_1" value="12:51:00" />' )) @override_settings(USE_L10N=True) @translation.override('de-at') def test_l10n(self): d = datetime(2007, 9, 17, 12, 51) self.check_html(self.widget, 'date', d, html=( """ <input type="hidden" name="date_0" value="17.09.2007" /> <input type="hidden" name="date_1" value="12:51:00" /> """ ))
af06f38dd25be13079896749ff94181c9e2e6ec92ccb54e2b80119011488f8fd
from django.forms import CheckboxInput from .base import WidgetTest class CheckboxInputTest(WidgetTest): widget = CheckboxInput() def test_render_empty(self): self.check_html(self.widget, 'is_cool', '', html='<input type="checkbox" name="is_cool" />') def test_render_none(self): self.check_html(self.widget, 'is_cool', None, html='<input type="checkbox" name="is_cool" />') def test_render_false(self): self.check_html(self.widget, 'is_cool', False, html='<input type="checkbox" name="is_cool" />') def test_render_true(self): self.check_html( self.widget, 'is_cool', True, html='<input checked type="checkbox" name="is_cool" />' ) def test_render_value(self): """ Using any value that's not in ('', None, False, True) will check the checkbox and set the 'value' attribute. """ self.check_html( self.widget, 'is_cool', 'foo', html='<input checked type="checkbox" name="is_cool" value="foo" />', ) def test_render_int(self): """ Integers are handled by value, not as booleans (#17114). """ self.check_html( self.widget, 'is_cool', 0, html='<input checked type="checkbox" name="is_cool" value="0" />', ) self.check_html( self.widget, 'is_cool', 1, html='<input checked type="checkbox" name="is_cool" value="1" />', ) def test_render_check_test(self): """ You can pass 'check_test' to the constructor. This is a callable that takes the value and returns True if the box should be checked. """ widget = CheckboxInput(check_test=lambda value: value.startswith('hello')) self.check_html(widget, 'greeting', '', html=( '<input type="checkbox" name="greeting" />' )) self.check_html(widget, 'greeting', 'hello', html=( '<input checked type="checkbox" name="greeting" value="hello" />' )) self.check_html(widget, 'greeting', 'hello there', html=( '<input checked type="checkbox" name="greeting" value="hello there" />' )) self.check_html(widget, 'greeting', 'hello & goodbye', html=( '<input checked type="checkbox" name="greeting" value="hello &amp; goodbye" />' )) def test_render_check_exception(self): """ Calling check_test() shouldn't swallow exceptions (#17888). """ widget = CheckboxInput( check_test=lambda value: value.startswith('hello'), ) with self.assertRaises(AttributeError): widget.render('greeting', True) def test_value_from_datadict(self): """ The CheckboxInput widget will return False if the key is not found in the data dictionary (because HTML form submission doesn't send any result for unchecked checkboxes). """ self.assertFalse(self.widget.value_from_datadict({}, {}, 'testing')) def test_value_from_datadict_string_int(self): value = self.widget.value_from_datadict({'testing': '0'}, {}, 'testing') self.assertIs(value, True) def test_value_omitted_from_data(self): self.assertIs(self.widget.value_omitted_from_data({'field': 'value'}, {}, 'field'), False) self.assertIs(self.widget.value_omitted_from_data({}, {}, 'field'), False)
ae03935ea3cfb2717532f486bab7cfe02de60a059040130bec298a1aefe10222
from django.forms import HiddenInput from .base import WidgetTest class HiddenInputTest(WidgetTest): widget = HiddenInput() def test_render(self): self.check_html(self.widget, 'email', '', html='<input type="hidden" name="email" />') def test_use_required_attribute(self): # Always False to avoid browser validation on inputs hidden from the # user. self.assertIs(self.widget.use_required_attribute(None), False) self.assertIs(self.widget.use_required_attribute(''), False) self.assertIs(self.widget.use_required_attribute('foo'), False)
ad0afc4cef920c0bad01b8e2712093f53aba65b6fa17c1709759fccab5499385
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import TextInput from django.utils.safestring import mark_safe from .base import WidgetTest class TextInputTest(WidgetTest): widget = TextInput() def test_render(self): self.check_html(self.widget, 'email', '', html='<input type="text" name="email" />') def test_render_none(self): self.check_html(self.widget, 'email', None, html='<input type="text" name="email" />') def test_render_value(self): self.check_html(self.widget, 'email', '[email protected]', html=( '<input type="text" name="email" value="[email protected]" />' )) def test_render_boolean(self): """ Boolean values are rendered to their string forms ("True" and "False"). """ self.check_html(self.widget, 'get_spam', False, html=( '<input type="text" name="get_spam" value="False" />' )) self.check_html(self.widget, 'get_spam', True, html=( '<input type="text" name="get_spam" value="True" />' )) def test_render_quoted(self): self.check_html( self.widget, 'email', 'some "quoted" & ampersanded value', html='<input type="text" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />', ) def test_render_custom_attrs(self): self.check_html( self.widget, 'email', '[email protected]', attrs={'class': 'fun'}, html='<input type="text" name="email" value="[email protected]" class="fun" />', ) def test_render_unicode(self): self.check_html( self.widget, 'email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}, html=( '<input type="text" name="email" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun" />' ), ) def test_constructor_attrs(self): widget = TextInput(attrs={'class': 'fun', 'type': 'email'}) self.check_html(widget, 'email', '', html='<input type="email" class="fun" name="email" />') self.check_html( widget, 'email', '[email protected]', html='<input type="email" class="fun" value="[email protected]" name="email" />', ) def test_attrs_precedence(self): """ `attrs` passed to render() get precedence over those passed to the constructor """ widget = TextInput(attrs={'class': 'pretty'}) self.check_html( widget, 'email', '', attrs={'class': 'special'}, html='<input type="text" class="special" name="email" />', ) def test_attrs_safestring(self): widget = TextInput(attrs={'onBlur': mark_safe("function('foo')")}) self.check_html(widget, 'email', '', html='<input onBlur="function(\'foo\')" type="text" name="email" />') def test_use_required_attribute(self): # Text inputs can safely trigger the browser validation. self.assertIs(self.widget.use_required_attribute(None), True) self.assertIs(self.widget.use_required_attribute(''), True) self.assertIs(self.widget.use_required_attribute('resume.txt'), True)
5eaf768b51a9c956d2c90981fab59255de275f66cca3b49cdc6740d41364fdb0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import copy from django.forms import Select from django.utils.safestring import mark_safe from .base import WidgetTest class SelectTest(WidgetTest): widget = Select nested_widget = Select(choices=( ('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2'))), )) def test_render(self): self.check_html(self.widget(choices=self.beatles), 'beatle', 'J', html=( """<select name="beatle"> <option value="J" selected>John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_none(self): """ If the value is None, none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatle', None, html=( """<select name="beatle"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_label_value(self): """ If the value corresponds to a label (but not to an option value), none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatle', 'John', html=( """<select name="beatle"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_selected(self): """ Only one option can be selected (#8103). """ choices = [('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('0', 'extra')] self.check_html(self.widget(choices=choices), 'choices', '0', html=( """<select name="choices"> <option value="0" selected>0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="0">extra</option> </select>""" )) def test_constructor_attrs(self): """ Select options shouldn't inherit the parent widget attrs. """ widget = Select( attrs={'class': 'super', 'id': 'super'}, choices=[(1, 1), (2, 2), (3, 3)], ) self.check_html(widget, 'num', 2, html=( """<select name="num" class="super" id="super"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" )) def test_compare_to_str(self): """ The value is compared to its str(). """ self.check_html( self.widget(choices=[('1', '1'), ('2', '2'), ('3', '3')]), 'num', 2, html=( """<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" ), ) self.check_html( self.widget(choices=[(1, 1), (2, 2), (3, 3)]), 'num', '2', html=( """<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" ), ) self.check_html( self.widget(choices=[(1, 1), (2, 2), (3, 3)]), 'num', 2, html=( """<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" ), ) def test_choices_constuctor(self): widget = Select(choices=[(1, 1), (2, 2), (3, 3)]) self.check_html(widget, 'num', 2, html=( """<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" )) def test_choices_constructor_generator(self): """ If choices is passed to the constructor and is a generator, it can be iterated over multiple times without getting consumed. """ def get_choices(): for i in range(5): yield (i, i) widget = Select(choices=get_choices()) self.check_html(widget, 'num', 2, html=( """<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> <option value="4">4</option> </select>""" )) self.check_html(widget, 'num', 3, html=( """<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3" selected>3</option> <option value="4">4</option> </select>""" )) def test_choices_escaping(self): choices = (('bad', 'you & me'), ('good', mark_safe('you &gt; me'))) self.check_html(self.widget(choices=choices), 'escape', None, html=( """<select name="escape"> <option value="bad">you &amp; me</option> <option value="good">you &gt; me</option> </select>""" )) def test_choices_unicode(self): self.check_html( self.widget(choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), 'email', 'ŠĐĆŽćžšđ', html=( """<select name="email"> <option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111 </option> <option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option> </select>""" ), ) def test_choices_optgroup(self): """ Choices can be nested one level in order to create HTML optgroups. """ self.check_html(self.nested_widget, 'nestchoice', None, html=( """<select name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""" )) def test_choices_select_outer(self): self.check_html(self.nested_widget, 'nestchoice', 'outer1', html=( """<select name="nestchoice"> <option value="outer1" selected>Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""" )) def test_choices_select_inner(self): self.check_html(self.nested_widget, 'nestchoice', 'inner1', html=( """<select name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1" selected>Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""" )) def test_deepcopy(self): """ __deepcopy__() should copy all attributes properly (#25085). """ widget = Select() obj = copy.deepcopy(widget) self.assertIsNot(widget, obj) self.assertEqual(widget.choices, obj.choices) self.assertIsNot(widget.choices, obj.choices) self.assertEqual(widget.attrs, obj.attrs) self.assertIsNot(widget.attrs, obj.attrs)
11fc2e1b3977a8408f11d4bef4f521d773867d000fb56ece112f205f8b4da28e
from django.forms import NullBooleanSelect from django.test import override_settings from django.utils import translation from .base import WidgetTest class NullBooleanSelectTest(WidgetTest): widget = NullBooleanSelect() def test_render_true(self): self.check_html(self.widget, 'is_cool', True, html=( """<select name="is_cool"> <option value="1">Unknown</option> <option value="2" selected>Yes</option> <option value="3">No</option> </select>""" )) def test_render_false(self): self.check_html(self.widget, 'is_cool', False, html=( """<select name="is_cool"> <option value="1">Unknown</option> <option value="2">Yes</option> <option value="3" selected>No</option> </select>""" )) def test_render_none(self): self.check_html(self.widget, 'is_cool', None, html=( """<select name="is_cool"> <option value="1" selected>Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select>""" )) def test_render_value(self): self.check_html(self.widget, 'is_cool', '2', html=( """<select name="is_cool"> <option value="1">Unknown</option> <option value="2" selected>Yes</option> <option value="3">No</option> </select>""" )) @override_settings(USE_L10N=True) def test_l10n(self): """ Ensure that the NullBooleanSelect widget's options are lazily localized (#17190). """ widget = NullBooleanSelect() with translation.override('de-at'): self.check_html(widget, 'id_bool', True, html=( """ <select name="id_bool"> <option value="1">Unbekannt</option> <option value="2" selected>Ja</option> <option value="3">Nein</option> </select> """ ))
68160b496886d7237963728051574ab8e0943de3fb07b8b4a42f08aaecbe75db
from __future__ import unicode_literals from django.forms import Widget from django.test import SimpleTestCase class WidgetTests(SimpleTestCase): def test_value_omitted_from_data(self): widget = Widget() self.assertIs(widget.value_omitted_from_data({}, {}, 'field'), True) self.assertIs(widget.value_omitted_from_data({'field': 'value'}, {}, 'field'), False)
c89f3f4647a17c9de0c0877ad8df517ebf69ac2e71229c8fc914f41749c79e83
from datetime import time from django.forms import TimeInput from django.test import override_settings from django.utils import translation from .base import WidgetTest class TimeInputTest(WidgetTest): widget = TimeInput() def test_render_none(self): self.check_html(self.widget, 'time', None, html='<input type="text" name="time" />') def test_render_value(self): """ The microseconds are trimmed on display, by default. """ t = time(12, 51, 34, 482548) self.assertEqual(str(t), '12:51:34.482548') self.check_html(self.widget, 'time', t, html='<input type="text" name="time" value="12:51:34" />') self.check_html(self.widget, 'time', time(12, 51, 34), html=( '<input type="text" name="time" value="12:51:34" />' )) self.check_html(self.widget, 'time', time(12, 51), html=( '<input type="text" name="time" value="12:51:00" />' )) def test_string(self): """ We should be able to initialize from a unicode value. """ self.check_html(self.widget, 'time', '13:12:11', html=( '<input type="text" name="time" value="13:12:11" />' )) def test_format(self): """ Use 'format' to change the way a value is displayed. """ t = time(12, 51, 34, 482548) widget = TimeInput(format='%H:%M', attrs={'type': 'time'}) self.check_html(widget, 'time', t, html='<input type="time" name="time" value="12:51" />') @override_settings(USE_L10N=True) @translation.override('de-at') def test_l10n(self): t = time(12, 51, 34, 482548) self.check_html(self.widget, 'time', t, html='<input type="text" name="time" value="12:51:34" />')
fa5b6505bc62f31d3f02f5dace7ce1634ad012054632e6401afbff95bf93ca25
from django.forms import MultipleHiddenInput from .base import WidgetTest class MultipleHiddenInputTest(WidgetTest): widget = MultipleHiddenInput() def test_render_single(self): self.check_html( self.widget, 'email', ['[email protected]'], html='<input type="hidden" name="email" value="[email protected]" />', ) def test_render_multiple(self): self.check_html( self.widget, 'email', ['[email protected]', '[email protected]'], html=( '<input type="hidden" name="email" value="[email protected]" />\n' '<input type="hidden" name="email" value="[email protected]" />' ), ) def test_render_attrs(self): self.check_html( self.widget, 'email', ['[email protected]'], attrs={'class': 'fun'}, html='<input type="hidden" name="email" value="[email protected]" class="fun" />', ) def test_render_attrs_multiple(self): self.check_html( self.widget, 'email', ['[email protected]', '[email protected]'], attrs={'class': 'fun'}, html=( '<input type="hidden" name="email" value="[email protected]" class="fun" />\n' '<input type="hidden" name="email" value="[email protected]" class="fun" />' ), ) def test_render_attrs_constructor(self): widget = MultipleHiddenInput(attrs={'class': 'fun'}) self.check_html(widget, 'email', [], '') self.check_html( widget, 'email', ['[email protected]'], html='<input type="hidden" class="fun" value="[email protected]" name="email" />', ) self.check_html( widget, 'email', ['[email protected]', '[email protected]'], html=( '<input type="hidden" class="fun" value="[email protected]" name="email" />\n' '<input type="hidden" class="fun" value="[email protected]" name="email" />' ), ) self.check_html( widget, 'email', ['[email protected]'], attrs={'class': 'special'}, html='<input type="hidden" class="special" value="[email protected]" name="email" />', ) def test_render_empty(self): self.check_html(self.widget, 'email', [], '') def test_render_none(self): self.check_html(self.widget, 'email', None, '') def test_render_increment_id(self): """ Each input should get a separate ID. """ self.check_html( self.widget, 'letters', ['a', 'b', 'c'], attrs={'id': 'hideme'}, html=( '<input type="hidden" name="letters" value="a" id="hideme_0" />\n' '<input type="hidden" name="letters" value="b" id="hideme_1" />\n' '<input type="hidden" name="letters" value="c" id="hideme_2" />' ), )
435b037a23d345c4deb3b10c951df858ebc899b3d130994bb6eb3ab112e9c12e
from django.forms import RadioSelect from .base import WidgetTest class RadioSelectTest(WidgetTest): widget = RadioSelect def test_render(self): self.check_html(self.widget(choices=self.beatles), 'beatle', 'J', html=( """<ul> <li><label><input checked type="radio" name="beatle" value="J" /> John</label></li> <li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> <li><label><input type="radio" name="beatle" value="G" /> George</label></li> <li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> </ul>""" )) def test_nested_choices(self): nested_choices = ( ('unknown', 'Unknown'), ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))), ) html = """ <ul id="media"> <li> <label for="media_0"><input id="media_0" name="nestchoice" type="radio" value="unknown" /> Unknown</label> </li> <li>Audio<ul id="media_1"> <li> <label for="media_1_0"><input id="media_1_0" name="nestchoice" type="radio" value="vinyl" /> Vinyl</label> </li> <li><label for="media_1_1"><input id="media_1_1" name="nestchoice" type="radio" value="cd" /> CD</label></li> </ul></li> <li>Video<ul id="media_2"> <li><label for="media_2_0"><input id="media_2_0" name="nestchoice" type="radio" value="vhs" /> VHS</label></li> <li> <label for="media_2_1"> <input checked id="media_2_1" name="nestchoice" type="radio" value="dvd" /> DVD </label> </li> </ul></li> </ul> """ self.check_html( self.widget(choices=nested_choices), 'nestchoice', 'dvd', attrs={'id': 'media'}, html=html, ) def test_constructor_attrs(self): """ Attributes provided at instantiation are passed to the constituent inputs. """ widget = RadioSelect(attrs={'id': 'foo'}, choices=self.beatles) html = """ <ul id="foo"> <li> <label for="foo_0"><input checked type="radio" id="foo_0" value="J" name="beatle" /> John</label> </li> <li><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle" /> Paul</label></li> <li><label for="foo_2"><input type="radio" id="foo_2" value="G" name="beatle" /> George</label></li> <li><label for="foo_3"><input type="radio" id="foo_3" value="R" name="beatle" /> Ringo</label></li> </ul> """ self.check_html(widget, 'beatle', 'J', html=html) def test_render_attrs(self): """ Attributes provided at render-time are passed to the constituent inputs. """ html = """ <ul id="bar"> <li> <label for="bar_0"><input checked type="radio" id="bar_0" value="J" name="beatle" /> John</label> </li> <li><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle" /> Paul</label></li> <li><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle" /> George</label></li> <li><label for="bar_3"><input type="radio" id="bar_3" value="R" name="beatle" /> Ringo</label></li> </ul> """ self.check_html(self.widget(choices=self.beatles), 'beatle', 'J', attrs={'id': 'bar'}, html=html)
74f3aaed2655476c519075a1b9a08e91ff54c7ecb598c7033f9a5282541f31ac
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import IntegerField, Textarea, ValidationError from django.test import SimpleTestCase from . import FormFieldAssertionsMixin class IntegerFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_integerfield_1(self): f = IntegerField() self.assertWidgetRendersTo(f, '<input type="number" name="f" id="id_f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(1, f.clean('1')) self.assertIsInstance(f.clean('1'), int) self.assertEqual(23, f.clean('23')) with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): f.clean('a') self.assertEqual(42, f.clean(42)) with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): f.clean(3.14) self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): f.clean('1a') self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_integerfield_2(self): f = IntegerField(required=False) self.assertIsNone(f.clean('')) self.assertEqual('None', repr(f.clean(''))) self.assertIsNone(f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertEqual(1, f.clean('1')) self.assertIsInstance(f.clean('1'), int) self.assertEqual(23, f.clean('23')) with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): f.clean('a') self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): f.clean('1a') self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_integerfield_3(self): f = IntegerField(max_value=10) self.assertWidgetRendersTo(f, '<input max="10" type="number" name="f" id="id_f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(1, f.clean(1)) self.assertEqual(10, f.clean(10)) with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"): f.clean(11) self.assertEqual(10, f.clean('10')) with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"): f.clean('11') self.assertEqual(f.max_value, 10) self.assertIsNone(f.min_value) def test_integerfield_4(self): f = IntegerField(min_value=10) self.assertWidgetRendersTo(f, '<input id="id_f" type="number" name="f" min="10" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"): f.clean(1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) self.assertIsNone(f.max_value) self.assertEqual(f.min_value, 10) def test_integerfield_5(self): f = IntegerField(min_value=10, max_value=20) self.assertWidgetRendersTo(f, '<input id="id_f" max="20" type="number" name="f" min="10" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"): f.clean(1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) self.assertEqual(20, f.clean(20)) with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'"): f.clean(21) self.assertEqual(f.max_value, 20) self.assertEqual(f.min_value, 10) def test_integerfield_localized(self): """ A localized IntegerField's widget renders to a text input without any number input specific attributes. """ f1 = IntegerField(localize=True) self.assertWidgetRendersTo(f1, '<input id="id_f" name="f" type="text" required />') def test_integerfield_float(self): f = IntegerField() self.assertEqual(1, f.clean(1.0)) self.assertEqual(1, f.clean('1.0')) self.assertEqual(1, f.clean(' 1.0 ')) self.assertEqual(1, f.clean('1.')) self.assertEqual(1, f.clean(' 1. ')) with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): f.clean('1.5') with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): f.clean('…') def test_integerfield_big_num(self): f = IntegerField() self.assertEqual(9223372036854775808, f.clean(9223372036854775808)) self.assertEqual(9223372036854775808, f.clean('9223372036854775808')) self.assertEqual(9223372036854775808, f.clean('9223372036854775808.0')) def test_integerfield_unicode_number(self): f = IntegerField() self.assertEqual(50, f.clean('50')) def test_integerfield_subclass(self): """ Class-defined widget is not overwritten by __init__() (#22245). """ class MyIntegerField(IntegerField): widget = Textarea f = MyIntegerField() self.assertEqual(f.widget.__class__, Textarea) f = MyIntegerField(localize=True) self.assertEqual(f.widget.__class__, Textarea)
946fa44e448efb15144d70242c0b76772c9a49f7fb047a3586e1b5f94bb45667
# -*- coding: utf-8 -*- from datetime import date, datetime from django.forms import ( DateField, Form, HiddenInput, SelectDateWidget, ValidationError, ) from django.test import SimpleTestCase, override_settings from django.utils import translation class GetDate(Form): mydate = DateField(widget=SelectDateWidget) class DateFieldTest(SimpleTestCase): def test_form_field(self): a = GetDate({'mydate_month': '4', 'mydate_day': '1', 'mydate_year': '2008'}) self.assertTrue(a.is_valid()) self.assertEqual(a.cleaned_data['mydate'], date(2008, 4, 1)) # As with any widget that implements get_value_from_datadict(), we must # accept the input from the "as_hidden" rendering as well. self.assertHTMLEqual( a['mydate'].as_hidden(), '<input type="hidden" name="mydate" value="2008-4-1" id="id_mydate" />', ) b = GetDate({'mydate': '2008-4-1'}) self.assertTrue(b.is_valid()) self.assertEqual(b.cleaned_data['mydate'], date(2008, 4, 1)) # Invalid dates shouldn't be allowed c = GetDate({'mydate_month': '2', 'mydate_day': '31', 'mydate_year': '2010'}) self.assertFalse(c.is_valid()) self.assertEqual(c.errors, {'mydate': ['Enter a valid date.']}) # label tag is correctly associated with month dropdown d = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'}) self.assertIn('<label for="id_mydate_month">', d.as_p()) @override_settings(USE_L10N=True) @translation.override('nl') def test_l10n_date_changed(self): """ DateField.has_changed() with SelectDateWidget works with a localized date format (#17165). """ # With Field.show_hidden_initial=False b = GetDate({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '1', }, initial={'mydate': date(2008, 4, 1)}) self.assertFalse(b.has_changed()) b = GetDate({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '2', }, initial={'mydate': date(2008, 4, 1)}) self.assertTrue(b.has_changed()) # With Field.show_hidden_initial=True class GetDateShowHiddenInitial(Form): mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True) b = GetDateShowHiddenInitial({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '1', 'initial-mydate': HiddenInput().format_value(date(2008, 4, 1)), }, initial={'mydate': date(2008, 4, 1)}) self.assertFalse(b.has_changed()) b = GetDateShowHiddenInitial({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput().format_value(date(2008, 4, 1)), }, initial={'mydate': date(2008, 4, 1)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput().format_value(date(2008, 4, 1)), }, initial={'mydate': date(2008, 4, 22)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput().format_value(date(2008, 4, 22)), }, initial={'mydate': date(2008, 4, 1)}) self.assertFalse(b.has_changed()) @override_settings(USE_L10N=True) @translation.override('nl') def test_l10n_invalid_date_in(self): # Invalid dates shouldn't be allowed a = GetDate({'mydate_month': '2', 'mydate_day': '31', 'mydate_year': '2010'}) self.assertFalse(a.is_valid()) # 'Geef een geldige datum op.' = 'Enter a valid date.' self.assertEqual(a.errors, {'mydate': ['Geef een geldige datum op.']}) @override_settings(USE_L10N=True) @translation.override('nl') def test_form_label_association(self): # label tag is correctly associated with first rendered dropdown a = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'}) self.assertIn('<label for="id_mydate_day">', a.as_p()) def test_datefield_1(self): f = DateField() self.assertEqual(date(2006, 10, 25), f.clean(date(2006, 10, 25))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(date(2006, 10, 25), f.clean('2006-10-25')) self.assertEqual(date(2006, 10, 25), f.clean('10/25/2006')) self.assertEqual(date(2006, 10, 25), f.clean('10/25/06')) self.assertEqual(date(2006, 10, 25), f.clean('Oct 25 2006')) self.assertEqual(date(2006, 10, 25), f.clean('October 25 2006')) self.assertEqual(date(2006, 10, 25), f.clean('October 25, 2006')) self.assertEqual(date(2006, 10, 25), f.clean('25 October 2006')) self.assertEqual(date(2006, 10, 25), f.clean('25 October, 2006')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('2006-4-31') with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('200a-10-25') with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('25/10/06') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) def test_datefield_2(self): f = DateField(required=False) self.assertIsNone(f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertIsNone(f.clean('')) self.assertEqual('None', repr(f.clean(''))) def test_datefield_3(self): f = DateField(input_formats=['%Y %m %d']) self.assertEqual(date(2006, 10, 25), f.clean(date(2006, 10, 25))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30))) self.assertEqual(date(2006, 10, 25), f.clean('2006 10 25')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('2006-10-25') with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('10/25/2006') with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('10/25/06') def test_datefield_4(self): # Test whitespace stripping behavior (#5714) f = DateField() self.assertEqual(date(2006, 10, 25), f.clean(' 10/25/2006 ')) self.assertEqual(date(2006, 10, 25), f.clean(' 10/25/06 ')) self.assertEqual(date(2006, 10, 25), f.clean(' Oct 25 2006 ')) self.assertEqual(date(2006, 10, 25), f.clean(' October 25 2006 ')) self.assertEqual(date(2006, 10, 25), f.clean(' October 25, 2006 ')) self.assertEqual(date(2006, 10, 25), f.clean(' 25 October 2006 ')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean(' ') def test_datefield_5(self): # Test null bytes (#18982) f = DateField() with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('a\x00b') def test_datefield_changed(self): format = '%d/%m/%Y' f = DateField(input_formats=[format]) d = date(2007, 9, 17) self.assertFalse(f.has_changed(d, '17/09/2007')) def test_datefield_strptime(self): """field.strptime() doesn't raise a UnicodeEncodeError (#16123)""" f = DateField() try: f.strptime('31 мая 2011', '%d-%b-%y') except Exception as e: # assertIsInstance or assertRaises cannot be used because UnicodeEncodeError # is a subclass of ValueError self.assertEqual(e.__class__, ValueError)
7545fa3fd4c9154198d9e87fdf47f491d6f3ced28d756a3479e87d4b8860d937
from __future__ import unicode_literals import datetime from django.forms import TimeField, ValidationError from django.test import SimpleTestCase from . import FormFieldAssertionsMixin class TimeFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_timefield_1(self): f = TimeField() self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(14, 25), f.clean('14:25')) self.assertEqual(datetime.time(14, 25, 59), f.clean('14:25:59')) with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): f.clean('hello') with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): f.clean('1:24 p.m.') def test_timefield_2(self): f = TimeField(input_formats=['%I:%M %p']) self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(4, 25), f.clean('4:25 AM')) self.assertEqual(datetime.time(16, 25), f.clean('4:25 PM')) with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): f.clean('14:30:45') def test_timefield_3(self): f = TimeField() # Test whitespace stripping behavior (#5714) self.assertEqual(datetime.time(14, 25), f.clean(' 14:25 ')) self.assertEqual(datetime.time(14, 25, 59), f.clean(' 14:25:59 ')) with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): f.clean(' ') def test_timefield_changed(self): t1 = datetime.time(12, 51, 34, 482548) t2 = datetime.time(12, 51) f = TimeField(input_formats=['%H:%M', '%H:%M %p']) self.assertTrue(f.has_changed(t1, '12:51')) self.assertFalse(f.has_changed(t2, '12:51')) self.assertFalse(f.has_changed(t2, '12:51 PM'))
9e7a6deda4c076f13ef25d7a447fd913956388a613779a49583cb53885a9cd0e
from __future__ import unicode_literals import datetime from django.forms import DurationField from django.test import SimpleTestCase from django.utils.duration import duration_string from . import FormFieldAssertionsMixin class DurationFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_durationfield_clean(self): f = DurationField() self.assertEqual(datetime.timedelta(seconds=30), f.clean('30')) self.assertEqual(datetime.timedelta(minutes=15, seconds=30), f.clean('15:30')) self.assertEqual(datetime.timedelta(hours=1, minutes=15, seconds=30), f.clean('1:15:30')) self.assertEqual( datetime.timedelta(days=1, hours=1, minutes=15, seconds=30, milliseconds=300), f.clean('1 1:15:30.3') ) def test_durationfield_render(self): self.assertWidgetRendersTo( DurationField(initial=datetime.timedelta(hours=1)), '<input id="id_f" type="text" name="f" value="01:00:00" required>', ) def test_durationfield_integer_value(self): f = DurationField() self.assertEqual(datetime.timedelta(0, 10800), f.clean(10800)) def test_durationfield_prepare_value(self): field = DurationField() td = datetime.timedelta(minutes=15, seconds=30) self.assertEqual(field.prepare_value(td), duration_string(td)) self.assertEqual(field.prepare_value('arbitrary'), 'arbitrary') self.assertIsNone(field.prepare_value(None))
644afad9a70dfe460f1b8bba8eef7cb0d957d0efe979e74175c8ee74913d57b7
from __future__ import unicode_literals import datetime from django.forms import SplitDateTimeField, ValidationError from django.forms.widgets import SplitDateTimeWidget from django.test import SimpleTestCase from django.utils import six class SplitDateTimeFieldTest(SimpleTestCase): def test_splitdatetimefield_1(self): f = SplitDateTimeField() self.assertIsInstance(f.widget, SplitDateTimeWidget) self.assertEqual( datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]) ) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): f.clean('hello') with six.assertRaisesRegex(self, ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"): f.clean(['hello', 'there']) with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): f.clean(['2006-01-10', 'there']) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean(['hello', '07:30']) def test_splitdatetimefield_2(self): f = SplitDateTimeField(required=False) self.assertEqual( datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]) ) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean(['2006-01-10', '07:30'])) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean([''])) self.assertIsNone(f.clean(['', ''])) with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): f.clean('hello') with six.assertRaisesRegex(self, ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"): f.clean(['hello', 'there']) with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): f.clean(['2006-01-10', 'there']) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean(['hello', '07:30']) with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): f.clean(['2006-01-10', '']) with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): f.clean(['2006-01-10']) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean(['', '07:30']) def test_splitdatetimefield_changed(self): f = SplitDateTimeField(input_date_formats=['%d/%m/%Y']) self.assertFalse(f.has_changed(['11/01/2012', '09:18:15'], ['11/01/2012', '09:18:15'])) self.assertTrue(f.has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['2008-05-06', '12:40:00'])) self.assertFalse(f.has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:40'])) self.assertTrue(f.has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:41']))
9d8a3c655cfc4823c77ea2baa2bdab618973ed27638951ee262b8f2f2d5565e2
from django import forms class FormFieldAssertionsMixin(object): def assertWidgetRendersTo(self, field, to): class Form(forms.Form): f = field self.assertHTMLEqual(str(Form()['f']), to)
ae66ea7e0b0871ac13ac4aaecffb3ec434d8b7c6c088e4fd0c073e1d7d9e8b72
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pickle from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import FileField, ValidationError from django.test import SimpleTestCase class FileFieldTest(SimpleTestCase): def test_filefield_1(self): f = FileField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('', '') self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None, '') self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) no_file_msg = "'No file was submitted. Check the encoding type on the form.'" with self.assertRaisesMessage(ValidationError, no_file_msg): f.clean(SimpleUploadedFile('', b'')) with self.assertRaisesMessage(ValidationError, no_file_msg): f.clean(SimpleUploadedFile('', b''), '') self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) with self.assertRaisesMessage(ValidationError, no_file_msg): f.clean('some content that is not a file') with self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'"): f.clean(SimpleUploadedFile('name', None)) with self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'"): f.clean(SimpleUploadedFile('name', b'')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) self.assertIsInstance( f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))), SimpleUploadedFile ) self.assertIsInstance( f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'), SimpleUploadedFile ) def test_filefield_2(self): f = FileField(max_length=5) with self.assertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'"): f.clean(SimpleUploadedFile('test_maxlength.txt', b'hello world')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertIsInstance(f.clean(SimpleUploadedFile('name', b'Some File Content')), SimpleUploadedFile) def test_filefield_3(self): f = FileField(allow_empty_file=True) self.assertIsInstance(f.clean(SimpleUploadedFile('name', b'')), SimpleUploadedFile) def test_filefield_changed(self): """ The value of data will more than likely come from request.FILES. The value of initial data will likely be a filename stored in the database. Since its value is of no use to a FileField it is ignored. """ f = FileField() # No file was uploaded and no initial data. self.assertFalse(f.has_changed('', None)) # A file was uploaded and no initial data. self.assertTrue(f.has_changed('', {'filename': 'resume.txt', 'content': 'My resume'})) # A file was not uploaded, but there is initial data self.assertFalse(f.has_changed('resume.txt', None)) # A file was uploaded and there is initial data (file identity is not dealt # with here) self.assertTrue(f.has_changed('resume.txt', {'filename': 'resume.txt', 'content': 'My resume'})) def test_file_picklable(self): self.assertIsInstance(pickle.loads(pickle.dumps(FileField())), FileField)
ab7c6b6f926874721577fe2beda5bf4e655aca6026c40bb84cc223d7418f6e1e
from __future__ import unicode_literals import uuid from django.forms import UUIDField, ValidationError from django.test import SimpleTestCase class UUIDFieldTest(SimpleTestCase): def test_uuidfield_1(self): field = UUIDField() value = field.clean('550e8400e29b41d4a716446655440000') self.assertEqual(value, uuid.UUID('550e8400e29b41d4a716446655440000')) def test_uuidfield_2(self): field = UUIDField(required=False) value = field.clean('') self.assertIsNone(value) def test_uuidfield_3(self): field = UUIDField() with self.assertRaises(ValidationError) as cm: field.clean('550e8400') self.assertEqual(cm.exception.messages[0], 'Enter a valid UUID.') def test_uuidfield_4(self): field = UUIDField() value = field.prepare_value(uuid.UUID('550e8400e29b41d4a716446655440000')) self.assertEqual(value, '550e8400e29b41d4a716446655440000')
0f0b8fbfdbdd884840a83881dd6febe88681e355bf93a308f7116d2eed9b02af
from django.forms import ChoiceField, Field, Form, Select from django.test import SimpleTestCase class BasicFieldsTests(SimpleTestCase): def test_field_sets_widget_is_required(self): self.assertTrue(Field(required=True).widget.is_required) self.assertFalse(Field(required=False).widget.is_required) def test_cooperative_multiple_inheritance(self): class A(object): def __init__(self): self.class_a_var = True super(A, self).__init__() class ComplexField(Field, A): def __init__(self): super(ComplexField, self).__init__() f = ComplexField() self.assertTrue(f.class_a_var) def test_field_deepcopies_widget_instance(self): class CustomChoiceField(ChoiceField): widget = Select(attrs={'class': 'my-custom-class'}) class TestForm(Form): field1 = CustomChoiceField(choices=[]) field2 = CustomChoiceField(choices=[]) f = TestForm() f.fields['field1'].choices = [('1', '1')] f.fields['field2'].choices = [('2', '2')] self.assertEqual(f.fields['field1'].widget.choices, [('1', '1')]) self.assertEqual(f.fields['field2'].widget.choices, [('2', '2')])
2bce658ff0ead565415f4fa9ecc6d1ca83b00869196c9150c4e442ffc06ab6e2
from datetime import datetime from django.forms import ( CharField, Form, MultipleChoiceField, MultiValueField, MultiWidget, SelectMultiple, SplitDateTimeField, SplitDateTimeWidget, TextInput, ValidationError, ) from django.test import SimpleTestCase beatles = (('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')) class ComplexMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = ( TextInput(), SelectMultiple(choices=beatles), SplitDateTimeWidget(), ) super(ComplexMultiWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: data = value.split(',') return [ data[0], list(data[1]), datetime.strptime(data[2], "%Y-%m-%d %H:%M:%S"), ] return [None, None, None] def format_output(self, rendered_widgets): return '\n'.join(rendered_widgets) class ComplexField(MultiValueField): def __init__(self, required=True, widget=None, label=None, initial=None): fields = ( CharField(), MultipleChoiceField(choices=beatles), SplitDateTimeField(), ) super(ComplexField, self).__init__(fields, required, widget, label, initial) def compress(self, data_list): if data_list: return '%s,%s,%s' % (data_list[0], ''.join(data_list[1]), data_list[2]) return None class ComplexFieldForm(Form): field1 = ComplexField(widget=ComplexMultiWidget()) class MultiValueFieldTest(SimpleTestCase): @classmethod def setUpClass(cls): cls.field = ComplexField(widget=ComplexMultiWidget()) super(MultiValueFieldTest, cls).setUpClass() def test_clean(self): self.assertEqual( self.field.clean(['some text', ['J', 'P'], ['2007-04-25', '6:24:00']]), 'some text,JP,2007-04-25 06:24:00', ) def test_bad_choice(self): msg = "'Select a valid choice. X is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): self.field.clean(['some text', ['X'], ['2007-04-25', '6:24:00']]) def test_no_value(self): """ If insufficient data is provided, None is substituted. """ msg = "'This field is required.'" with self.assertRaisesMessage(ValidationError, msg): self.field.clean(['some text', ['JP']]) def test_has_changed_no_initial(self): self.assertTrue(self.field.has_changed(None, ['some text', ['J', 'P'], ['2007-04-25', '6:24:00']])) def test_has_changed_same(self): self.assertFalse(self.field.has_changed( 'some text,JP,2007-04-25 06:24:00', ['some text', ['J', 'P'], ['2007-04-25', '6:24:00']], )) def test_has_changed_first_widget(self): """ Test when the first widget's data has changed. """ self.assertTrue(self.field.has_changed( 'some text,JP,2007-04-25 06:24:00', ['other text', ['J', 'P'], ['2007-04-25', '6:24:00']], )) def test_has_changed_last_widget(self): """ Test when the last widget's data has changed. This ensures that it is not short circuiting while testing the widgets. """ self.assertTrue(self.field.has_changed( 'some text,JP,2007-04-25 06:24:00', ['some text', ['J', 'P'], ['2009-04-25', '11:44:00']], )) def test_form_as_table(self): form = ComplexFieldForm() self.assertHTMLEqual( form.as_table(), """ <tr><th><label for="id_field1_0">Field1:</label></th> <td><input type="text" name="field1_0" id="id_field1_0" required /> <select multiple="multiple" name="field1_1" id="id_field1_1" required> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select> <input type="text" name="field1_2_0" id="id_field1_2_0" required /> <input type="text" name="field1_2_1" id="id_field1_2_1" required /></td></tr> """, ) def test_form_as_table_data(self): form = ComplexFieldForm({ 'field1_0': 'some text', 'field1_1': ['J', 'P'], 'field1_2_0': '2007-04-25', 'field1_2_1': '06:24:00', }) self.assertHTMLEqual( form.as_table(), """ <tr><th><label for="id_field1_0">Field1:</label></th> <td><input type="text" name="field1_0" value="some text" id="id_field1_0" required /> <select multiple="multiple" name="field1_1" id="id_field1_1" required> <option value="J" selected>John</option> <option value="P" selected>Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select> <input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" required /> <input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" required /></td></tr> """, ) def test_form_cleaned_data(self): form = ComplexFieldForm({ 'field1_0': 'some text', 'field1_1': ['J', 'P'], 'field1_2_0': '2007-04-25', 'field1_2_1': '06:24:00', }) form.is_valid() self.assertEqual(form.cleaned_data['field1'], 'some text,JP,2007-04-25 06:24:00')
2873293581eaef85538dbcef042c096d88c7085158006f1c7c0433ac745dac93
from __future__ import unicode_literals import decimal from django.forms import TypedMultipleChoiceField, ValidationError from django.test import SimpleTestCase class TypedMultipleChoiceFieldTest(SimpleTestCase): def test_typedmultiplechoicefield_1(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1], f.clean(['1'])) msg = "'Select a valid choice. 2 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['2']) def test_typedmultiplechoicefield_2(self): # Different coercion, same validation. f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual([1.0], f.clean(['1'])) def test_typedmultiplechoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertEqual([True], f.clean(['-1'])) def test_typedmultiplechoicefield_4(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1, -1], f.clean(['1', '-1'])) msg = "'Select a valid choice. 2 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['1', '2']) def test_typedmultiplechoicefield_5(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) msg = "'Select a valid choice. B is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['B']) # Required fields require values with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) def test_typedmultiplechoicefield_6(self): # Non-required fields aren't required f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual([], f.clean([])) def test_typedmultiplechoicefield_7(self): # If you want cleaning an empty value to return a different type, tell the field f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertIsNone(f.clean([])) def test_typedmultiplechoicefield_has_changed(self): # has_changed should not trigger required validation f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True) self.assertFalse(f.has_changed(None, '')) def test_typedmultiplechoicefield_special_coerce(self): """ A coerce function which results in a value not present in choices should raise an appropriate error (#21397). """ def coerce_func(val): return decimal.Decimal('1.%s' % val) f = TypedMultipleChoiceField( choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True) self.assertEqual([decimal.Decimal('1.2')], f.clean(['2'])) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['3'])
e262f56c38bbbeebe344f717172179a91e295221701ab6218320ae6e735c294b
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import ChoiceField, Form, ValidationError from django.test import SimpleTestCase, ignore_warnings from . import FormFieldAssertionsMixin class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_choicefield_1(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('3') def test_choicefield_2(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('3') def test_choicefield_3(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) self.assertEqual('J', f.clean('J')) msg = "'Select a valid choice. John is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('John') def test_choicefield_4(self): f = ChoiceField( choices=[ ('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other'), ] ) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) self.assertEqual('3', f.clean(3)) self.assertEqual('3', f.clean('3')) self.assertEqual('5', f.clean(5)) self.assertEqual('5', f.clean('5')) msg = "'Select a valid choice. 6 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('6') def test_choicefield_callable(self): def choices(): return [('J', 'John'), ('P', 'Paul')] f = ChoiceField(choices=choices) self.assertEqual('J', f.clean('J')) def test_choicefield_callable_may_evaluate_to_different_values(self): choices = [] def choices_as_callable(): return choices class ChoiceFieldForm(Form): choicefield = ChoiceField(choices=choices_as_callable) choices = [('J', 'John')] form = ChoiceFieldForm() self.assertEqual([('J', 'John')], list(form.fields['choicefield'].choices)) choices = [('P', 'Paul')] form = ChoiceFieldForm() self.assertEqual([('P', 'Paul')], list(form.fields['choicefield'].choices)) def test_choicefield_disabled(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')], disabled=True) self.assertWidgetRendersTo( f, '<select id="id_f" name="f" disabled required><option value="J">John</option>' '<option value="P">Paul</option></select>' ) @ignore_warnings(category=UnicodeWarning) def test_utf8_bytesrings(self): # Choice validation with UTF-8 bytestrings as input (these are the # Russian abbreviations "мес." and "шт.". f = ChoiceField( choices=( (b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'), (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.'), ), ) self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.') self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.')
408967560d594e3fe7d514471c8892645297aacacd007ff642b516ad83471da8
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import URLField, ValidationError from django.test import SimpleTestCase from . import FormFieldAssertionsMixin class URLFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_urlfield_1(self): f = URLField() self.assertWidgetRendersTo(f, '<input type="url" name="f" id="id_f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual('http://localhost', f.clean('http://localhost')) self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://example.com.', f.clean('http://example.com.')) self.assertEqual('http://www.example.com', f.clean('http://www.example.com')) self.assertEqual('http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test')) self.assertEqual('http://valid-with-hyphens.com', f.clean('valid-with-hyphens.com')) self.assertEqual('http://subdomain.domain.com', f.clean('subdomain.domain.com')) self.assertEqual('http://200.8.9.10', f.clean('http://200.8.9.10')) self.assertEqual('http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('com.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://invalid-.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://-invalid.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://inv-.alid-.com') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://inv-.-alid.com') self.assertEqual('http://valid-----hyphens.com', f.clean('http://valid-----hyphens.com')) self.assertEqual( 'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah') ) self.assertEqual( 'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804') ) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('[a') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://[a') def test_url_regex_ticket11198(self): f = URLField() # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://%s' % ("X" * 200,)) # a second test, to make sure the problem is really addressed, even on # domains that don't fail the domain label length check in the regex with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://%s' % ("X" * 60,)) def test_urlfield_2(self): f = URLField(required=False) self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://www.example.com', f.clean('http://www.example.com')) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://example.') with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean('http://.com') def test_urlfield_5(self): f = URLField(min_length=15, max_length=20) self.assertWidgetRendersTo(f, '<input id="id_f" type="url" name="f" maxlength="20" minlength="15" required />') with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 12).'"): f.clean('http://f.com') self.assertEqual('http://example.com', f.clean('http://example.com')) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 37).'"): f.clean('http://abcdefghijklmnopqrstuvwxyz.com') def test_urlfield_6(self): f = URLField(required=False) self.assertEqual('http://example.com', f.clean('example.com')) self.assertEqual('', f.clean('')) self.assertEqual('https://example.com', f.clean('https://example.com')) def test_urlfield_7(self): f = URLField() self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://example.com/test', f.clean('http://example.com/test')) self.assertEqual( 'http://example.com?some_param=some_value', f.clean('http://example.com?some_param=some_value') ) def test_urlfield_9(self): f = URLField() urls = ( 'http://עברית.idn.icann.org/', 'http://sãopaulo.com/', 'http://sãopaulo.com.br/', 'http://пример.испытание/', 'http://مثال.إختبار/', 'http://例子.测试/', 'http://例子.測試/', 'http://उदाहरण.परीक्षा/', 'http://例え.テスト/', 'http://مثال.آزمایشی/', 'http://실례.테스트/', 'http://العربية.idn.icann.org/', ) for url in urls: # Valid IDN self.assertEqual(url, f.clean(url)) def test_urlfield_10(self): """URLField correctly validates IPv6 (#18779).""" f = URLField() urls = ( 'http://[12:34::3a53]/', 'http://[a34:9238::]:8080/', ) for url in urls: self.assertEqual(url, f.clean(url)) def test_urlfield_not_string(self): f = URLField(required=False) with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): f.clean(23) def test_urlfield_normalization(self): f = URLField() self.assertEqual(f.clean('http://example.com/ '), 'http://example.com/') def test_urlfield_strip_on_none_value(self): f = URLField(required=False, empty_value=None) self.assertIsNone(f.clean(None)) def test_urlfield_unable_to_set_strip_kwarg(self): msg = "__init__() got multiple values for keyword argument 'strip'" with self.assertRaisesMessage(TypeError, msg): URLField(strip=False)
23fd66a6384882c030e8baef7df6437e5f58ff47a1d52042dd0a963e4b208c3a
from __future__ import unicode_literals from django.forms import MultipleChoiceField, ValidationError from django.test import SimpleTestCase class MultipleChoiceFieldTest(SimpleTestCase): def test_multiplechoicefield_1(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '2'], f.clean(['1', '2'])) self.assertEqual(['1', '2'], f.clean([1, '2'])) self.assertEqual(['1', '2'], f.clean((1, '2'))) with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): f.clean('hello') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(()) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['3']) def test_multiplechoicefield_2(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual([], f.clean('')) self.assertEqual([], f.clean(None)) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '2'], f.clean(['1', '2'])) self.assertEqual(['1', '2'], f.clean([1, '2'])) self.assertEqual(['1', '2'], f.clean((1, '2'))) with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): f.clean('hello') self.assertEqual([], f.clean([])) self.assertEqual([], f.clean(())) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['3']) def test_multiplechoicefield_3(self): f = MultipleChoiceField( choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')] ) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '5'], f.clean([1, 5])) self.assertEqual(['1', '5'], f.clean([1, '5'])) self.assertEqual(['1', '5'], f.clean(['1', 5])) self.assertEqual(['1', '5'], f.clean(['1', '5'])) msg = "'Select a valid choice. 6 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['6']) msg = "'Select a valid choice. 6 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(['1', '6']) def test_multiplechoicefield_changed(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')]) self.assertFalse(f.has_changed(None, None)) self.assertFalse(f.has_changed([], None)) self.assertTrue(f.has_changed(None, ['1'])) self.assertFalse(f.has_changed([1, 2], ['1', '2'])) self.assertFalse(f.has_changed([2, 1], ['1', '2'])) self.assertTrue(f.has_changed([1, 2], ['1'])) self.assertTrue(f.has_changed([1, 2], ['1', '3']))
4cd76fa2ced1081a68387fd219ae9f4bb16fda642ce630263a8c7917ed4f6d26
from __future__ import unicode_literals from django.forms import CharField, ComboField, EmailField, ValidationError from django.test import SimpleTestCase class ComboFieldTest(SimpleTestCase): def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) self.assertEqual('[email protected]', f.clean('[email protected]')) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'"): f.clean('[email protected]') with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): f.clean('not an email') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) def test_combofield_2(self): f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False) self.assertEqual('[email protected]', f.clean('[email protected]')) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'"): f.clean('[email protected]') with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): f.clean('not an email') self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None))
5950fb9e459ee529f41ff3e94d865f19e769632a6766057cddbfe89d10231ff1
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import EmailField, ValidationError from django.test import SimpleTestCase from . import FormFieldAssertionsMixin class EmailFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_emailfield_1(self): f = EmailField() self.assertWidgetRendersTo(f, '<input type="email" name="f" id="id_f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual('[email protected]', f.clean('[email protected]')) with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): f.clean('foo') self.assertEqual( '[email protected]\xe4\xf6\xfc\xdfabc.part.com', f.clean('[email protected]äöüßabc.part.com') ) def test_email_regexp_for_performance(self): f = EmailField() # Check for runaway regex security problem. This will take a long time # if the security fix isn't in place. addr = '[email protected]' self.assertEqual(addr, f.clean(addr)) def test_emailfield_not_required(self): f = EmailField(required=False) self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) self.assertEqual('[email protected]', f.clean('[email protected]')) self.assertEqual('[email protected]', f.clean(' [email protected] \t \t ')) with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): f.clean('foo') def test_emailfield_min_max_length(self): f = EmailField(min_length=10, max_length=15) self.assertWidgetRendersTo( f, '<input id="id_f" type="email" name="f" maxlength="15" minlength="10" required />', ) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'"): f.clean('[email protected]') self.assertEqual('[email protected]', f.clean('[email protected]')) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'"): f.clean('[email protected]') def test_emailfield_strip_on_none_value(self): f = EmailField(required=False, empty_value=None) self.assertIsNone(f.clean(None)) def test_emailfield_unable_to_set_strip_kwarg(self): msg = "__init__() got multiple values for keyword argument 'strip'" with self.assertRaisesMessage(TypeError, msg): EmailField(strip=False)
46540a076f39e0cf2cf36053e254498e930517ab9062f5e356059e5eeb2615cb
from __future__ import unicode_literals import datetime from django.forms import DateTimeField, ValidationError from django.test import SimpleTestCase class DateTimeFieldTest(SimpleTestCase): def test_datetimefield_1(self): f = DateTimeField() self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual( datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)) ) self.assertEqual( datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)) ) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.000200')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.0002')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('2006-10-25 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006-10-25 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006-10-25 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('2006-10-25')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('10/25/2006 14:30:45.000200')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('10/25/2006 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/2006 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/2006 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/2006')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('10/25/06 14:30:45.000200')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('10/25/06 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/06')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'"): f.clean('hello') with self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'"): f.clean('2006-10-25 4:30 p.m.') def test_datetimefield_2(self): f = DateTimeField(input_formats=['%Y %m %d %I:%M %p']) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual( datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)) ) self.assertEqual( datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)) ) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'"): f.clean('2006-10-25 14:30:45') def test_datetimefield_3(self): f = DateTimeField(required=False) self.assertIsNone(f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertIsNone(f.clean('')) self.assertEqual('None', repr(f.clean(''))) def test_datetimefield_4(self): f = DateTimeField() # Test whitespace stripping behavior (#5714) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 2006-10-25 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 2006-10-25 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/2006 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(' 10/25/2006 14:30 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/2006 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/06 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/06 ')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'"): f.clean(' ') def test_datetimefield_5(self): f = DateTimeField(input_formats=['%Y.%m.%d %H:%M:%S.%f']) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006.10.25 14:30:45.0002')) def test_datetimefield_changed(self): format = '%Y %m %d %I:%M %p' f = DateTimeField(input_formats=[format]) d = datetime.datetime(2006, 9, 17, 14, 30, 0) self.assertFalse(f.has_changed(d, '2006 09 17 2:30 PM'))
47d7aee9cb5175060ccded38068a77d982ede8e3aa5a93a59aaf15d11cd01338
from __future__ import unicode_literals from django.forms import Form, HiddenInput, NullBooleanField, RadioSelect from django.test import SimpleTestCase from . import FormFieldAssertionsMixin class NullBooleanFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_nullbooleanfield_clean(self): f = NullBooleanField() self.assertIsNone(f.clean('')) self.assertTrue(f.clean(True)) self.assertFalse(f.clean(False)) self.assertIsNone(f.clean(None)) self.assertFalse(f.clean('0')) self.assertTrue(f.clean('1')) self.assertIsNone(f.clean('2')) self.assertIsNone(f.clean('3')) self.assertIsNone(f.clean('hello')) self.assertTrue(f.clean('true')) self.assertFalse(f.clean('false')) def test_nullbooleanfield_2(self): # The internal value is preserved if using HiddenInput (#7753). class HiddenNullBooleanForm(Form): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False) f = HiddenNullBooleanForm() self.assertHTMLEqual( '<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1" />' '<input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2" />', str(f) ) def test_nullbooleanfield_3(self): class HiddenNullBooleanForm(Form): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False) f = HiddenNullBooleanForm({'hidden_nullbool1': 'True', 'hidden_nullbool2': 'False'}) self.assertIsNone(f.full_clean()) self.assertTrue(f.cleaned_data['hidden_nullbool1']) self.assertFalse(f.cleaned_data['hidden_nullbool2']) def test_nullbooleanfield_4(self): # Make sure we're compatible with MySQL, which uses 0 and 1 for its # boolean values (#9609). NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown')) class MySQLNullBooleanForm(Form): nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool1 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool2 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) f = MySQLNullBooleanForm({'nullbool0': '1', 'nullbool1': '0', 'nullbool2': ''}) self.assertIsNone(f.full_clean()) self.assertTrue(f.cleaned_data['nullbool0']) self.assertFalse(f.cleaned_data['nullbool1']) self.assertIsNone(f.cleaned_data['nullbool2']) def test_nullbooleanfield_changed(self): f = NullBooleanField() self.assertTrue(f.has_changed(False, None)) self.assertTrue(f.has_changed(None, False)) self.assertFalse(f.has_changed(None, None)) self.assertFalse(f.has_changed(False, False)) self.assertTrue(f.has_changed(True, False)) self.assertTrue(f.has_changed(True, None)) self.assertTrue(f.has_changed(True, False)) # HiddenInput widget sends string values for boolean but doesn't clean them in value_from_datadict self.assertFalse(f.has_changed(False, 'False')) self.assertFalse(f.has_changed(True, 'True')) self.assertFalse(f.has_changed(None, '')) self.assertTrue(f.has_changed(False, 'True')) self.assertTrue(f.has_changed(True, 'False')) self.assertTrue(f.has_changed(None, 'False'))
1ea8e108275a8f5a58f3236fb8ee3c91de3eec2659df6df806a1dc5748465cda
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import SlugField from django.test import SimpleTestCase class SlugFieldTest(SimpleTestCase): def test_slugfield_normalization(self): f = SlugField() self.assertEqual(f.clean(' aa-bb-cc '), 'aa-bb-cc') def test_slugfield_unicode_normalization(self): f = SlugField(allow_unicode=True) self.assertEqual(f.clean('a'), 'a') self.assertEqual(f.clean('1'), '1') self.assertEqual(f.clean('a1'), 'a1') self.assertEqual(f.clean('你好'), '你好') self.assertEqual(f.clean(' 你-好 '), '你-好') self.assertEqual(f.clean('ıçğüş'), 'ıçğüş') self.assertEqual(f.clean('foo-ıç-bar'), 'foo-ıç-bar')
c0b8b5f4f7fdcc9bd37ce94ee58cf7b5b93ffca7826e494fa5c9a2d5d1e8770c
# -*- coding: utf-8 -*- from __future__ import unicode_literals import decimal from django.forms import DecimalField, NumberInput, ValidationError, Widget from django.test import SimpleTestCase from django.utils import formats, translation from . import FormFieldAssertionsMixin class DecimalFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_decimalfield_1(self): f = DecimalField(max_digits=4, decimal_places=2) self.assertWidgetRendersTo(f, '<input id="id_f" step="0.01" type="number" name="f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(f.clean('1'), decimal.Decimal("1")) self.assertIsInstance(f.clean('1'), decimal.Decimal) self.assertEqual(f.clean('23'), decimal.Decimal("23")) self.assertEqual(f.clean('3.14'), decimal.Decimal("3.14")) self.assertEqual(f.clean(3.14), decimal.Decimal("3.14")) self.assertEqual(f.clean(decimal.Decimal('3.14')), decimal.Decimal("3.14")) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('NaN') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('Inf') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('-Inf') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('a') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('łąść') self.assertEqual(f.clean('1.0 '), decimal.Decimal("1.0")) self.assertEqual(f.clean(' 1.0'), decimal.Decimal("1.0")) self.assertEqual(f.clean(' 1.0 '), decimal.Decimal("1.0")) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('1.0a') with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): f.clean('123.45') with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): f.clean('1.234') msg = "'Ensure that there are no more than 2 digits before the decimal point.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('123.4') self.assertEqual(f.clean('-12.34'), decimal.Decimal("-12.34")) with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): f.clean('-123.45') self.assertEqual(f.clean('-.12'), decimal.Decimal("-0.12")) self.assertEqual(f.clean('-00.12'), decimal.Decimal("-0.12")) self.assertEqual(f.clean('-000.12'), decimal.Decimal("-0.12")) with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): f.clean('-000.123') with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): f.clean('-000.12345') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('--0.12') self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_decimalfield_2(self): f = DecimalField(max_digits=4, decimal_places=2, required=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertEqual(f.clean('1'), decimal.Decimal("1")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_decimalfield_3(self): f = DecimalField( max_digits=4, decimal_places=2, max_value=decimal.Decimal('1.5'), min_value=decimal.Decimal('0.5') ) self.assertWidgetRendersTo( f, '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" required />', ) with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"): f.clean('1.6') with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"): f.clean('0.4') self.assertEqual(f.clean('1.5'), decimal.Decimal("1.5")) self.assertEqual(f.clean('0.5'), decimal.Decimal("0.5")) self.assertEqual(f.clean('.5'), decimal.Decimal("0.5")) self.assertEqual(f.clean('00.50'), decimal.Decimal("0.50")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, decimal.Decimal('1.5')) self.assertEqual(f.min_value, decimal.Decimal('0.5')) def test_decimalfield_4(self): f = DecimalField(decimal_places=2) with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): f.clean('0.00000001') def test_decimalfield_5(self): f = DecimalField(max_digits=3) # Leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('0000000.10'), decimal.Decimal("0.1")) # But a leading 0 before the . doesn't count towards max_digits self.assertEqual(f.clean('0000000.100'), decimal.Decimal("0.100")) # Only leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('000000.02'), decimal.Decimal('0.02')) with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'"): f.clean('000000.0002') self.assertEqual(f.clean('.002'), decimal.Decimal("0.002")) def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('.01'), decimal.Decimal(".01")) msg = "'Ensure that there are no more than 0 digits before the decimal point.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('1.1') def test_decimalfield_scientific(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('1E+2'), decimal.Decimal('1E+2')) self.assertEqual(f.clean('1e+2'), decimal.Decimal('1E+2')) with self.assertRaisesMessage(ValidationError, "Ensure that there are no more"): f.clean('0.546e+2') def test_decimalfield_widget_attrs(self): f = DecimalField(max_digits=6, decimal_places=2) self.assertEqual(f.widget_attrs(Widget()), {}) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '0.01'}) f = DecimalField(max_digits=10, decimal_places=0) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '1'}) f = DecimalField(max_digits=19, decimal_places=19) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '1e-19'}) f = DecimalField(max_digits=20) self.assertEqual(f.widget_attrs(NumberInput()), {'step': 'any'}) f = DecimalField(max_digits=6, widget=NumberInput(attrs={'step': '0.01'})) self.assertWidgetRendersTo(f, '<input step="0.01" name="f" type="number" id="id_f" required />') def test_decimalfield_localized(self): """ A localized DecimalField's widget renders to a text input without number input specific attributes. """ f = DecimalField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required />') def test_decimalfield_changed(self): f = DecimalField(max_digits=2, decimal_places=2) d = decimal.Decimal("0.1") self.assertFalse(f.has_changed(d, '0.10')) self.assertTrue(f.has_changed(d, '0.101')) with translation.override('fr'), self.settings(USE_L10N=True): f = DecimalField(max_digits=2, decimal_places=2, localize=True) localized_d = formats.localize_input(d) # -> '0,1' in French self.assertFalse(f.has_changed(d, localized_d))
76e5831586dcb6b82302e3973969cfab5a2df34887b28a68a80f79ff10950d0b
from __future__ import unicode_literals import os import unittest from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ImageField from django.test import SimpleTestCase from django.utils._os import upath try: from PIL import Image except ImportError: Image = None def get_img_path(path): return os.path.join(os.path.abspath(os.path.join(upath(__file__), '..', '..')), 'tests', path) @unittest.skipUnless(Image, "Pillow is required to test ImageField") class ImageFieldTest(SimpleTestCase): def test_imagefield_annotate_with_image_after_clean(self): f = ImageField() img_path = get_img_path('filepath_test_files/1x1.png') with open(img_path, 'rb') as img_file: img_data = img_file.read() img_file = SimpleUploadedFile('1x1.png', img_data) img_file.content_type = 'text/plain' uploaded_file = f.clean(img_file) self.assertEqual('PNG', uploaded_file.image.format) self.assertEqual('image/png', uploaded_file.content_type) def test_imagefield_annotate_with_bitmap_image_after_clean(self): """ This also tests the situation when Pillow doesn't detect the MIME type of the image (#24948). """ from PIL.BmpImagePlugin import BmpImageFile try: Image.register_mime(BmpImageFile.format, None) f = ImageField() img_path = get_img_path('filepath_test_files/1x1.bmp') with open(img_path, 'rb') as img_file: img_data = img_file.read() img_file = SimpleUploadedFile('1x1.bmp', img_data) img_file.content_type = 'text/plain' uploaded_file = f.clean(img_file) self.assertEqual('BMP', uploaded_file.image.format) self.assertIsNone(uploaded_file.content_type) finally: Image.register_mime(BmpImageFile.format, 'image/bmp')
5880b44cc864462bc3201a5b3b67983c6b8fafe92cac3a8db397d281e1c42aaa
from __future__ import unicode_literals import pickle from django.forms import BooleanField, ValidationError from django.test import SimpleTestCase class BooleanFieldTest(SimpleTestCase): def test_booleanfield_clean_1(self): f = BooleanField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertTrue(f.clean(True)) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(False) self.assertTrue(f.clean(1)) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(0) self.assertTrue(f.clean('Django rocks')) self.assertTrue(f.clean('True')) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('False') def test_booleanfield_clean_2(self): f = BooleanField(required=False) self.assertIs(f.clean(''), False) self.assertIs(f.clean(None), False) self.assertIs(f.clean(True), True) self.assertIs(f.clean(False), False) self.assertIs(f.clean(1), True) self.assertIs(f.clean(0), False) self.assertIs(f.clean('1'), True) self.assertIs(f.clean('0'), False) self.assertIs(f.clean('Django rocks'), True) self.assertIs(f.clean('False'), False) self.assertIs(f.clean('false'), False) self.assertIs(f.clean('FaLsE'), False) def test_boolean_picklable(self): self.assertIsInstance(pickle.loads(pickle.dumps(BooleanField())), BooleanField) def test_booleanfield_changed(self): f = BooleanField() self.assertFalse(f.has_changed(None, None)) self.assertFalse(f.has_changed(None, '')) self.assertFalse(f.has_changed('', None)) self.assertFalse(f.has_changed('', '')) self.assertTrue(f.has_changed(False, 'on')) self.assertFalse(f.has_changed(True, 'on')) self.assertTrue(f.has_changed(True, '')) # Initial value may have mutated to a string due to show_hidden_initial (#19537) self.assertTrue(f.has_changed('False', 'on')) # HiddenInput widget sends string values for boolean but doesn't clean them in value_from_datadict self.assertFalse(f.has_changed(False, 'False')) self.assertFalse(f.has_changed(True, 'True')) self.assertTrue(f.has_changed(False, 'True')) self.assertTrue(f.has_changed(True, 'False'))
02af11a532e476a1684c392dee4dfe21c9473b79c5ef1b9d4e838f25514af8bf
from __future__ import unicode_literals import decimal from django.forms import TypedChoiceField, ValidationError from django.test import SimpleTestCase from django.utils import six class TypedChoiceFieldTest(SimpleTestCase): def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) msg = "'Select a valid choice. 2 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('2') def test_typedchoicefield_2(self): # Different coercion, same validation. f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual(1.0, f.clean('1')) def test_typedchoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertTrue(f.clean('-1')) def test_typedchoicefield_4(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) msg = "'Select a valid choice. B is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('B') # Required fields require values with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') def test_typedchoicefield_5(self): # Non-required fields aren't required f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual('', f.clean('')) # If you want cleaning an empty value to return a different type, tell the field def test_typedchoicefield_6(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertIsNone(f.clean('')) def test_typedchoicefield_has_changed(self): # has_changed should not trigger required validation f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True) self.assertFalse(f.has_changed(None, '')) self.assertFalse(f.has_changed(1, '1')) self.assertFalse(f.has_changed('1', '1')) f = TypedChoiceField( choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=six.text_type, required=False, initial=None, empty_value=None, ) self.assertFalse(f.has_changed(None, '')) self.assertTrue(f.has_changed('', 'a')) self.assertFalse(f.has_changed('a', 'a')) def test_typedchoicefield_special_coerce(self): """ A coerce function which results in a value not present in choices should raise an appropriate error (#21397). """ def coerce_func(val): return decimal.Decimal('1.%s' % val) f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True) self.assertEqual(decimal.Decimal('1.2'), f.clean('2')) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('3')
1550244bb15daf32e909c6bfe7a1c63ff4dab6c6b933eef1fab3c9f3eb67c901
from __future__ import unicode_literals from django.forms import ( CharField, HiddenInput, PasswordInput, Textarea, TextInput, ValidationError, ) from django.test import SimpleTestCase from . import FormFieldAssertionsMixin class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_charfield_1(self): f = CharField() self.assertEqual('1', f.clean(1)) self.assertEqual('hello', f.clean('hello')) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertIsNone(f.max_length) self.assertIsNone(f.min_length) def test_charfield_2(self): f = CharField(required=False) self.assertEqual('1', f.clean(1)) self.assertEqual('hello', f.clean('hello')) self.assertEqual('', f.clean(None)) self.assertEqual('', f.clean('')) self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertIsNone(f.max_length) self.assertIsNone(f.min_length) def test_charfield_3(self): f = CharField(max_length=10, required=False) self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) msg = "'Ensure this value has at most 10 characters (it has 11).'" with self.assertRaisesMessage(ValidationError, msg): f.clean('1234567890a') self.assertEqual(f.max_length, 10) self.assertIsNone(f.min_length) def test_charfield_4(self): f = CharField(min_length=10, required=False) self.assertEqual('', f.clean('')) msg = "'Ensure this value has at least 10 characters (it has 5).'" with self.assertRaisesMessage(ValidationError, msg): f.clean('12345') self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertIsNone(f.max_length) self.assertEqual(f.min_length, 10) def test_charfield_5(self): f = CharField(min_length=10, required=True) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') msg = "'Ensure this value has at least 10 characters (it has 5).'" with self.assertRaisesMessage(ValidationError, msg): f.clean('12345') self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertIsNone(f.max_length) self.assertEqual(f.min_length, 10) def test_charfield_length_not_int(self): """ Setting min_length or max_length to something that is not a number raises an exception. """ with self.assertRaises(ValueError): CharField(min_length='a') with self.assertRaises(ValueError): CharField(max_length='a') with self.assertRaises(ValueError): CharField('a') def test_charfield_widget_attrs(self): """ CharField.widget_attrs() always returns a dictionary and includes minlength/maxlength if min_length/max_length are defined on the field and the widget is not hidden. """ # Return an empty dictionary if max_length and min_length are both None. f = CharField() self.assertEqual(f.widget_attrs(TextInput()), {}) self.assertEqual(f.widget_attrs(Textarea()), {}) # Return a maxlength attribute equal to max_length. f = CharField(max_length=10) self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'}) # Return a minlength attribute equal to min_length. f = CharField(min_length=5) self.assertEqual(f.widget_attrs(TextInput()), {'minlength': '5'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'minlength': '5'}) self.assertEqual(f.widget_attrs(Textarea()), {'minlength': '5'}) # Return both maxlength and minlength when both max_length and # min_length are set. f = CharField(max_length=10, min_length=5) self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10', 'minlength': '5'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10', 'minlength': '5'}) self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10', 'minlength': '5'}) self.assertEqual(f.widget_attrs(HiddenInput()), {}) def test_charfield_strip(self): """ Values have whitespace stripped but not if strip=False. """ f = CharField() self.assertEqual(f.clean(' 1'), '1') self.assertEqual(f.clean('1 '), '1') f = CharField(strip=False) self.assertEqual(f.clean(' 1'), ' 1') self.assertEqual(f.clean('1 '), '1 ') def test_charfield_disabled(self): f = CharField(disabled=True) self.assertWidgetRendersTo(f, '<input type="text" name="f" id="id_f" disabled required />')
91d05fc6f45c40e0568e90707a45b6603633f6752bf65ab3d2c0994c587deb83
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re from django.forms import RegexField, ValidationError from django.test import SimpleTestCase from django.utils import six class RegexFieldTest(SimpleTestCase): def test_regexfield_1(self): f = RegexField('^[0-9][A-F][0-9]$') self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('3G3') with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean(' 2A2') with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('2A2 ') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') def test_regexfield_2(self): f = RegexField('^[0-9][A-F][0-9]$', required=False) self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('3G3') self.assertEqual('', f.clean('')) def test_regexfield_3(self): f = RegexField(re.compile('^[0-9][A-F][0-9]$')) self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('3G3') with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean(' 2A2') with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('2A2 ') def test_regexfield_4(self): f = RegexField('^[0-9]+$', min_length=5, max_length=10) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'"): f.clean('123') six.assertRaisesRegex( self, ValidationError, r"'Ensure this value has at least 5 characters \(it has 3\)\.'," r" u?'Enter a valid value\.'", f.clean, 'abc' ) self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'"): f.clean('12345678901') with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('12345a') def test_regexfield_unicode_characters(self): f = RegexField(r'^\w+$') self.assertEqual('éèøçÎÎ你好', f.clean('éèøçÎÎ你好')) def test_change_regex_after_init(self): f = RegexField('^[a-z]+$') f.regex = '^[0-9]+$' self.assertEqual('1234', f.clean('1234')) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('abcd')
c8516718f227ebdbe25d1dae0d0e865c17cb701baa8cc9b3272f092edc05e131
from __future__ import unicode_literals from django.forms import GenericIPAddressField, ValidationError from django.test import SimpleTestCase class GenericIPAddressFieldTest(SimpleTestCase): def test_generic_ipaddress_invalid_arguments(self): with self.assertRaises(ValueError): GenericIPAddressField(protocol='hamster') with self.assertRaises(ValueError): GenericIPAddressField(protocol='ipv4', unpack_ipv4=True) def test_generic_ipaddress_as_generic(self): # The edge cases of the IPv6 validation code are not deeply tested # here, they are covered in the tests for django.utils.ipv6 f = GenericIPAddressField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(f.clean(' 127.0.0.1 '), '127.0.0.1') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): f.clean('127.0.0.') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): f.clean('1.2.3.4.5') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): f.clean('256.125.1.5') self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a') self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('12345:2:3:4') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1::2:3::4') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('foo::223:6cff:fe8a:2e8a') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1::2:3:4:5:6:7:8') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1:2') def test_generic_ipaddress_as_ipv4_only(self): f = GenericIPAddressField(protocol="IPv4") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(f.clean(' 127.0.0.1 '), '127.0.0.1') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): f.clean('127.0.0.') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): f.clean('1.2.3.4.5') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): f.clean('256.125.1.5') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): f.clean('fe80::223:6cff:fe8a:2e8a') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): f.clean('2a02::223:6cff:fe8a:2e8a') def test_generic_ipaddress_as_ipv6_only(self): f = GenericIPAddressField(protocol="IPv6") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): f.clean('127.0.0.1') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): f.clean('127.0.0.') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): f.clean('1.2.3.4.5') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): f.clean('256.125.1.5') self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a') self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('12345:2:3:4') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1::2:3::4') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('foo::223:6cff:fe8a:2e8a') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1::2:3:4:5:6:7:8') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1:2') def test_generic_ipaddress_as_generic_not_required(self): f = GenericIPAddressField(required=False) self.assertEqual(f.clean(''), '') self.assertEqual(f.clean(None), '') self.assertEqual(f.clean('127.0.0.1'), '127.0.0.1') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): f.clean('foo') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): f.clean('127.0.0.') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): f.clean('1.2.3.4.5') with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): f.clean('256.125.1.5') self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a') self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('12345:2:3:4') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1::2:3::4') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('foo::223:6cff:fe8a:2e8a') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1::2:3:4:5:6:7:8') with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): f.clean('1:2') def test_generic_ipaddress_normalization(self): # Test the normalizing code f = GenericIPAddressField() self.assertEqual(f.clean(' ::ffff:0a0a:0a0a '), '::ffff:10.10.10.10') self.assertEqual(f.clean(' ::ffff:10.10.10.10 '), '::ffff:10.10.10.10') self.assertEqual(f.clean(' 2001:000:a:0000:0:fe:fe:beef '), '2001:0:a::fe:fe:beef') self.assertEqual(f.clean(' 2001::a:0000:0:fe:fe:beef '), '2001:0:a::fe:fe:beef') f = GenericIPAddressField(unpack_ipv4=True) self.assertEqual(f.clean(' ::ffff:0a0a:0a0a'), '10.10.10.10')
eb891f70a878e7fd6f0c3bc41807482ffbdc183272294a59184e119494a0aea7
from __future__ import unicode_literals from django.forms import FloatField, NumberInput, ValidationError from django.test import SimpleTestCase from django.utils import formats, translation from . import FormFieldAssertionsMixin class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_floatfield_1(self): f = FloatField() self.assertWidgetRendersTo(f, '<input step="any" type="number" name="f" id="id_f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(1.0, f.clean('1')) self.assertIsInstance(f.clean('1'), float) self.assertEqual(23.0, f.clean('23')) self.assertEqual(3.1400000000000001, f.clean('3.14')) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('a') self.assertEqual(1.0, f.clean('1.0 ')) self.assertEqual(1.0, f.clean(' 1.0')) self.assertEqual(1.0, f.clean(' 1.0 ')) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('1.0a') self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('Infinity') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('NaN') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('-Inf') def test_floatfield_2(self): f = FloatField(required=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertEqual(1.0, f.clean('1')) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo( f, '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" required />', ) with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"): f.clean('1.6') with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"): f.clean('0.4') self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(f.max_value, 1.5) self.assertEqual(f.min_value, 0.5) def test_floatfield_widget_attrs(self): f = FloatField(widget=NumberInput(attrs={'step': 0.01, 'max': 1.0, 'min': 0.0})) self.assertWidgetRendersTo( f, '<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" required />', ) def test_floatfield_localized(self): """ A localized FloatField's widget renders to a text input without any number input specific attributes. """ f = FloatField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required />') def test_floatfield_changed(self): f = FloatField() n = 4.35 self.assertFalse(f.has_changed(n, '4.3500')) with translation.override('fr'), self.settings(USE_L10N=True): f = FloatField(localize=True) localized_n = formats.localize_input(n) # -> '4,35' in French self.assertFalse(f.has_changed(n, localized_n))
40a25ff7feb0a050b20dad205908d7d074618e1e4346e86d859b1962c07a9d0b
from __future__ import unicode_literals import os.path from django.forms import FilePathField, ValidationError, forms from django.test import SimpleTestCase from django.utils import six from django.utils._os import upath def fix_os_paths(x): if isinstance(x, six.string_types): return x.replace('\\', '/') elif isinstance(x, tuple): return tuple(fix_os_paths(list(x))) elif isinstance(x, list): return [fix_os_paths(y) for y in x] else: return x class FilePathFieldTest(SimpleTestCase): def test_filepathfield_1(self): path = os.path.abspath(upath(forms.__file__)) path = os.path.dirname(path) + '/' self.assertTrue(fix_os_paths(path).endswith('/django/forms/')) def test_filepathfield_2(self): path = upath(forms.__file__) path = os.path.dirname(os.path.abspath(path)) + '/' f = FilePathField(path=path) f.choices = [p for p in f.choices if p[0].endswith('.py')] f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/boundfield.py', 'boundfield.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/utils.py', 'utils.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) msg = "'Select a valid choice. fields.py is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('fields.py') self.assertTrue(fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py')) def test_filepathfield_3(self): path = upath(forms.__file__) path = os.path.dirname(os.path.abspath(path)) + '/' f = FilePathField(path=path, match=r'^.*?\.py$') f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/boundfield.py', 'boundfield.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/utils.py', 'utils.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) def test_filepathfield_4(self): path = os.path.abspath(upath(forms.__file__)) path = os.path.dirname(path) + '/' f = FilePathField(path=path, recursive=True, match=r'^.*?\.py$') f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/boundfield.py', 'boundfield.py'), ('/django/forms/extras/__init__.py', 'extras/__init__.py'), ('/django/forms/extras/widgets.py', 'extras/widgets.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/utils.py', 'utils.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) def test_filepathfield_folders(self): path = os.path.abspath(os.path.join(upath(__file__), '..', '..')) + '/tests/filepath_test_files/' f = FilePathField(path=path, allow_folders=True, allow_files=False) f.choices.sort() expected = [ ('/forms_tests/tests/filepath_test_files/directory', 'directory'), ] actual = fix_os_paths(f.choices) self.assertEqual(len(expected), len(actual)) for exp, got in zip(expected, actual): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) f = FilePathField(path=path, allow_folders=True, allow_files=True) f.choices.sort() expected = [ ('/forms_tests/tests/filepath_test_files/.dot-file', '.dot-file'), ('/forms_tests/tests/filepath_test_files/1x1.bmp', '1x1.bmp'), ('/forms_tests/tests/filepath_test_files/1x1.png', '1x1.png'), ('/forms_tests/tests/filepath_test_files/directory', 'directory'), ('/forms_tests/tests/filepath_test_files/fake-image.jpg', 'fake-image.jpg'), ('/forms_tests/tests/filepath_test_files/real-text-file.txt', 'real-text-file.txt'), ] actual = fix_os_paths(f.choices) self.assertEqual(len(expected), len(actual)) for exp, got in zip(expected, actual): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0]))
baa957ab2325635c3de8864c9715ce4cf802b7256b04a9bf505767020dd685b7
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from django.forms import ( CharField, DateField, FileField, Form, IntegerField, SplitDateTimeField, ValidationError, formsets, ) from django.forms.formsets import BaseFormSet, formset_factory from django.forms.utils import ErrorList from django.test import SimpleTestCase from django.utils.encoding import force_text class Choice(Form): choice = CharField() votes = IntegerField() # FormSet allows us to use multiple instance of the same form on 1 page. For now, # the best way to create a FormSet is by using the formset_factory function. ChoiceFormSet = formset_factory(Choice) class FavoriteDrinkForm(Form): name = CharField() class BaseFavoriteDrinksFormSet(BaseFormSet): def clean(self): seen_drinks = [] for drink in self.cleaned_data: if drink['name'] in seen_drinks: raise ValidationError('You may only specify a drink once.') seen_drinks.append(drink['name']) class EmptyFsetWontValidate(BaseFormSet): def clean(self): raise ValidationError("Clean method called") # Let's define a FormSet that takes a list of favorite drinks, but raises an # error if there are any duplicates. Used in ``test_clean_hook``, # ``test_regression_6926`` & ``test_regression_12878``. FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3) # Used in ``test_formset_splitdatetimefield``. class SplitDateTimeForm(Form): when = SplitDateTimeField(initial=datetime.datetime.now) SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) class CustomKwargForm(Form): def __init__(self, *args, **kwargs): self.custom_kwarg = kwargs.pop('custom_kwarg') super(CustomKwargForm, self).__init__(*args, **kwargs) class FormsFormsetTestCase(SimpleTestCase): def make_choiceformset( self, formset_data=None, formset_class=ChoiceFormSet, total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs): """ Make a ChoiceFormset from the given formset_data. The data should be given as a list of (choice, votes) tuples. """ kwargs.setdefault('prefix', 'choices') kwargs.setdefault('auto_id', False) if formset_data is None: return formset_class(**kwargs) if total_forms is None: total_forms = len(formset_data) def prefixed(*args): args = (kwargs['prefix'],) + args return '-'.join(args) data = { prefixed('TOTAL_FORMS'): str(total_forms), prefixed('INITIAL_FORMS'): str(initial_forms), prefixed('MAX_NUM_FORMS'): str(max_num_forms), prefixed('MIN_NUM_FORMS'): str(min_num_forms), } for i, (choice, votes) in enumerate(formset_data): data[prefixed(str(i), 'choice')] = choice data[prefixed(str(i), 'votes')] = votes return formset_class(data, **kwargs) def test_basic_formset(self): # A FormSet constructor takes the same arguments as Form. Let's create a FormSet # for adding data. By default, it displays 1 blank form. It can display more, # but we'll look at how to do so later. formset = self.make_choiceformset() self.assertHTMLEqual( str(formset), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /> <input type="hidden" name="choices-INITIAL_FORMS" value="0" /> <input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /> <input type="hidden" name="choices-MAX_NUM_FORMS" value="1000" /> <tr><th>Choice:</th><td><input type="text" name="choices-0-choice" /></td></tr> <tr><th>Votes:</th><td><input type="number" name="choices-0-votes" /></td></tr>""" ) # We treat FormSet pretty much like we would treat a normal Form. FormSet has an # is_valid method, and a cleaned_data or errors attribute depending on whether all # the forms passed validation. However, unlike a Form instance, cleaned_data and # errors will be a list of dicts rather than just a single dict. formset = self.make_choiceformset([('Calexico', '100')]) self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}]) # If a FormSet was not passed any data, its is_valid and has_changed # methods should return False. formset = self.make_choiceformset() self.assertFalse(formset.is_valid()) self.assertFalse(formset.has_changed()) def test_form_kwargs_formset(self): """ Test that custom kwargs set on the formset instance are passed to the underlying forms. """ FormSet = formset_factory(CustomKwargForm, extra=2) formset = FormSet(form_kwargs={'custom_kwarg': 1}) for form in formset: self.assertTrue(hasattr(form, 'custom_kwarg')) self.assertEqual(form.custom_kwarg, 1) def test_form_kwargs_formset_dynamic(self): """ Test that form kwargs can be passed dynamically in a formset. """ class DynamicBaseFormSet(BaseFormSet): def get_form_kwargs(self, index): return {'custom_kwarg': index} DynamicFormSet = formset_factory(CustomKwargForm, formset=DynamicBaseFormSet, extra=2) formset = DynamicFormSet(form_kwargs={'custom_kwarg': 'ignored'}) for i, form in enumerate(formset): self.assertTrue(hasattr(form, 'custom_kwarg')) self.assertEqual(form.custom_kwarg, i) def test_form_kwargs_empty_form(self): FormSet = formset_factory(CustomKwargForm) formset = FormSet(form_kwargs={'custom_kwarg': 1}) self.assertTrue(hasattr(formset.empty_form, 'custom_kwarg')) self.assertEqual(formset.empty_form.custom_kwarg, 1) def test_formset_validation(self): # FormSet instances can also have an error attribute if validation failed for # any of the forms. formset = self.make_choiceformset([('Calexico', '')]) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'votes': ['This field is required.']}]) def test_formset_has_changed(self): # FormSet instances has_changed method will be True if any data is # passed to his forms, even if the formset didn't validate blank_formset = self.make_choiceformset([('', '')]) self.assertFalse(blank_formset.has_changed()) # invalid formset test invalid_formset = self.make_choiceformset([('Calexico', '')]) self.assertFalse(invalid_formset.is_valid()) self.assertTrue(invalid_formset.has_changed()) # valid formset test valid_formset = self.make_choiceformset([('Calexico', '100')]) self.assertTrue(valid_formset.is_valid()) self.assertTrue(valid_formset.has_changed()) def test_formset_initial_data(self): # We can also prefill a FormSet with existing data by providing an ``initial`` # argument to the constructor. ``initial`` should be a list of dicts. By default, # an extra blank form is included. initial = [{'choice': 'Calexico', 'votes': 100}] formset = self.make_choiceformset(initial=initial) form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertHTMLEqual( '\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="number" name="choices-0-votes" value="100" /></li> <li>Choice: <input type="text" name="choices-1-choice" /></li> <li>Votes: <input type="number" name="choices-1-votes" /></li>""" ) # Let's simulate what would happen if we submitted this form. formset = self.make_choiceformset([('Calexico', '100'), ('', '')], initial_forms=1) self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}, {}]) def test_second_form_partially_filled(self): # But the second form was blank! Shouldn't we get some errors? No. If we display # a form as blank, it's ok for it to be submitted as blank. If we fill out even # one of the fields of a blank form though, it will be validated. We may want to # required that at least x number of forms are completed, but we'll show how to # handle that later. formset = self.make_choiceformset([('Calexico', '100'), ('The Decemberists', '')], initial_forms=1) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{}, {'votes': ['This field is required.']}]) def test_delete_prefilled_data(self): # If we delete data that was pre-filled, we should get an error. Simply removing # data from form fields isn't the proper way to delete it. We'll see how to # handle that case later. formset = self.make_choiceformset([('', ''), ('', '')], initial_forms=1) self.assertFalse(formset.is_valid()) self.assertEqual( formset.errors, [{'votes': ['This field is required.'], 'choice': ['This field is required.']}, {}] ) def test_displaying_more_than_one_blank_form(self): # Displaying more than 1 blank form ########################################### # We can also display more than 1 empty form at a time. To do so, pass a # extra argument to formset_factory. ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertHTMLEqual( '\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" /></li> <li>Votes: <input type="number" name="choices-0-votes" /></li> <li>Choice: <input type="text" name="choices-1-choice" /></li> <li>Votes: <input type="number" name="choices-1-votes" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="number" name="choices-2-votes" /></li>""" ) # Since we displayed every form as blank, we will also accept them back as blank. # This may seem a little strange, but later we will show how to require a minimum # number of forms to be completed. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': '', 'choices-0-votes': '', 'choices-1-choice': '', 'choices-1-votes': '', 'choices-2-choice': '', 'choices-2-votes': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}]) def test_min_num_displaying_more_than_one_blank_form(self): # We can also display more than 1 empty form passing min_num argument # to formset_factory. It will (essentially) increment the extra argument ChoiceFormSet = formset_factory(Choice, extra=1, min_num=1) formset = ChoiceFormSet(auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) # Min_num forms are required; extra forms can be empty. self.assertFalse(formset.forms[0].empty_permitted) self.assertTrue(formset.forms[1].empty_permitted) self.assertHTMLEqual( '\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" /></li> <li>Votes: <input type="number" name="choices-0-votes" /></li> <li>Choice: <input type="text" name="choices-1-choice" /></li> <li>Votes: <input type="number" name="choices-1-votes" /></li>""" ) def test_min_num_displaying_more_than_one_blank_form_with_zero_extra(self): # We can also display more than 1 empty form passing min_num argument ChoiceFormSet = formset_factory(Choice, extra=0, min_num=3) formset = ChoiceFormSet(auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertHTMLEqual( '\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" /></li> <li>Votes: <input type="number" name="choices-0-votes" /></li> <li>Choice: <input type="text" name="choices-1-choice" /></li> <li>Votes: <input type="number" name="choices-1-votes" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="number" name="choices-2-votes" /></li>""" ) def test_single_form_completed(self): # We can just fill out one of the forms. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': '', 'choices-1-votes': '', 'choices-2-choice': '', 'choices-2-votes': '', } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}, {}, {}]) def test_formset_validate_max_flag(self): # If validate_max is set and max_num is less than TOTAL_FORMS in the # data, then throw an exception. MAX_NUM_FORMS in the data is # irrelevant here (it's output as a hint for the client but its # value in the returned data is not checked) data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 1 or fewer forms.']) def test_formset_validate_min_flag(self): # If validate_min is set and min_num is more than TOTAL_FORMS in the # data, then throw an exception. MIN_NUM_FORMS in the data is # irrelevant here (it's output as a hint for the client but its # value in the returned data is not checked) data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', } ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 3 or more forms.']) def test_formset_validate_min_excludes_empty_forms(self): data = { 'choices-TOTAL_FORMS': '2', 'choices-INITIAL_FORMS': '0', } ChoiceFormSet = formset_factory(Choice, extra=2, min_num=1, validate_min=True, can_delete=True) formset = ChoiceFormSet(data, prefix='choices') self.assertFalse(formset.has_changed()) self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 1 or more forms.']) def test_second_form_partially_filled_2(self): # And once again, if we try to partially complete a form, validation will fail. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': 'The Decemberists', 'choices-1-votes': '', # missing value 'choices-2-choice': '', 'choices-2-votes': '', } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{}, {'votes': ['This field is required.']}, {}]) def test_more_initial_data(self): # The extra argument also works when the formset is pre-filled with initial # data. initial = [{'choice': 'Calexico', 'votes': 100}] ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertHTMLEqual( '\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="number" name="choices-0-votes" value="100" /></li> <li>Choice: <input type="text" name="choices-1-choice" /></li> <li>Votes: <input type="number" name="choices-1-votes" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="number" name="choices-2-votes" /></li> <li>Choice: <input type="text" name="choices-3-choice" /></li> <li>Votes: <input type="number" name="choices-3-votes" /></li>""" ) # Make sure retrieving an empty form works, and it shows up in the form list self.assertTrue(formset.empty_form.empty_permitted) self.assertHTMLEqual( formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice" /></li> <li>Votes: <input type="number" name="choices-__prefix__-votes" /></li>""" ) def test_formset_with_deletion(self): # FormSets with deletion ###################################################### # We can easily add deletion ability to a FormSet with an argument to # formset_factory. This will add a boolean field to each form instance. When # that boolean field is True, the form will be in formset.deleted_forms ChoiceFormSet = formset_factory(Choice, can_delete=True) initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertHTMLEqual( '\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="number" name="choices-0-votes" value="100" /></li> <li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> <li>Votes: <input type="number" name="choices-1-votes" value="900" /></li> <li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="number" name="choices-2-votes" /></li> <li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li>""" ) # To delete something, we just need to set that form's special delete field to # 'on'. Let's go ahead and delete Fergie. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '2', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-DELETE': '', 'choices-1-choice': 'Fergie', 'choices-1-votes': '900', 'choices-1-DELETE': 'on', 'choices-2-choice': '', 'choices-2-votes': '', 'choices-2-DELETE': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [ {'votes': 100, 'DELETE': False, 'choice': 'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': 'Fergie'}, {}, ] ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': 'Fergie'}] ) # If we fill a form with something and then we check the can_delete checkbox for # that form, that form's errors should not make the entire formset invalid since # it's going to be deleted. class CheckForm(Form): field = IntegerField(min_value=100) data = { 'check-TOTAL_FORMS': '3', # the number of forms rendered 'check-INITIAL_FORMS': '2', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'check-MAX_NUM_FORMS': '0', # max number of forms 'check-0-field': '200', 'check-0-DELETE': '', 'check-1-field': '50', 'check-1-DELETE': 'on', 'check-2-field': '', 'check-2-DELETE': '', } CheckFormSet = formset_factory(CheckForm, can_delete=True) formset = CheckFormSet(data, prefix='check') self.assertTrue(formset.is_valid()) # If we remove the deletion flag now we will have our validation back. data['check-1-DELETE'] = '' formset = CheckFormSet(data, prefix='check') self.assertFalse(formset.is_valid()) # Should be able to get deleted_forms from a valid formset even if a # deleted form would have been invalid. class Person(Form): name = CharField() PeopleForm = formset_factory( form=Person, can_delete=True) p = PeopleForm( {'form-0-name': '', 'form-0-DELETE': 'on', # no name! 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1}) self.assertTrue(p.is_valid()) self.assertEqual(len(p.deleted_forms), 1) def test_formsets_with_ordering(self): # FormSets with ordering ###################################################### # We can also add ordering ability to a FormSet with an argument to # formset_factory. This will add an integer field to each form instance. When # form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct # order specified by the ordering fields. If a number is duplicated in the set # of ordering fields, for instance form 0 and form 3 are both marked as 1, then # the form index used as a secondary ordering criteria. In order to put # something at the front of the list, you'd need to set it's order to 0. ChoiceFormSet = formset_factory(Choice, can_order=True) initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertHTMLEqual( '\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="number" name="choices-0-votes" value="100" /></li> <li>Order: <input type="number" name="choices-0-ORDER" value="1" /></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> <li>Votes: <input type="number" name="choices-1-votes" value="900" /></li> <li>Order: <input type="number" name="choices-1-ORDER" value="2" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="number" name="choices-2-votes" /></li> <li>Order: <input type="number" name="choices-2-ORDER" /></li>""" ) data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '2', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', 'choices-1-choice': 'Fergie', 'choices-1-votes': '900', 'choices-1-ORDER': '2', 'choices-2-choice': 'The Decemberists', 'choices-2-votes': '500', 'choices-2-ORDER': '0', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) form_output = [] for form in formset.ordered_forms: form_output.append(form.cleaned_data) self.assertEqual(form_output, [ {'votes': 500, 'ORDER': 0, 'choice': 'The Decemberists'}, {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'}, {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'}, ]) def test_empty_ordered_fields(self): # Ordering fields are allowed to be left blank, and if they *are* left blank, # they will be sorted below everything else. data = { 'choices-TOTAL_FORMS': '4', # the number of forms rendered 'choices-INITIAL_FORMS': '3', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', 'choices-1-choice': 'Fergie', 'choices-1-votes': '900', 'choices-1-ORDER': '2', 'choices-2-choice': 'The Decemberists', 'choices-2-votes': '500', 'choices-2-ORDER': '', 'choices-3-choice': 'Basia Bulat', 'choices-3-votes': '50', 'choices-3-ORDER': '', } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) form_output = [] for form in formset.ordered_forms: form_output.append(form.cleaned_data) self.assertEqual(form_output, [ {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'}, {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'}, {'votes': 500, 'ORDER': None, 'choice': 'The Decemberists'}, {'votes': 50, 'ORDER': None, 'choice': 'Basia Bulat'}, ]) def test_ordering_blank_fieldsets(self): # Ordering should work with blank fieldsets. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) form_output = [] for form in formset.ordered_forms: form_output.append(form.cleaned_data) self.assertEqual(form_output, []) def test_formset_with_ordering_and_deletion(self): # FormSets with ordering + deletion ########################################### # Let's try throwing ordering and deletion into the same form. ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True) initial = [ {'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}, {'choice': 'The Decemberists', 'votes': 500}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertHTMLEqual( '\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="number" name="choices-0-votes" value="100" /></li> <li>Order: <input type="number" name="choices-0-ORDER" value="1" /></li> <li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> <li>Votes: <input type="number" name="choices-1-votes" value="900" /></li> <li>Order: <input type="number" name="choices-1-ORDER" value="2" /></li> <li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li> <li>Choice: <input type="text" name="choices-2-choice" value="The Decemberists" /></li> <li>Votes: <input type="number" name="choices-2-votes" value="500" /></li> <li>Order: <input type="number" name="choices-2-ORDER" value="3" /></li> <li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li> <li>Choice: <input type="text" name="choices-3-choice" /></li> <li>Votes: <input type="number" name="choices-3-votes" /></li> <li>Order: <input type="number" name="choices-3-ORDER" /></li> <li>Delete: <input type="checkbox" name="choices-3-DELETE" /></li>""" ) # Let's delete Fergie, and put The Decemberists ahead of Calexico. data = { 'choices-TOTAL_FORMS': '4', # the number of forms rendered 'choices-INITIAL_FORMS': '3', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', 'choices-0-DELETE': '', 'choices-1-choice': 'Fergie', 'choices-1-votes': '900', 'choices-1-ORDER': '2', 'choices-1-DELETE': 'on', 'choices-2-choice': 'The Decemberists', 'choices-2-votes': '500', 'choices-2-ORDER': '0', 'choices-2-DELETE': '', 'choices-3-choice': '', 'choices-3-votes': '', 'choices-3-ORDER': '', 'choices-3-DELETE': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) form_output = [] for form in formset.ordered_forms: form_output.append(form.cleaned_data) self.assertEqual(form_output, [ {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': 'The Decemberists'}, {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': 'Calexico'}, ]) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': 'Fergie'}] ) def test_invalid_deleted_form_with_ordering(self): # Should be able to get ordered forms from a valid formset even if a # deleted form would have been invalid. class Person(Form): name = CharField() PeopleForm = formset_factory(form=Person, can_delete=True, can_order=True) p = PeopleForm({ 'form-0-name': '', 'form-0-DELETE': 'on', # no name! 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1 }) self.assertTrue(p.is_valid()) self.assertEqual(p.ordered_forms, []) def test_clean_hook(self): # FormSet clean hook ########################################################## # FormSets have a hook for doing extra validation that shouldn't be tied to any # particular form. It follows the same pattern as the clean hook on Forms. # We start out with a some duplicate data. data = { 'drinks-TOTAL_FORMS': '2', # the number of forms rendered 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data 'drinks-MIN_NUM_FORMS': '0', # min number of forms 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Gin and Tonic', } formset = FavoriteDrinksFormSet(data, prefix='drinks') self.assertFalse(formset.is_valid()) # Any errors raised by formset.clean() are available via the # formset.non_form_errors() method. for error in formset.non_form_errors(): self.assertEqual(str(error), 'You may only specify a drink once.') # Make sure we didn't break the valid case. data = { 'drinks-TOTAL_FORMS': '2', # the number of forms rendered 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data 'drinks-MIN_NUM_FORMS': '0', # min number of forms 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Bloody Mary', } formset = FavoriteDrinksFormSet(data, prefix='drinks') self.assertTrue(formset.is_valid()) self.assertEqual(formset.non_form_errors(), []) def test_limiting_max_forms(self): # Limiting the maximum number of forms ######################################## # Base case for max_num. # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the extra parameter. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertHTMLEqual( '\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th> <td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th> <td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr> <tr><th><label for="id_form-2-name">Name:</label></th> <td><input type="text" name="form-2-name" id="id_form-2-name" /></td></tr>""" ) # If max_num is 0 then no form is rendered at all. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), "") LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertHTMLEqual( '\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td> <input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th> <td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""" ) # Ensure that max_num has no effect when extra is less than max_num. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertHTMLEqual( '\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th> <td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>""" ) def test_max_num_with_initial_data(self): # max_num with initial data # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the initial and extra # parameters. initial = [ {'name': 'Fernet and Coke'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1) formset = LimitedFavoriteDrinkFormSet(initial=initial) form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertHTMLEqual( '\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th> <td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th> <td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""" ) def test_max_num_zero(self): # If max_num is 0 then no form is rendered at all, regardless of extra, # unless initial data is present. (This changed in the patch for bug # 20084 -- previously max_num=0 trumped initial data) LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), "") # test that initial trumps max_num initial = [ {'name': 'Fernet and Coke'}, {'name': 'Bloody Mary'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0) formset = LimitedFavoriteDrinkFormSet(initial=initial) form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertHTMLEqual( '\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th> <td><input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th> <td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary" /></td></tr>""" ) def test_more_initial_than_max_num(self): # More initial forms than max_num now results in all initial forms # being displayed (but no extra forms). This behavior was changed # from max_num taking precedence in the patch for #20084 initial = [ {'name': 'Gin Tonic'}, {'name': 'Bloody Mary'}, {'name': 'Jack and Coke'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) formset = LimitedFavoriteDrinkFormSet(initial=initial) form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertHTMLEqual( '\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th> <td><input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th> <td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary" /></td></tr> <tr><th><label for="id_form-2-name">Name:</label></th> <td><input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke" /></td></tr>""" ) # One form from initial and extra=3 with max_num=2 should result in the one # initial form and one extra. initial = [ {'name': 'Gin Tonic'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2) formset = LimitedFavoriteDrinkFormSet(initial=initial) form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertHTMLEqual( '\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th> <td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th> <td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""" ) def test_regression_6926(self): # Regression test for #6926 ################################################## # Make sure the management form has the correct prefix. formset = FavoriteDrinksFormSet() self.assertEqual(formset.management_form.prefix, 'form') data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MIN_NUM_FORMS': '0', 'form-MAX_NUM_FORMS': '0', } formset = FavoriteDrinksFormSet(data=data) self.assertEqual(formset.management_form.prefix, 'form') formset = FavoriteDrinksFormSet(initial={}) self.assertEqual(formset.management_form.prefix, 'form') def test_regression_12878(self): # Regression test for #12878 ################################################# data = { 'drinks-TOTAL_FORMS': '2', # the number of forms rendered 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data 'drinks-MIN_NUM_FORMS': '0', # min number of forms 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Gin and Tonic', } formset = FavoriteDrinksFormSet(data, prefix='drinks') self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['You may only specify a drink once.']) def test_formset_iteration(self): # Regression tests for #16455 -- formset instances are iterable ChoiceFormset = formset_factory(Choice, extra=3) formset = ChoiceFormset() # confirm iterated formset yields formset.forms forms = list(formset) self.assertEqual(forms, formset.forms) self.assertEqual(len(formset), len(forms)) # confirm indexing of formset self.assertEqual(formset[0], forms[0]) with self.assertRaises(IndexError): formset[3] # Formsets can override the default iteration order class BaseReverseFormSet(BaseFormSet): def __iter__(self): return reversed(self.forms) def __getitem__(self, idx): return super(BaseReverseFormSet, self).__getitem__(len(self) - idx - 1) ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3) reverse_formset = ReverseChoiceFormset() # confirm that __iter__ modifies rendering order # compare forms from "reverse" formset with forms from original formset self.assertEqual(str(reverse_formset[0]), str(forms[-1])) self.assertEqual(str(reverse_formset[1]), str(forms[-2])) self.assertEqual(len(reverse_formset), len(forms)) def test_formset_nonzero(self): """ Formsets with no forms should still evaluate as true. Regression test for #15722 """ ChoiceFormset = formset_factory(Choice, extra=0) formset = ChoiceFormset() self.assertEqual(len(formset.forms), 0) self.assertTrue(formset) def test_formset_splitdatetimefield(self): """ Formset should also work with SplitDateTimeField(initial=datetime.datetime.now). Regression test for #18709. """ data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-0-when_0': '1904-06-16', 'form-0-when_1': '15:51:33', } formset = SplitDateTimeFormSet(data) self.assertTrue(formset.is_valid()) def test_formset_error_class(self): # Regression tests for #16479 -- formsets form use ErrorList instead of supplied error_class class CustomErrorList(ErrorList): pass formset = FavoriteDrinksFormSet(error_class=CustomErrorList) self.assertEqual(formset.forms[0].error_class, CustomErrorList) def test_formset_calls_forms_is_valid(self): # Regression tests for #18574 -- make sure formsets call # is_valid() on each form. class AnotherChoice(Choice): def is_valid(self): self.is_valid_called = True return super(AnotherChoice, self).is_valid() AnotherChoiceFormSet = formset_factory(AnotherChoice) data = { 'choices-TOTAL_FORMS': '1', # number of forms rendered 'choices-INITIAL_FORMS': '0', # number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', } formset = AnotherChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertTrue(all(form.is_valid_called for form in formset.forms)) def test_hard_limit_on_instantiated_forms(self): """A formset has a hard limit on the number of forms instantiated.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 2 ChoiceFormSet = formset_factory(Choice, max_num=1) # someone fiddles with the mgmt form data... formset = ChoiceFormSet( { 'choices-TOTAL_FORMS': '4', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '4', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', 'choices-2-choice': 'Two', 'choices-2-votes': '2', 'choices-3-choice': 'Three', 'choices-3-votes': '3', }, prefix='choices', ) # But we still only instantiate 3 forms self.assertEqual(len(formset.forms), 3) # and the formset isn't valid self.assertFalse(formset.is_valid()) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_increase_hard_limit(self): """Can increase the built-in forms limit via a higher max_num.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 3 # for this form, we want a limit of 4 ChoiceFormSet = formset_factory(Choice, max_num=4) formset = ChoiceFormSet( { 'choices-TOTAL_FORMS': '4', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '4', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', 'choices-2-choice': 'Two', 'choices-2-votes': '2', 'choices-3-choice': 'Three', 'choices-3-votes': '3', }, prefix='choices', ) # Four forms are instantiated and no exception is raised self.assertEqual(len(formset.forms), 4) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_non_form_errors_run_full_clean(self): # Regression test for #11160 # If non_form_errors() is called without calling is_valid() first, # it should ensure that full_clean() is called. class BaseCustomFormSet(BaseFormSet): def clean(self): raise ValidationError("This is a non-form error") ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertIsInstance(formset.non_form_errors(), ErrorList) self.assertEqual(list(formset.non_form_errors()), ['This is a non-form error']) def test_validate_max_ignores_forms_marked_for_deletion(self): class CheckForm(Form): field = IntegerField() data = { 'check-TOTAL_FORMS': '2', 'check-INITIAL_FORMS': '0', 'check-MAX_NUM_FORMS': '1', 'check-0-field': '200', 'check-0-DELETE': '', 'check-1-field': '50', 'check-1-DELETE': 'on', } CheckFormSet = formset_factory(CheckForm, max_num=1, validate_max=True, can_delete=True) formset = CheckFormSet(data, prefix='check') self.assertTrue(formset.is_valid()) def test_formset_total_error_count(self): """A valid formset should have 0 total errors.""" data = [ # formset_data, expected error count ([('Calexico', '100')], 0), ([('Calexico', '')], 1), ([('', 'invalid')], 2), ([('Calexico', '100'), ('Calexico', '')], 1), ([('Calexico', ''), ('Calexico', '')], 2), ] for formset_data, expected_error_count in data: formset = self.make_choiceformset(formset_data) self.assertEqual(formset.total_error_count(), expected_error_count) def test_formset_total_error_count_with_non_form_errors(self): data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertEqual(formset.total_error_count(), 1) data['choices-1-votes'] = '' formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertEqual(formset.total_error_count(), 2) def test_html_safe(self): formset = self.make_choiceformset() self.assertTrue(hasattr(formset, '__html__')) self.assertEqual(force_text(formset), formset.__html__()) data = { 'choices-TOTAL_FORMS': '1', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', } class FormsetAsFooTests(SimpleTestCase): def test_as_table(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertHTMLEqual( formset.as_table(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /> <input type="hidden" name="choices-INITIAL_FORMS" value="0" /> <input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /> <input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> <tr><th>Choice:</th><td><input type="text" name="choices-0-choice" value="Calexico" /></td></tr> <tr><th>Votes:</th><td><input type="number" name="choices-0-votes" value="100" /></td></tr>""" ) def test_as_p(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertHTMLEqual( formset.as_p(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /> <input type="hidden" name="choices-INITIAL_FORMS" value="0" /> <input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /> <input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> <p>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></p> <p>Votes: <input type="number" name="choices-0-votes" value="100" /></p>""" ) def test_as_ul(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertHTMLEqual( formset.as_ul(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /> <input type="hidden" name="choices-INITIAL_FORMS" value="0" /> <input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /> <input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> <li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="number" name="choices-0-votes" value="100" /></li>""" ) # Regression test for #11418 ################################################# class ArticleForm(Form): title = CharField() pub_date = DateField() ArticleFormSet = formset_factory(ArticleForm) class TestIsBoundBehavior(SimpleTestCase): def test_no_data_raises_validation_error(self): with self.assertRaises(ValidationError): ArticleFormSet({}).is_valid() def test_with_management_data_attrs_work_fine(self): data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', } formset = ArticleFormSet(data) self.assertEqual(0, formset.initial_form_count()) self.assertEqual(1, formset.total_form_count()) self.assertTrue(formset.is_bound) self.assertTrue(formset.forms[0].is_bound) self.assertTrue(formset.is_valid()) self.assertTrue(formset.forms[0].is_valid()) self.assertEqual([{}], formset.cleaned_data) def test_form_errors_are_caught_by_formset(self): data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-0-title': 'Test', 'form-0-pub_date': '1904-06-16', 'form-1-title': 'Test', 'form-1-pub_date': '', # <-- this date is missing but required } formset = ArticleFormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual([{}, {'pub_date': ['This field is required.']}], formset.errors) def test_empty_forms_are_unbound(self): data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-0-title': 'Test', 'form-0-pub_date': '1904-06-16', } unbound_formset = ArticleFormSet() bound_formset = ArticleFormSet(data) empty_forms = [ unbound_formset.empty_form, bound_formset.empty_form ] # Empty forms should be unbound self.assertFalse(empty_forms[0].is_bound) self.assertFalse(empty_forms[1].is_bound) # The empty forms should be equal. self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p()) class TestEmptyFormSet(SimpleTestCase): def test_empty_formset_is_valid(self): """Test that an empty formset still calls clean()""" EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate) formset = EmptyFsetWontValidateFormset( data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'}, prefix="form", ) formset2 = EmptyFsetWontValidateFormset( data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '1', 'form-0-name': 'bah'}, prefix="form", ) self.assertFalse(formset.is_valid()) self.assertFalse(formset2.is_valid()) def test_empty_formset_media(self): """Make sure media is available on empty formset, refs #19545""" class MediaForm(Form): class Media: js = ('some-file.js',) self.assertIn('some-file.js', str(formset_factory(MediaForm, extra=0)().media)) def test_empty_formset_is_multipart(self): """Make sure `is_multipart()` works with empty formset, refs #19545""" class FileForm(Form): file = FileField() self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart())
dcb35d7e53995bbcbfb390465e0f4f1f6b6dfb39f77e277b7b5c223a40940003
# -*- coding: utf-8 -*- from __future__ import unicode_literals import copy from django.core.exceptions import ValidationError from django.forms.utils import ErrorDict, ErrorList, flatatt from django.test import SimpleTestCase from django.utils import six from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy class FormsUtilsTestCase(SimpleTestCase): # Tests for forms/utils.py module. def test_flatatt(self): ########### # flatatt # ########### self.assertEqual(flatatt({'id': "header"}), ' id="header"') self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"') self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': "required"}), ' class="news" required="required" title="Read this"' ) self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': True}), ' class="news" title="Read this" required' ) self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': False}), ' class="news" title="Read this"' ) self.assertEqual(flatatt({}), '') def test_flatatt_no_side_effects(self): """ Fixes #23883 -- Check that flatatt does not modify the dict passed in """ attrs = {'foo': 'bar', 'true': True, 'false': False} attrs_copy = copy.copy(attrs) self.assertEqual(attrs, attrs_copy) first_run = flatatt(attrs) self.assertEqual(attrs, attrs_copy) self.assertEqual(first_run, ' foo="bar" true') second_run = flatatt(attrs) self.assertEqual(attrs, attrs_copy) self.assertEqual(first_run, second_run) def test_validation_error(self): ################### # ValidationError # ################### # Can take a string. self.assertHTMLEqual( str(ErrorList(ValidationError("There was an error.").messages)), '<ul class="errorlist"><li>There was an error.</li></ul>' ) # Can take a unicode string. self.assertHTMLEqual( six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)), '<ul class="errorlist"><li>Not π.</li></ul>' ) # Can take a lazy string. self.assertHTMLEqual( str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)), '<ul class="errorlist"><li>Error.</li></ul>' ) # Can take a list. self.assertHTMLEqual( str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), '<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>' ) # Can take a dict. self.assertHTMLEqual( str(ErrorList(sorted(ValidationError({'error_1': "1. Error one.", 'error_2': "2. Error two."}).messages))), '<ul class="errorlist"><li>1. Error one.</li><li>2. Error two.</li></ul>' ) # Can take a mixture in a list. self.assertHTMLEqual( str(ErrorList(sorted(ValidationError([ "1. First error.", "2. Not \u03C0.", ugettext_lazy("3. Error."), { 'error_1': "4. First dict error.", 'error_2': "5. Second dict error.", }, ]).messages))), '<ul class="errorlist">' '<li>1. First error.</li>' '<li>2. Not π.</li>' '<li>3. Error.</li>' '<li>4. First dict error.</li>' '<li>5. Second dict error.</li>' '</ul>' ) @python_2_unicode_compatible class VeryBadError: def __str__(self): return "A very bad error." # Can take a non-string. self.assertHTMLEqual( str(ErrorList(ValidationError(VeryBadError()).messages)), '<ul class="errorlist"><li>A very bad error.</li></ul>' ) # Escapes non-safe input but not input marked safe. example = 'Example of link: <a href="http://www.example.com/">example</a>' self.assertHTMLEqual( str(ErrorList([example])), '<ul class="errorlist"><li>Example of link: ' '&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>' ) self.assertHTMLEqual( str(ErrorList([mark_safe(example)])), '<ul class="errorlist"><li>Example of link: ' '<a href="http://www.example.com/">example</a></li></ul>' ) self.assertHTMLEqual( str(ErrorDict({'name': example})), '<ul class="errorlist"><li>nameExample of link: ' '&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>' ) self.assertHTMLEqual( str(ErrorDict({'name': mark_safe(example)})), '<ul class="errorlist"><li>nameExample of link: ' '<a href="http://www.example.com/">example</a></li></ul>' ) def test_error_dict_copy(self): e = ErrorDict() e['__all__'] = ErrorList([ ValidationError( message='message %(i)s', params={'i': 1}, ), ValidationError( message='message %(i)s', params={'i': 2}, ), ]) e_copy = copy.copy(e) self.assertEqual(e, e_copy) self.assertEqual(e.as_data(), e_copy.as_data()) e_deepcopy = copy.deepcopy(e) self.assertEqual(e, e_deepcopy) self.assertEqual(e.as_data(), e_copy.as_data()) def test_error_dict_html_safe(self): e = ErrorDict() e['username'] = 'Invalid username.' self.assertTrue(hasattr(ErrorDict, '__html__')) self.assertEqual(force_text(e), e.__html__()) def test_error_list_html_safe(self): e = ErrorList(['Invalid username.']) self.assertTrue(hasattr(ErrorList, '__html__')) self.assertEqual(force_text(e), e.__html__())
79e49033523c0eccceb8490f915e66c141bdbf05712cc321ddff62e3464541ed
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from django.core.files.uploadedfile import SimpleUploadedFile from django.db import models from django.forms import ( CharField, FileField, Form, ModelChoiceField, ModelForm, ) from django.forms.models import ModelFormMetaclass from django.test import SimpleTestCase, TestCase from django.utils import six from ..models import ( BoundaryModel, ChoiceFieldModel, ChoiceModel, ChoiceOptionModel, Defaults, FileModel, Group, OptionalMultiChoiceModel, ) class ChoiceFieldForm(ModelForm): class Meta: model = ChoiceFieldModel fields = '__all__' class OptionalMultiChoiceModelForm(ModelForm): class Meta: model = OptionalMultiChoiceModel fields = '__all__' class ChoiceFieldExclusionForm(ModelForm): multi_choice = CharField(max_length=50) class Meta: exclude = ['multi_choice'] model = ChoiceFieldModel class EmptyCharLabelChoiceForm(ModelForm): class Meta: model = ChoiceModel fields = ['name', 'choice'] class EmptyIntegerLabelChoiceForm(ModelForm): class Meta: model = ChoiceModel fields = ['name', 'choice_integer'] class EmptyCharLabelNoneChoiceForm(ModelForm): class Meta: model = ChoiceModel fields = ['name', 'choice_string_w_none'] class FileForm(Form): file1 = FileField() class TestModelChoiceField(TestCase): def test_choices_not_fetched_when_not_rendering(self): """ Generating choices for ModelChoiceField should require 1 query (#12510). """ self.groups = [Group.objects.create(name=name) for name in 'abc'] # only one query is required to pull the model from DB with self.assertNumQueries(1): field = ModelChoiceField(Group.objects.order_by('-name')) self.assertEqual('a', field.clean(self.groups[0].pk).name) def test_queryset_manager(self): f = ModelChoiceField(ChoiceOptionModel.objects) choice = ChoiceOptionModel.objects.create(name="choice 1") self.assertEqual(list(f.choices), [('', '---------'), (choice.pk, str(choice))]) class TestTicket14567(TestCase): """ Check that the return values of ModelMultipleChoiceFields are QuerySets """ def test_empty_queryset_return(self): "If a model's ManyToManyField has blank=True and is saved with no data, a queryset is returned." option = ChoiceOptionModel.objects.create(name='default') form = OptionalMultiChoiceModelForm({'multi_choice_optional': '', 'multi_choice': [option.pk]}) self.assertTrue(form.is_valid()) # Check that the empty value is a QuerySet self.assertIsInstance(form.cleaned_data['multi_choice_optional'], models.query.QuerySet) # While we're at it, test whether a QuerySet is returned if there *is* a value. self.assertIsInstance(form.cleaned_data['multi_choice'], models.query.QuerySet) class ModelFormCallableModelDefault(TestCase): def test_no_empty_option(self): "If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792)." option = ChoiceOptionModel.objects.create(name='default') choices = list(ChoiceFieldForm().fields['choice'].choices) self.assertEqual(len(choices), 1) self.assertEqual(choices[0], (option.pk, six.text_type(option))) def test_callable_initial_value(self): "The initial value for a callable default returning a queryset is the pk (refs #13769)" ChoiceOptionModel.objects.create(id=1, name='default') ChoiceOptionModel.objects.create(id=2, name='option 2') ChoiceOptionModel.objects.create(id=3, name='option 3') self.assertHTMLEqual( ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice" required> <option value="1" selected>ChoiceOption 1</option> <option value="2">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-choice" value="1" id="initial-id_choice" /></p> <p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int" required> <option value="1" selected>ChoiceOption 1</option> <option value="2">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-choice_int" value="1" id="initial-id_choice_int" /></p> <p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice" required> <option value="1" selected>ChoiceOption 1</option> <option value="2">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-multi_choice" value="1" id="initial-id_multi_choice_0" /></p> <p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int" required> <option value="1" selected>ChoiceOption 1</option> <option value="2">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0" /></p>""" ) def test_initial_instance_value(self): "Initial instances for model fields may also be instances (refs #7287)" ChoiceOptionModel.objects.create(id=1, name='default') obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') self.assertHTMLEqual( ChoiceFieldForm(initial={ 'choice': obj2, 'choice_int': obj2, 'multi_choice': [obj2, obj3], 'multi_choice_int': ChoiceOptionModel.objects.exclude(name="default"), }).as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice" required> <option value="1">ChoiceOption 1</option> <option value="2" selected>ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-choice" value="2" id="initial-id_choice" /></p> <p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int" required> <option value="1">ChoiceOption 1</option> <option value="2" selected>ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-choice_int" value="2" id="initial-id_choice_int" /></p> <p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice" required> <option value="1">ChoiceOption 1</option> <option value="2" selected>ChoiceOption 2</option> <option value="3" selected>ChoiceOption 3</option> </select><input type="hidden" name="initial-multi_choice" value="2" id="initial-id_multi_choice_0" /> <input type="hidden" name="initial-multi_choice" value="3" id="initial-id_multi_choice_1" /></p> <p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int" required> <option value="1">ChoiceOption 1</option> <option value="2" selected>ChoiceOption 2</option> <option value="3" selected>ChoiceOption 3</option> </select><input type="hidden" name="initial-multi_choice_int" value="2" id="initial-id_multi_choice_int_0" /> <input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1" /></p>""" ) class FormsModelTestCase(TestCase): def test_unicode_filename(self): # FileModel with unicode filename and data ######################### file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8')) f = FileForm(data={}, files={'file1': file1}, auto_id=False) self.assertTrue(f.is_valid()) self.assertIn('file1', f.cleaned_data) m = FileModel.objects.create(file=f.cleaned_data['file1']) self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt') m.delete() def test_boundary_conditions(self): # Boundary conditions on a PositiveIntegerField ######################### class BoundaryForm(ModelForm): class Meta: model = BoundaryModel fields = '__all__' f = BoundaryForm({'positive_integer': 100}) self.assertTrue(f.is_valid()) f = BoundaryForm({'positive_integer': 0}) self.assertTrue(f.is_valid()) f = BoundaryForm({'positive_integer': -100}) self.assertFalse(f.is_valid()) def test_formfield_initial(self): # Formfield initial values ######## # If the model has default values for some fields, they are used as the formfield # initial values. class DefaultsForm(ModelForm): class Meta: model = Defaults fields = '__all__' self.assertEqual(DefaultsForm().fields['name'].initial, 'class default value') self.assertEqual(DefaultsForm().fields['def_date'].initial, datetime.date(1980, 1, 1)) self.assertEqual(DefaultsForm().fields['value'].initial, 42) r1 = DefaultsForm()['callable_default'].as_widget() r2 = DefaultsForm()['callable_default'].as_widget() self.assertNotEqual(r1, r2) # In a ModelForm that is passed an instance, the initial values come from the # instance's values, not the model's defaults. foo_instance = Defaults(name='instance value', def_date=datetime.date(1969, 4, 4), value=12) instance_form = DefaultsForm(instance=foo_instance) self.assertEqual(instance_form.initial['name'], 'instance value') self.assertEqual(instance_form.initial['def_date'], datetime.date(1969, 4, 4)) self.assertEqual(instance_form.initial['value'], 12) from django.forms import CharField class ExcludingForm(ModelForm): name = CharField(max_length=255) class Meta: model = Defaults exclude = ['name', 'callable_default'] f = ExcludingForm({'name': 'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['name'], 'Hello') obj = f.save() self.assertEqual(obj.name, 'class default value') self.assertEqual(obj.value, 99) self.assertEqual(obj.def_date, datetime.date(1999, 3, 2)) class RelatedModelFormTests(SimpleTestCase): def test_invalid_loading_order(self): """ Test for issue 10405 """ class A(models.Model): ref = models.ForeignKey("B", models.CASCADE) class Meta: model = A fields = '__all__' with self.assertRaises(ValueError): ModelFormMetaclass(str('Form'), (ModelForm,), {'Meta': Meta}) class B(models.Model): pass def test_valid_loading_order(self): """ Test for issue 10405 """ class C(models.Model): ref = models.ForeignKey("D", models.CASCADE) class D(models.Model): pass class Meta: model = C fields = '__all__' self.assertTrue(issubclass(ModelFormMetaclass(str('Form'), (ModelForm,), {'Meta': Meta}), ModelForm)) class ManyToManyExclusionTestCase(TestCase): def test_m2m_field_exclusion(self): # Issue 12337. save_instance should honor the passed-in exclude keyword. opt1 = ChoiceOptionModel.objects.create(id=1, name='default') opt2 = ChoiceOptionModel.objects.create(id=2, name='option 2') opt3 = ChoiceOptionModel.objects.create(id=3, name='option 3') initial = { 'choice': opt1, 'choice_int': opt1, } data = { 'choice': opt2.pk, 'choice_int': opt2.pk, 'multi_choice': 'string data!', 'multi_choice_int': [opt1.pk], } instance = ChoiceFieldModel.objects.create(**initial) instance.multi_choice.set([opt2, opt3]) instance.multi_choice_int.set([opt2, opt3]) form = ChoiceFieldExclusionForm(data=data, instance=instance) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['multi_choice'], data['multi_choice']) form.save() self.assertEqual(form.instance.choice.pk, data['choice']) self.assertEqual(form.instance.choice_int.pk, data['choice_int']) self.assertEqual(list(form.instance.multi_choice.all()), [opt2, opt3]) self.assertEqual([obj.pk for obj in form.instance.multi_choice_int.all()], data['multi_choice_int']) class EmptyLabelTestCase(TestCase): def test_empty_field_char(self): f = EmptyCharLabelChoiceForm() self.assertHTMLEqual( f.as_p(), """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required /></p> <p><label for="id_choice">Choice:</label> <select id="id_choice" name="choice"> <option value="" selected>No Preference</option> <option value="f">Foo</option> <option value="b">Bar</option> </select></p>""" ) def test_empty_field_char_none(self): f = EmptyCharLabelNoneChoiceForm() self.assertHTMLEqual( f.as_p(), """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required /></p> <p><label for="id_choice_string_w_none">Choice string w none:</label> <select id="id_choice_string_w_none" name="choice_string_w_none"> <option value="" selected>No Preference</option> <option value="f">Foo</option> <option value="b">Bar</option> </select></p>""" ) def test_save_empty_label_forms(self): # Test that saving a form with a blank choice results in the expected # value being stored in the database. tests = [ (EmptyCharLabelNoneChoiceForm, 'choice_string_w_none', None), (EmptyIntegerLabelChoiceForm, 'choice_integer', None), (EmptyCharLabelChoiceForm, 'choice', ''), ] for form, key, expected in tests: f = form({'name': 'some-key', key: ''}) self.assertTrue(f.is_valid()) m = f.save() self.assertEqual(expected, getattr(m, key)) self.assertEqual('No Preference', getattr(m, 'get_{}_display'.format(key))()) def test_empty_field_integer(self): f = EmptyIntegerLabelChoiceForm() self.assertHTMLEqual( f.as_p(), """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required /></p> <p><label for="id_choice_integer">Choice integer:</label> <select id="id_choice_integer" name="choice_integer"> <option value="" selected>No Preference</option> <option value="1">Foo</option> <option value="2">Bar</option> </select></p>""" ) def test_get_display_value_on_none(self): m = ChoiceModel.objects.create(name='test', choice='', choice_integer=None) self.assertIsNone(m.choice_integer) self.assertEqual('No Preference', m.get_choice_integer_display()) def test_html_rendering_of_prepopulated_models(self): none_model = ChoiceModel(name='none-test', choice_integer=None) f = EmptyIntegerLabelChoiceForm(instance=none_model) self.assertHTMLEqual( f.as_p(), """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" value="none-test" required /></p> <p><label for="id_choice_integer">Choice integer:</label> <select id="id_choice_integer" name="choice_integer"> <option value="" selected>No Preference</option> <option value="1">Foo</option> <option value="2">Bar</option> </select></p>""" ) foo_model = ChoiceModel(name='foo-test', choice_integer=1) f = EmptyIntegerLabelChoiceForm(instance=foo_model) self.assertHTMLEqual( f.as_p(), """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" value="foo-test" required /></p> <p><label for="id_choice_integer">Choice integer:</label> <select id="id_choice_integer" name="choice_integer"> <option value="">No Preference</option> <option value="1" selected>Foo</option> <option value="2">Bar</option> </select></p>""" )
f791391b702f58db13c2fa1c8a5be1f427a88089d2c6b45e213d4f53712a1724
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ( BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField, EmailField, FileField, FloatField, Form, GenericIPAddressField, IntegerField, ModelChoiceField, ModelMultipleChoiceField, MultipleChoiceField, RegexField, SplitDateTimeField, TimeField, URLField, ValidationError, utils, ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase from django.utils.encoding import python_2_unicode_compatible from django.utils.safestring import mark_safe from ..models import ChoiceModel class AssertFormErrorsMixin(object): def assertFormErrors(self, expected, the_callable, *args, **kwargs): with self.assertRaises(ValidationError) as cm: the_callable(*args, **kwargs) self.assertEqual(cm.exception.messages, expected) class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin): def test_charfield(self): e = { 'required': 'REQUIRED', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = CharField(min_length=5, max_length=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234') self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') def test_integerfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', } f = IntegerField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') def test_floatfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', } f = FloatField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') def test_decimalfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', 'max_digits': 'MAX DIGITS IS %(max)s', 'max_decimal_places': 'MAX DP IS %(max)s', 'max_whole_digits': 'MAX DIGITS BEFORE DP IS %(max)s', } f = DecimalField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e) self.assertFormErrors(['MAX DIGITS IS 4'], f2.clean, '123.45') self.assertFormErrors(['MAX DP IS 2'], f2.clean, '1.234') self.assertFormErrors(['MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4') def test_datefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = DateField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_timefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = TimeField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_datetimefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = DateTimeField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_regexfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = RegexField(r'^[0-9]+$', min_length=5, max_length=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abcde') self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234') self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') def test_emailfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = EmailField(min_length=8, max_length=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abcdefgh') self.assertFormErrors(['LENGTH 7, MIN LENGTH 8'], f.clean, '[email protected]') self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '[email protected]') def test_filefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'missing': 'MISSING', 'empty': 'EMPTY FILE', } f = FileField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None)) self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', '')) def test_urlfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'max_length': '"%(value)s" has more than %(limit_value)d characters.', } f = URLField(error_messages=e, max_length=17) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc.c') self.assertFormErrors( ['"http://djangoproject.com" has more than 17 characters.'], f.clean, 'djangoproject.com' ) def test_booleanfield(self): e = { 'required': 'REQUIRED', } f = BooleanField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') def test_choicefield(self): e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', } f = ChoiceField(choices=[('a', 'aye')], error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, 'b') def test_multiplechoicefield(self): e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', 'invalid_list': 'NOT A LIST', } f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['NOT A LIST'], f.clean, 'b') self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, ['b']) def test_splitdatetimefield(self): e = { 'required': 'REQUIRED', 'invalid_date': 'INVALID DATE', 'invalid_time': 'INVALID TIME', } f = SplitDateTimeField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID DATE', 'INVALID TIME'], f.clean, ['a', 'b']) def test_generic_ipaddressfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID IP ADDRESS', } f = GenericIPAddressField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0') def test_subclassing_errorlist(self): class TestForm(Form): first_name = CharField() last_name = CharField() birthday = DateField() def clean(self): raise ValidationError("I like to be awkward.") @python_2_unicode_compatible class CustomErrorList(utils.ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return mark_safe('<div class="error">%s</div>' % ''.join('<p>%s</p>' % e for e in self)) # This form should print errors the default way. form1 = TestForm({'first_name': 'John'}) self.assertHTMLEqual( str(form1['last_name'].errors), '<ul class="errorlist"><li>This field is required.</li></ul>' ) self.assertHTMLEqual( str(form1.errors['__all__']), '<ul class="errorlist nonfield"><li>I like to be awkward.</li></ul>' ) # This one should wrap error groups in the customized way. form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList) self.assertHTMLEqual(str(form2['last_name'].errors), '<div class="error"><p>This field is required.</p></div>') self.assertHTMLEqual(str(form2.errors['__all__']), '<div class="error"><p>I like to be awkward.</p></div>') def test_error_messages_escaping(self): # The forms layer doesn't escape input values directly because error # messages might be presented in non-HTML contexts. Instead, the # message is marked for escaping by the template engine, so a template # is needed to trigger the escaping. t = Template('{{ form.errors }}') class SomeForm(Form): field = ChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': '<script>'}) self.assertHTMLEqual( t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist">' '<li>Select a valid choice. &lt;script&gt; is not one of the ' 'available choices.</li></ul></li></ul>' ) class SomeForm(Form): field = MultipleChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': ['<script>']}) self.assertHTMLEqual( t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist">' '<li>Select a valid choice. &lt;script&gt; is not one of the ' 'available choices.</li></ul></li></ul>' ) class SomeForm(Form): field = ModelMultipleChoiceField(ChoiceModel.objects.all()) f = SomeForm({'field': ['<script>']}) self.assertHTMLEqual( t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist">' '<li>&quot;&lt;script&gt;&quot; is not a valid value for a ' 'primary key.</li></ul></li></ul>' ) class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): def test_modelchoicefield(self): # Create choices for the model choice field tests below. ChoiceModel.objects.create(pk=1, name='a') ChoiceModel.objects.create(pk=2, name='b') ChoiceModel.objects.create(pk=3, name='c') # ModelChoiceField e = { 'required': 'REQUIRED', 'invalid_choice': 'INVALID CHOICE', } f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID CHOICE'], f.clean, '4') # ModelMultipleChoiceField e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', 'list': 'NOT A LIST OF VALUES', } f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3') self.assertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4'])
2439d4f5153f403cb1de20600a978b1025d7b6e5bc0f90b5a39e3417246aa7d8
from datetime import date, datetime, time from django import forms from django.test import SimpleTestCase, override_settings from django.utils.translation import activate, deactivate @override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"], USE_L10N=True) class LocalizedTimeTests(SimpleTestCase): def setUp(self): # nl/formats.py has customized TIME_INPUT_FORMATS: # ['%H:%M:%S', '%H.%M:%S', '%H.%M', '%H:%M'] activate('nl') def tearDown(self): deactivate() def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('13:30:05') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, '13:30:05') # Parse a time in a valid, but non-default format, get a parsed result result = f.clean('13:30') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") # ISO formats are accepted, even if not specified in formats.py result = f.clean('13:30:05.000155') self.assertEqual(result, time(13, 30, 5, 155)) def test_localized_timeField(self): "Localized TimeFields act as unlocalized widgets" f = forms.TimeField(localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('13:30:05') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13:30') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM') with self.assertRaises(forms.ValidationError): f.clean('13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('13.30') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField_with_inputformat(self): "Localized TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM') with self.assertRaises(forms.ValidationError): f.clean('13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('13.30') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") @override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"]) class CustomTimeInputFormatsTests(SimpleTestCase): def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('1:30:05 PM') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, '01:30:05 PM') # Parse a time in a valid, but non-default format, get a parsed result result = f.clean('1:30 PM') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM") def test_localized_timeField(self): "Localized TimeFields act as unlocalized widgets" f = forms.TimeField(localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('1:30:05 PM') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, '01:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('01:30 PM') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM') with self.assertRaises(forms.ValidationError): f.clean('13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean('13.30') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM") def test_localized_timeField_with_inputformat(self): "Localized TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM') with self.assertRaises(forms.ValidationError): f.clean('13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean('13.30') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM") class SimpleTimeFormatTests(SimpleTestCase): def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('13:30:05') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid, but non-default format, get a parsed result result = f.clean('13:30') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField(self): "Localized TimeFields in a non-localized environment act as unlocalized widgets" f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('13:30:05') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('13:30') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('1:30:05 PM') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('1:30 PM') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField_with_inputformat(self): "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) # Parse a time in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('1:30:05 PM') self.assertEqual(result, time(13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('1:30 PM') self.assertEqual(result, time(13, 30, 0)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") @override_settings(DATE_INPUT_FORMATS=["%d/%m/%Y", "%d-%m-%Y"], USE_L10N=True) class LocalizedDateTests(SimpleTestCase): def setUp(self): activate('de') def tearDown(self): deactivate() def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('21/12/2010') # ISO formats are accepted, even if not specified in formats.py self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21)) # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, '21.12.2010') # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('21.12.10') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField(self): "Localized DateFields act as unlocalized widgets" f = forms.DateField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('21/12/2010') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, '21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.10') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21') with self.assertRaises(forms.ValidationError): f.clean('21/12/2010') with self.assertRaises(forms.ValidationError): f.clean('21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField_with_inputformat(self): "Localized DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21') with self.assertRaises(forms.ValidationError): f.clean('21/12/2010') with self.assertRaises(forms.ValidationError): f.clean('21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") @override_settings(DATE_INPUT_FORMATS=["%d.%m.%Y", "%d-%m-%Y"]) class CustomDateInputFormatsTests(SimpleTestCase): def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, '21.12.2010') # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('21-12-2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField(self): "Localized DateFields act as unlocalized widgets" f = forms.DateField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, '21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('21-12-2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('21.12.2010') with self.assertRaises(forms.ValidationError): f.clean('2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField_with_inputformat(self): "Localized DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('21.12.2010') with self.assertRaises(forms.ValidationError): f.clean('2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") class SimpleDateFormatTests(SimpleTestCase): def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('2010-12-21') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('12/21/2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") def test_localized_dateField(self): "Localized DateFields in a non-localized environment act as unlocalized widgets" f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('2010-12-21') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean('12/21/2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean('21-12-2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") def test_localized_dateField_with_inputformat(self): "Localized DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean('21-12-2010') self.assertEqual(result, date(2010, 12, 21)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") @override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"], USE_L10N=True) class LocalizedDateTimeTests(SimpleTestCase): def setUp(self): activate('de') def tearDown(self): deactivate() def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM 21/12/2010') # ISO formats are accepted, even if not specified in formats.py self.assertEqual(f.clean('2010-12-21 13:30:05'), datetime(2010, 12, 21, 13, 30, 5)) # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, '21.12.2010 13:30:05') # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('21.12.2010 13:30') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_localized_dateTimeField(self): "Localized DateTimeFields act as unlocalized widgets" f = forms.DateTimeField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM 21/12/2010') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, '21.12.2010 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010 13:30') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_dateTimeField_with_inputformat(self): "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"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21 13:30:05 13:30:05') with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM 21/12/2010') with self.assertRaises(forms.ValidationError): f.clean('13:30:05 21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('13.30.05 12.21.2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('13.30 12-21-2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_localized_dateTimeField_with_inputformat(self): "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) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21 13:30:05') with self.assertRaises(forms.ValidationError): f.clean('1:30:05 PM 21/12/2010') with self.assertRaises(forms.ValidationError): f.clean('13:30:05 21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('13.30.05 12.21.2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('13.30 12-21-2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") @override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"]) class CustomDateTimeInputFormatsTests(SimpleTestCase): def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('1:30:05 PM 21/12/2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, '01:30:05 PM 21/12/2010') # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('1:30 PM 21-12-2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_localized_dateTimeField(self): "Localized DateTimeFields act as unlocalized widgets" f = forms.DateTimeField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('1:30:05 PM 21/12/2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, '01:30:05 PM 21/12/2010') # Parse a date in a valid format, get a parsed result result = f.clean('1:30 PM 21-12-2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_dateTimeField_with_inputformat(self): "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"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('13:30:05 21.12.2010') with self.assertRaises(forms.ValidationError): f.clean('2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010 13:30') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_localized_dateTimeField_with_inputformat(self): "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) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('13:30:05 21.12.2010') with self.assertRaises(forms.ValidationError): f.clean('2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010 13:30') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") class SimpleDateTimeFormatTests(SimpleTestCase): def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('13:30:05 21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('2010-12-21 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('12/21/2010 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") def test_localized_dateTimeField(self): "Localized DateTimeFields in a non-localized environment act as unlocalized widgets" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('13:30:05 21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('2010-12-21 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('12/21/2010 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") def test_dateTimeField_with_inputformat(self): "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"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('1:30:05 PM 21.12.2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('1:30 PM 21-12-2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:00") def test_localized_dateTimeField_with_inputformat(self): "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) # Parse a date in an unaccepted format; get an error with self.assertRaises(forms.ValidationError): f.clean('2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('1:30:05 PM 21.12.2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # Check that the parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('1:30 PM 21-12-2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # Check that the parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:00")
61b20ccc038fe50ed970366c9767816b5678829806b4e3a4836ba3bc8126916a
from __future__ import unicode_literals from django.forms import ( CharField, ChoiceField, Form, IntegerField, RadioSelect, Select, TextInput, ) from django.test import SimpleTestCase from django.utils import translation from django.utils.translation import gettext_lazy, ugettext_lazy class FormsI18nTests(SimpleTestCase): def test_lazy_labels(self): class SomeForm(Form): username = CharField(max_length=10, label=ugettext_lazy('username')) f = SomeForm() self.assertHTMLEqual( f.as_p(), '<p><label for="id_username">username:</label>' '<input id="id_username" type="text" name="username" maxlength="10" required /></p>' ) # Translations are done at rendering time, so multi-lingual apps can define forms) with translation.override('de'): self.assertHTMLEqual( f.as_p(), '<p><label for="id_username">Benutzername:</label>' '<input id="id_username" type="text" name="username" maxlength="10" required /></p>' ) with translation.override('pl'): self.assertHTMLEqual( f.as_p(), '<p><label for="id_username">u\u017cytkownik:</label>' '<input id="id_username" type="text" name="username" maxlength="10" required /></p>' ) def test_non_ascii_label(self): class SomeForm(Form): field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) field_2 = CharField( max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'}), ) f = SomeForm() self.assertHTMLEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1:</label>') self.assertHTMLEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2:</label>') def test_non_ascii_choices(self): class SomeForm(Form): somechoice = ChoiceField( choices=(('\xc5', 'En tied\xe4'), ('\xf8', 'Mies'), ('\xdf', 'Nainen')), widget=RadioSelect(), label='\xc5\xf8\xdf', ) f = SomeForm() self.assertHTMLEqual( f.as_p(), '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label>' '<ul id="id_somechoice">\n' '<li><label for="id_somechoice_0">' '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" required /> ' 'En tied\xe4</label></li>\n' '<li><label for="id_somechoice_1">' '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" required /> ' 'Mies</label></li>\n<li><label for="id_somechoice_2">' '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" required /> ' 'Nainen</label></li>\n</ul></p>' ) # Translated error messages with translation.override('ru'): f = SomeForm({}) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist"><li>' '\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c' '\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n' '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label>' ' <ul id="id_somechoice">\n<li><label for="id_somechoice_0">' '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" required /> ' 'En tied\xe4</label></li>\n' '<li><label for="id_somechoice_1">' '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" required /> ' 'Mies</label></li>\n<li><label for="id_somechoice_2">' '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" required /> ' 'Nainen</label></li>\n</ul></p>' ) def test_select_translated_text(self): # Deep copying translated text shouldn't raise an error. class CopyForm(Form): degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) CopyForm()