hash
stringlengths
64
64
content
stringlengths
0
1.51M
2954f079bd8f1b7f4fd2fcc779f6d7c3c59d69c1a9d0f9ec402a1fa12ffd42eb
from unittest import TestCase from django.test import SimpleTestCase, TestCase as DjangoTestCase class DjangoCase1(DjangoTestCase): def test_1(self): pass def test_2(self): pass class DjangoCase2(DjangoTestCase): def test_1(self): pass def test_2(self): pass class SimpleCase1(SimpleTestCase): def test_1(self): pass def test_2(self): pass class SimpleCase2(SimpleTestCase): def test_1(self): pass def test_2(self): pass class UnittestCase1(TestCase): def test_1(self): pass def test_2(self): pass class UnittestCase2(TestCase): def test_1(self): pass def test_2(self): pass
04a770ee09a41e1203852f8cdc02060187dcec2d05ebb90ca61f1779f1fee4a8
from unittest import TestCase from django.test import tag @tag('slow') class TaggedTestCase(TestCase): @tag('fast') def test_single_tag(self): self.assertEqual(1, 1) @tag('fast', 'core') def test_multiple_tags(self): self.assertEqual(1, 1)
ddbd3da319787dd3e6b97d707882e16e3c6b94b5aa5bc2ebde130d0d2ad476d5
from unittest import TestCase from django.test import tag @tag('foo') class FooBase(TestCase): pass class Foo(FooBase): def test_no_new_tags(self): pass @tag('baz') def test_new_func_tag(self): pass @tag('bar') class FooBar(FooBase): def test_new_class_tag_only(self): pass @tag('baz') def test_new_class_and_func_tags(self): pass
4beae4e8e2a7b89fe7620cb90040b2e9c4b01b05a8ece3077a70ebd1bdfaa688
from unittest import TestCase class Test(TestCase): def test_sample(self): pass
1ffe8575bc9b46ef647e6d2a4608b1dbdc035da731786d37da3d4b7b62297c64
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, ), ]
fd888e607c09e00af4ec7d3f6c45862cdf8a21d8537c9c5dbab2d8664d88cd6e
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,), ), ]
72ec222ac3683ecf08997ed9d4220dadc0df6dd9ce1f391dab704b16e0b6cbff
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)) if options['integer'] > 0: self.stdout.write("You passed %d as a positional argument." % options['integer'])
e72ef72d5a99705860e943181bde9b9738884af2288c3e51710c8b33839d693b
from django.core.management.base import BaseCommand from django.urls import reverse class Command(BaseCommand): """ This command returns a URL from a reverse() call. """ def handle(self, *args, **options): return reverse('some_url')
990c0bcf3b84ba6c58378e3f6f0d93dd7bd56c7569664ddfaae5b2650bb78613
from django.core.management.base import BaseCommand, no_translations from django.utils import translation class Command(BaseCommand): @no_translations def handle(self, *args, **options): return translation.get_language()
d906a4e0cfeb136ffbe3adcaa1b7935bfc669e60cda2d241a2aac5a309486551
from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Say hello." args = '' output_transaction = True def handle(self, *args, **options): return 'Hello!'
1d83a01268da26450cb62b98cd28ff608532d8e599c8841fd52add6618146844
from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-n', '--need-me', required=True) parser.add_argument('-t', '--need-me-too', required=True, dest='needme2') def handle(self, *args, **options): self.stdout.write(','.join(options))
b50d5e74095a71b24f972800704e49f9cbfd99b5ce4c556afbbb8b2711454d65
from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): subparsers = parser.add_subparsers() parser_foo = subparsers.add_parser('foo') parser_foo.add_argument('bar', type=int) def handle(self, *args, **options): self.stdout.write(','.join(options))
6f98b338204638f34f5e5039bcf72606a8fc65ca4faee56e25e8fb3e19c6eeb2
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', 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.")
d1848a3e28d065f43fe5fc75bec75549e53197cab0086eb46b6b7c7f0797dfd0
from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--set') def handle(self, **options): self.stdout.write('Set %s' % options['set'])
86fc24a71f25b8b049a4ac7c49cfa83dad8250cdec198d01b5e8ccbc76347b01
from argparse import ArgumentError from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def add_arguments(self, parser): try: parser.add_argument('--version', action='version', version='A.B.C') except ArgumentError: pass else: raise CommandError('--version argument does no yet exist') def handle(self, *args, **options): return 'Detected that --version already exists'
686153d26d4d92670641689d750cfe3ea2048a24d30b30617af44a17269baaf6
default_app_config = 'apps.default_config_app.apps.CustomConfig'
1734ae9d01829b3b653a165a0435687d979e4de60f3fd57ae7fb04d74ef23cf0
from django.apps import AppConfig class CustomConfig(AppConfig): name = 'apps.default_config_app'
4fc02909189ceb0d223f06f2166223a73482c203765aa7eeb74ac5c8ea5dfbce
import os from django.apps import AppConfig class NSAppConfig(AppConfig): name = 'nsapp' path = os.path.dirname(__file__)
b4bed455b223078a16f26642f4caccb7d40a63a29d5d11378e29fb36fb31b632
from unittest import mock from django.db import migrations try: from django.contrib.postgres.operations import ( BtreeGinExtension, BtreeGistExtension, CITextExtension, CreateExtension, CryptoExtension, HStoreExtension, TrigramExtension, UnaccentExtension, ) except ImportError: BtreeGinExtension = mock.Mock() BtreeGistExtension = mock.Mock() CITextExtension = mock.Mock() CreateExtension = mock.Mock() CryptoExtension = mock.Mock() HStoreExtension = mock.Mock() TrigramExtension = mock.Mock() UnaccentExtension = mock.Mock() class Migration(migrations.Migration): operations = [ BtreeGinExtension(), BtreeGistExtension(), CITextExtension(), # Ensure CreateExtension quotes extension names by creating one with a # dash in its name. CreateExtension('uuid-ossp'), CryptoExtension(), HStoreExtension(), TrigramExtension(), UnaccentExtension(), ]
45c2bdef324266b10f5c7ee5b1c27b4d54f62513d4ab6aee6a4eb0c87ffd2ceb
from django.core.serializers.json import DjangoJSONEncoder from django.db import migrations, models from ..fields import ( ArrayField, BigIntegerRangeField, CICharField, CIEmailField, 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)), ('array_field', ArrayField(HStoreField(), 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='CITestModel', fields=[ ('name', CICharField(primary_key=True, max_length=255)), ('email', CIEmailField()), ('description', CITextField()), ('array_field', ArrayField(CITextField(), null=True)), ], 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.BooleanField(null=True)), ('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='UUIDTestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('uuid', models.UUIDField(default=None, null=True)), ] ), 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_vendor': 'postgresql', }, bases=(models.Model,), ), ]
6cbec5cb95b56498d8d21dc29fe22552aff0c7670d83a73bfb9801092516f1a1
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, ), ]
05ee87bbec16196ec77592bd3066f879c20be24565a33b4080e47dfbae0856a3
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,), ), ]
ae8ddcc2930797517f37ff3847a91b27aa786e246ff859bab3afe554e099ba00
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,), ), ]
eebcad564d288ceb07b47c2f553bb907b3a70d0676e8be4acf34f3c9df9411f1
# TODO: why can't I make this ..app2 from app2.models import NiceModel class ProxyModel(NiceModel): class Meta: proxy = True
f4cd861bf57264c28ed7ad6117c77ea858635033e56a58af3c8e9dd65b90f525
from django.db import models class NiceModel(models.Model): pass
c8eec6ca1885930dd0de41d20d7b29d7ae63e45ad1e72884d3b188067a98a80b
from django.contrib.staticfiles.apps import StaticFilesConfig class IgnorePatternsAppConfig(StaticFilesConfig): ignore_patterns = ['*.css']
4c833468e4bcc51e559b911d94d47952a82ef7e9aec9ed55a889f40ff3907402
from django.conf.urls import url from django.contrib.staticfiles import views urlpatterns = [ url(r'^static/(?P<path>.*)$', views.serve), ]
91279b3f40172e23221ee7514478e0ad8ef04581699d4479ccc15e33276fce2b
from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = staticfiles_urlpatterns()
f9079544348003cbef054147de1b10898312d74ced48ee766b068ffe14b6c7e8
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) ]
8799e124403cf39bf0308d820e9085bc3a304b4abd2935871b368cb4a3bec0a4
from django.db import migrations, models class Migration(migrations.Migration): operations = [ migrations.CreateModel( 'Foo', [ ('id', models.AutoField(primary_key=True)), ], ), ]
55271b0df38f34eaf69075ee9f1bd6e1f4bd11c4f52d7531cb60efc537098245
from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ClearableFileInput, MultiWidget from .base import WidgetTest class FakeFieldFile: """ Quacks like a FieldFile (has a .url and string 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). """ class StrangeFieldFile: 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_render_as_subwidget(self): """A ClearableFileInput as a subwidget of MultiWidget.""" widget = MultiWidget(widgets=(self.widget,)) self.check_html(widget, 'myfile', [FakeFieldFile()], html=( """ Currently: <a href="something">something</a> <input type="checkbox" name="myfile_0-clear" id="myfile_0-clear_id"> <label for="myfile_0-clear_id">Clear</label><br> Change: <input type="file" name="myfile_0"> """ )) 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. """ class FailingURLFieldFile: @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): class URLFieldFile: @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): class NoURLFieldFile: 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) def test_value_omitted_from_data(self): widget = ClearableFileInput() self.assertIs(widget.value_omitted_from_data({}, {}, 'field'), True) self.assertIs(widget.value_omitted_from_data({}, {'field': 'x'}, 'field'), False) self.assertIs(widget.value_omitted_from_data({'field-clear': 'y'}, {}, 'field'), False)
f05f51b6427f7fc47eb342945598d70800cfc066ee5523ad1d6bb2e84361f631
from django.forms import Textarea from django.utils.safestring import mark_safe from .base import WidgetTest class TextareaTest(WidgetTest): widget = Textarea() def test_render(self): self.check_html(self.widget, 'msg', 'value', html=( '<textarea rows="10" cols="40" name="msg">value</textarea>' )) def test_render_required(self): widget = Textarea() widget.is_required = True self.check_html(widget, 'msg', 'value', html='<textarea rows="10" cols="40" name="msg">value</textarea>') def test_render_empty(self): self.check_html(self.widget, 'msg', '', html='<textarea rows="10" cols="40" name="msg"></textarea>') def test_render_none(self): self.check_html(self.widget, 'msg', None, html='<textarea rows="10" cols="40" name="msg"></textarea>') def test_escaping(self): self.check_html(self.widget, 'msg', 'some "quoted" & ampersanded value', html=( '<textarea rows="10" cols="40" name="msg">some &quot;quoted&quot; &amp; ampersanded value</textarea>' )) def test_mark_safe(self): self.check_html(self.widget, 'msg', mark_safe('pre &quot;quoted&quot; value'), html=( '<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value</textarea>' ))
c473ba66a94a31011a802779493e62d253f53e05047f751e8b007f51a0ceb49c
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]">', )
7129d4d8433eea61695263276b38151d5a14ec07690bdf19b50e374d2f5804a3
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">', )
13a94f9c525e4802824f20478ef552fa36c01fc6ed7fcad418e5757869ca6292
from django.forms.widgets import NumberInput from django.test import override_settings from .base import WidgetTest class NumberInputTests(WidgetTest): @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_attrs_not_localized(self): widget = NumberInput(attrs={'max': 12345, 'min': 1234, 'step': 9999}) self.check_html( widget, 'name', 'value', '<input type="number" name="name" value="value" max="12345" min="1234" step="9999">' )
f15857ae4c3ad1fff7099da1dd148e4b68966befb34dcc75441ada1985a37a49
import datetime from django import forms from django.forms import CheckboxSelectMultiple from django.test import override_settings 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, even if the choices have an empty option. """ self.check_html(self.widget(choices=(('', 'Unknown'),) + self.beatles), 'beatles', None, html=( """<ul> <li><label><input type="checkbox" name="beatles" value=""> Unknown</label></li> <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_nested_choices_without_id(self): nested_choices = ( ('unknown', 'Unknown'), ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))), ) html = """ <ul> <li> <label><input name="nestchoice" type="checkbox" value="unknown"> Unknown</label> </li> <li>Audio<ul> <li> <label> <input checked name="nestchoice" type="checkbox" value="vinyl"> Vinyl </label> </li> <li> <label><input name="nestchoice" type="checkbox" value="cd"> CD</label> </li> </ul></li> <li>Video<ul> <li> <label><input name="nestchoice" type="checkbox" value="vhs"> VHS</label> </li> <li> <label> <input checked name="nestchoice" type="checkbox" value="dvd"> DVD </label> </li> </ul></li> </ul> """ self.check_html(self.widget(choices=nested_choices), 'nestchoice', ('vinyl', 'dvd'), 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) @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_doesnt_localize_input_value(self): choices = [ (1, 'One'), (1000, 'One thousand'), (1000000, 'One million'), ] html = """ <ul> <li><label><input type="checkbox" name="numbers" value="1"> One</label></li> <li><label><input type="checkbox" name="numbers" value="1000"> One thousand</label></li> <li><label><input type="checkbox" name="numbers" value="1000000"> One million</label></li> </ul> """ self.check_html(self.widget(choices=choices), 'numbers', None, html=html) choices = [ (datetime.time(0, 0), 'midnight'), (datetime.time(12, 0), 'noon'), ] html = """ <ul> <li><label><input type="checkbox" name="times" value="00:00:00"> midnight</label></li> <li><label><input type="checkbox" name="times" value="12:00:00"> noon</label></li> </ul> """ self.check_html(self.widget(choices=choices), 'times', None, 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) def test_label(self): """" CheckboxSelectMultiple doesn't contain 'for="field_0"' in the <label> because clicking that would toggle the first checkbox. """ class TestForm(forms.Form): f = forms.MultipleChoiceField(widget=CheckboxSelectMultiple) bound_field = TestForm()['f'] self.assertEqual(bound_field.field.widget.id_for_label('id'), '') self.assertEqual(bound_field.label_tag(), '<label>F:</label>')
142e4c488f14034ff8b9429c0aa14bf05d102f55c0a0dbd3e9f58b15a87c1220
from django.forms.widgets import Input from .base import WidgetTest class InputTests(WidgetTest): def test_attrs_with_type(self): attrs = {'type': 'date'} widget = Input(attrs) self.check_html(widget, 'name', 'value', '<input type="date" name="name" value="value">') # reuse the same attrs for another widget self.check_html(Input(attrs), 'name', 'value', '<input type="date" name="name" value="value">') attrs['type'] = 'number' # shouldn't change the widget type self.check_html(widget, 'name', 'value', '<input type="date" name="name" value="value">')
4d48baebb591f1494f32be8f9635e40c30dfefa4bb696da732cc3a9f737d9487
from django.forms.renderers import DjangoTemplates, Jinja2 from django.test import SimpleTestCase try: import jinja2 except ImportError: jinja2 = None class WidgetTest(SimpleTestCase): beatles = (('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')) @classmethod def setUpClass(cls): cls.django_renderer = DjangoTemplates() cls.jinja2_renderer = Jinja2() if jinja2 else None cls.renderers = [cls.django_renderer] + ([cls.jinja2_renderer] if cls.jinja2_renderer else []) super().setUpClass() def check_html(self, widget, name, value, html='', attrs=None, strict=False, **kwargs): assertEqual = self.assertEqual if strict else self.assertHTMLEqual if self.jinja2_renderer: output = widget.render(name, value, attrs=attrs, renderer=self.jinja2_renderer, **kwargs) # Django escapes quotes with '&quot;' while Jinja2 uses '&#34;'. assertEqual(output.replace('&#34;', '&quot;'), html) output = widget.render(name, value, attrs=attrs, renderer=self.django_renderer, **kwargs) assertEqual(output, html)
5fd84f3f182840a102925c03ea717ef03ce5c6c922b99db44fbcea4ecea71fb3
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)
ebf09e39c9bcde793ee95dd1d13a64640d52a3ce00f04b201da4c950ac682eee
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">', )
5c02da9a73d60cac58dacacc9413b236fcedd8821cc8ecebc2940ac0809f8913
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_format_value(self): widget = self.widget(choices=self.numeric_choices) self.assertEqual(widget.format_value(None), []) self.assertEqual(widget.format_value(''), ['']) self.assertEqual(widget.format_value([3, 0, 1]), ['3', '0', '1']) def test_render_selected(self): self.check_html(self.widget(choices=self.beatles), 'beatles', ['J'], html=( """<select 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 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, even if the choices have an empty option. """ self.check_html(self.widget(choices=(('', 'Unknown'),) + self.beatles), 'beatles', None, html=( """<select multiple name="beatles"> <option value="">Unknown</option> <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 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 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 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 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 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 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 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>""" )) 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)
2c609f9e5574011ca7adf4d13954341f37ebb509ab94d1d6f3bb252ea0c468a0
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 selected value="">---</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 selected value="">---</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 selected value="">---</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="">---</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="">---</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="">---</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="">---</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="">---</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="">---</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 selected value="">---</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 selected value="">---</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 selected value="">---</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 selected value="">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 selected value="">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 selected value="">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 selected value="">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="">---</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="">---</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="">---</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_format_value(self): valid_formats = [ '2000-1-1', '2000-10-15', '2000-01-01', '2000-01-0', '2000-0-01', '2000-0-0', '0-01-01', '0-01-0', '0-0-01', '0-0-0', ] for value in valid_formats: year, month, day = (int(x) or '' for x in value.split('-')) with self.subTest(value=value): self.assertEqual(self.widget.format_value(value), {'day': day, 'month': month, 'year': year}) invalid_formats = [ '2000-01-001', '2000-001-01', '2-01-01', '20-01-01', '200-01-01', '20000-01-01', ] for value in invalid_formats: with self.subTest(value=value): self.assertEqual(self.widget.format_value(value), {'day': None, 'month': None, 'year': None}) def test_value_from_datadict(self): tests = [ (('2000', '12', '1'), '2000-12-1'), (('', '12', '1'), '0-12-1'), (('2000', '', '1'), '2000-0-1'), (('2000', '12', ''), '2000-12-0'), (('', '', '', ''), None), ((None, '12', '1'), None), (('2000', None, '1'), None), (('2000', '12', None), None), ] for values, expected in tests: with self.subTest(values=values): data = {} for field_name, value in zip(('year', 'month', 'day'), values): if value is not None: data['field_%s' % field_name] = value self.assertEqual(self.widget.value_from_datadict(data, {}, 'field'), expected) 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) @override_settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=True) def test_years_rendered_without_separator(self): widget = SelectDateWidget(years=(2007,)) self.check_html(widget, 'mydate', '', html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</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 selected value="">---</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 selected value="">---</option> <option value="2007">2007</option> </select> """ ))
a0475dd837da673ba46cd16b223131f4246121a8e221f3fbfe1fc7c2d3d77ebf
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_constructor_different_attrs(self): html = ( '<input type="text" class="foo" value="2006-01-10" name="date_0">' '<input type="text" class="bar" value="07:30:00" name="date_1">' ) widget = SplitDateTimeWidget(date_attrs={'class': 'foo'}, time_attrs={'class': 'bar'}) self.check_html(widget, 'date', datetime(2006, 1, 10, 7, 30), html=html) widget = SplitDateTimeWidget(date_attrs={'class': 'foo'}, attrs={'class': 'bar'}) self.check_html(widget, 'date', datetime(2006, 1, 10, 7, 30), html=html) widget = SplitDateTimeWidget(time_attrs={'class': 'bar'}, attrs={'class': 'foo'}) self.check_html(widget, 'date', datetime(2006, 1, 10, 7, 30), html=html) 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">' ))
5023d17fc79ef7be19d3da726ebe718cfc6cbc5bb38e4f8fb8adbf178e3354b3
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().__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] class ComplexField(MultiValueField): def __init__(self, required=True, widget=None, label=None, initial=None): fields = ( CharField(), MultipleChoiceField(choices=WidgetTest.beatles), SplitDateTimeField(), ) super().__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().__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_constructor_attrs_with_type(self): attrs = {'type': 'number'} widget = MyMultiWidget(widgets=(TextInput, TextInput()), attrs=attrs) self.check_html(widget, 'code', ['1', '2'], html=( '<input type="number" value="1" name="code_0">' '<input type="number" value="2" name="code_1">' )) widget = MyMultiWidget(widgets=(TextInput(attrs), TextInput(attrs)), attrs={'class': 'bar'}) self.check_html(widget, 'code', ['1', '2'], html=( '<input type="number" value="1" name="code_0" class="bar">' '<input type="number" value="2" name="code_1" class="bar">' )) 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 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_no_whitespace_between_widgets(self): widget = MyMultiWidget(widgets=(TextInput, TextInput())) self.check_html(widget, 'code', None, html=( '<input type="text" name="code_0">' '<input type="text" name="code_1">' ), strict=True) 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])
d6e55dacf4850d7321921d8bc11fc3b9e9768b264b1708deb3d16dcde650b69b
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"> """ )) def test_constructor_different_attrs(self): html = ( '<input type="hidden" class="foo" value="2006-01-10" name="date_0">' '<input type="hidden" class="bar" value="07:30:00" name="date_1">' ) widget = SplitHiddenDateTimeWidget(date_attrs={'class': 'foo'}, time_attrs={'class': 'bar'}) self.check_html(widget, 'date', datetime(2006, 1, 10, 7, 30), html=html) widget = SplitHiddenDateTimeWidget(date_attrs={'class': 'foo'}, attrs={'class': 'bar'}) self.check_html(widget, 'date', datetime(2006, 1, 10, 7, 30), html=html) widget = SplitHiddenDateTimeWidget(time_attrs={'class': 'bar'}, attrs={'class': 'foo'}) self.check_html(widget, 'date', datetime(2006, 1, 10, 7, 30), html=html)
6d2f2f317fdf42659886135913d2e4ba04d8696bee6946e75b476d709fa32f96
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)
0e16364cadb234f0e0536560ae4c7887e0bf6e3a91255639d2fc42ba9f4ff5d2
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)
8756e8d133bfdb20e477eef41e3ed207088d8c7224bb1fcc0519b8f420973663
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)
bb7ad0f68bfaf49eef26189ef5ba1da974819f2efd2822c6e3d963cff25aef55
import copy import datetime from django.forms import Select from django.test import override_settings 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>""" )) @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_doesnt_localize_option_value(self): choices = [ (1, 'One'), (1000, 'One thousand'), (1000000, 'One million'), ] html = """ <select name="number"> <option value="1">One</option> <option value="1000">One thousand</option> <option value="1000000">One million</option> </select> """ self.check_html(self.widget(choices=choices), 'number', None, html=html) choices = [ (datetime.time(0, 0), 'midnight'), (datetime.time(12, 0), 'noon'), ] html = """ <select name="time"> <option value="00:00:00">midnight</option> <option value="12:00:00">noon</option> </select> """ self.check_html(self.widget(choices=choices), 'time', None, html=html) def test_options(self): options = list(self.widget(choices=self.beatles).options( 'name', ['J'], attrs={'class': 'super'}, )) self.assertEqual(len(options), 4) self.assertEqual(options[0]['name'], 'name') self.assertEqual(options[0]['value'], 'J') self.assertEqual(options[0]['label'], 'John') self.assertEqual(options[0]['index'], '0') self.assertEqual(options[0]['selected'], True) # Template-related attributes self.assertEqual(options[1]['name'], 'name') self.assertEqual(options[1]['value'], 'P') self.assertEqual(options[1]['label'], 'Paul') self.assertEqual(options[1]['index'], '1') self.assertEqual(options[1]['selected'], False) def test_optgroups(self): choices = [ ('Audio', [ ('vinyl', 'Vinyl'), ('cd', 'CD'), ]), ('Video', [ ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ]), ('unknown', 'Unknown'), ] groups = list(self.widget(choices=choices).optgroups( 'name', ['vhs'], attrs={'class': 'super'}, )) audio, video, unknown = groups label, options, index = audio self.assertEqual(label, 'Audio') self.assertEqual( options, [{ 'value': 'vinyl', 'type': 'select', 'attrs': {}, 'index': '0_0', 'label': 'Vinyl', 'template_name': 'django/forms/widgets/select_option.html', 'name': 'name', 'selected': False, 'wrap_label': True, }, { 'value': 'cd', 'type': 'select', 'attrs': {}, 'index': '0_1', 'label': 'CD', 'template_name': 'django/forms/widgets/select_option.html', 'name': 'name', 'selected': False, 'wrap_label': True, }] ) self.assertEqual(index, 0) label, options, index = video self.assertEqual(label, 'Video') self.assertEqual( options, [{ 'value': 'vhs', 'template_name': 'django/forms/widgets/select_option.html', 'label': 'VHS Tape', 'attrs': {'selected': True}, 'index': '1_0', 'name': 'name', 'selected': True, 'type': 'select', 'wrap_label': True, }, { 'value': 'dvd', 'template_name': 'django/forms/widgets/select_option.html', 'label': 'DVD', 'attrs': {}, 'index': '1_1', 'name': 'name', 'selected': False, 'type': 'select', 'wrap_label': True, }] ) self.assertEqual(index, 1) label, options, index = unknown self.assertEqual(label, None) self.assertEqual( options, [{ 'value': 'unknown', 'selected': False, 'template_name': 'django/forms/widgets/select_option.html', 'label': 'Unknown', 'attrs': {}, 'index': '2', 'name': 'name', 'type': 'select', 'wrap_label': True, }] ) self.assertEqual(index, 2) def test_optgroups_integer_choices(self): """The option 'value' is the same type as what's in `choices`.""" groups = list(self.widget(choices=[[0, 'choice text']]).optgroups('name', ['vhs'])) label, options, index = groups[0] self.assertEqual(options[0]['value'], 0) 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) def test_doesnt_render_required_when_impossible_to_select_empty_field(self): widget = self.widget(choices=[('J', 'John'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), False) def test_renders_required_when_possible_to_select_empty_field_str(self): widget = self.widget(choices=[('', 'select please'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_renders_required_when_possible_to_select_empty_field_list(self): widget = self.widget(choices=[['', 'select please'], ['P', 'Paul']]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_renders_required_when_possible_to_select_empty_field_none(self): widget = self.widget(choices=[(None, 'select please'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_doesnt_render_required_when_no_choices_are_available(self): widget = self.widget(choices=[]) self.assertIs(widget.use_required_attribute(initial=None), False)
74092417be5a8c4714bfe549195d835d2fb706e9ca3f661e9551354aad91ebed
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): """ 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> """ ))
8cdf3a3c7b51358f37cf88453794bb98fc8762967ccccd7c831168a86eec8d52
from django.forms import Widget from django.forms.widgets import Input from .base import WidgetTest class WidgetTests(WidgetTest): def test_format_value(self): widget = Widget() self.assertIsNone(widget.format_value(None)) self.assertIsNone(widget.format_value('')) self.assertEqual(widget.format_value('español'), 'español') self.assertEqual(widget.format_value(42.5), '42.5') 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) def test_no_trailing_newline_in_attrs(self): self.check_html(Input(), 'name', 'value', strict=True, html='<input type="None" name="name" value="value">') def test_attr_false_not_rendered(self): html = '<input type="None" name="name" value="value">' self.check_html(Input(), 'name', 'value', html=html, attrs={'readonly': False})
6faf48b6d61dd4ffd3eaa15d2a443fd2f53cf7dca5a406f9b3669e1a41838528
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): """Initializing from a string 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">')
9e99e57bee7faaedae0d690f7e89665920d58e85ba6da97458aef92966236d23
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">' ), )
53d0ff73b03692feca7b295e00626389ea7ef44da09ff9ac0df140d7da3170b2
import datetime from django.forms import MultiWidget, RadioSelect from django.test import override_settings from .base import WidgetTest class RadioSelectTest(WidgetTest): widget = RadioSelect def test_render(self): choices = (('', '------'),) + self.beatles self.check_html(self.widget(choices=choices), 'beatle', 'J', html=( """<ul> <li><label><input type="radio" name="beatle" value=""> ------</label></li> <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) def test_class_attrs(self): """ The <ul> in the multiple_input.html widget template include the class attribute. """ html = """ <ul class="bar"> <li><label><input checked type="radio" class="bar" value="J" name="beatle"> John</label></li> <li><label><input type="radio" class="bar" value="P" name="beatle"> Paul</label></li> <li><label><input type="radio" class="bar" value="G" name="beatle"> George</label></li> <li><label><input type="radio" class="bar" value="R" name="beatle"> Ringo</label></li> </ul> """ self.check_html(self.widget(choices=self.beatles), 'beatle', 'J', attrs={'class': 'bar'}, html=html) @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_doesnt_localize_input_value(self): choices = [ (1, 'One'), (1000, 'One thousand'), (1000000, 'One million'), ] html = """ <ul> <li><label><input type="radio" name="number" value="1"> One</label></li> <li><label><input type="radio" name="number" value="1000"> One thousand</label></li> <li><label><input type="radio" name="number" value="1000000"> One million</label></li> </ul> """ self.check_html(self.widget(choices=choices), 'number', None, html=html) choices = [ (datetime.time(0, 0), 'midnight'), (datetime.time(12, 0), 'noon'), ] html = """ <ul> <li><label><input type="radio" name="time" value="00:00:00"> midnight</label></li> <li><label><input type="radio" name="time" value="12:00:00"> noon</label></li> </ul> """ self.check_html(self.widget(choices=choices), 'time', None, html=html) def test_render_as_subwidget(self): """A RadioSelect as a subwidget of MultiWidget.""" choices = (('', '------'),) + self.beatles self.check_html(MultiWidget([self.widget(choices=choices)]), 'beatle', ['J'], html=( """<ul> <li><label><input type="radio" name="beatle_0" value=""> ------</label></li> <li><label><input checked type="radio" name="beatle_0" value="J"> John</label></li> <li><label><input type="radio" name="beatle_0" value="P"> Paul</label></li> <li><label><input type="radio" name="beatle_0" value="G"> George</label></li> <li><label><input type="radio" name="beatle_0" value="R"> Ringo</label></li> </ul>""" ))
f1422fb5cd864b4c80560bbbf7aa94c9f8d7fc36c5d7c07bcead780855a334e3
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)
e0424b15a8150a78d89dddd9a0f4815cd6f7bc986acae0bf65150a504f9c4de6
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': ['Voer een geldige datum in.']}) @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)
648126a9b6e82a8b200ca3d9a9f7e8e03ca2bd5d344e5cf8d6de309f4c39f1c7
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'))
9f90c949ce117fe4abe887863a0fbd033262a48b393289da4c3825d7f34ad78d
import datetime from django.core.exceptions import ValidationError 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_overflow(self): msg = "The number of days must be between {min_days} and {max_days}.".format( min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days, ) f = DurationField() with self.assertRaisesMessage(ValidationError, msg): f.clean('1000000000 00:00:00') with self.assertRaisesMessage(ValidationError, msg): f.clean('-1000000000 00:00:00') 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))
37e0c6361a7e69fb302f95662fdb5e751dd8ccdea6bbfc47d94bfc791b96d1ba
import datetime from django.forms import SplitDateTimeField, ValidationError from django.forms.widgets import SplitDateTimeWidget from django.test import SimpleTestCase 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 self.assertRaisesMessage(ValidationError, "'Enter a valid date.', '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 self.assertRaisesMessage(ValidationError, "'Enter a valid date.', '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']))
b1f2f9e059a7dfe5af849f788417be620103f8b188bdb7379ebb5031528a7a9d
from django import forms class FormFieldAssertionsMixin: def assertWidgetRendersTo(self, field, to): class Form(forms.Form): f = field self.assertHTMLEqual(str(Form()['f']), to)
df95c2302ad1ccd2bb88e6b57689e23eab8a10ab69208bdb5a57fad9c67bfa79
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())), 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_disabled_has_changed(self): f = FileField(disabled=True) self.assertIs(f.has_changed('x', 'y'), False) def test_file_picklable(self): self.assertIsInstance(pickle.loads(pickle.dumps(FileField())), FileField)
07f39952c0941b9a6a23353560e61764550f2ce0bc4bad0ec673dccd5a7120f9
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.assertRaisesMessage(ValidationError, 'Enter a valid UUID.'): field.clean('550e8400') def test_uuidfield_4(self): field = UUIDField() value = field.prepare_value(uuid.UUID('550e8400e29b41d4a716446655440000')) self.assertEqual(value, '550e8400e29b41d4a716446655440000')
1896980309b4d791341783857f150bc73faa1e6fa9879758d0cffe90af6a4f62
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: def __init__(self): self.class_a_var = True super().__init__() class ComplexField(Field, A): def __init__(self): super().__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')]) class DisabledFieldTests(SimpleTestCase): def test_disabled_field_has_changed_always_false(self): disabled_field = Field(disabled=True) self.assertFalse(disabled_field.has_changed('x', 'y'))
630b8f6195127048ef3a4efb55f671d4dd804baac8ba5b01475c0550a5c4a948
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().__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] class ComplexField(MultiValueField): def __init__(self, **kwargs): fields = ( CharField(), MultipleChoiceField(choices=beatles), SplitDateTimeField(), ) super().__init__(fields, **kwargs) 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().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_clean_disabled_multivalue(self): class ComplexFieldForm(Form): f = ComplexField(disabled=True, widget=ComplexMultiWidget) inputs = ( 'some text,JP,2007-04-25 06:24:00', ['some text', ['J', 'P'], ['2007-04-25', '6:24:00']], ) for data in inputs: with self.subTest(data=data): form = ComplexFieldForm({}, initial={'f': data}) form.full_clean() self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {'f': inputs[0]}) 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_disabled_has_changed(self): f = MultiValueField(fields=(CharField(), CharField()), disabled=True) self.assertIs(f.has_changed(['x', 'x'], ['y', 'y']), False) 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 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 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')
79f8437f508af10f7f58b154badd329211bb95db25b5b1e26731c7c38caa5dd9
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'])
a4ba00ec1a3e7e1518cb100337596d967fef997546593995e1deba36dfda369d
from django.forms import ChoiceField, Form, ValidationError from django.test import SimpleTestCase 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_choices_default(self): f = ChoiceField() self.assertEqual(f.choices, []) 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><option value="J">John</option>' '<option value="P">Paul</option></select>' )
ac12de6be9ecb77e46a6be60f245355ae1e843ebab1ee49bfed21d3b04739b4d
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: with self.subTest(url=url): # 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: with self.subTest(url=url): 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)
327b29caa4a0dda1665e2c26f26d417b6afa974df076214049b21042003e86fb
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'])) def test_disabled_has_changed(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], disabled=True) self.assertIs(f.has_changed('x', 'y'), False)
65b91ad52dc49346320b4e8d7f3e71d5cd00d229f0d7ccc43811b3602eedba2e
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))
be07710b900fac6d1d3a647d85a246dd4a51b711492ee7743b28b8cdb0694566
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)
56f41c95fbc5e3c05bd35c4230e026915dc6ef128b571ab5137368c7fa8f5cf3
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'))
8ee3258206a246b227ad8c1354940c498ecb322abff6779b688c5c2d91560424
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'))
8e93b3c8129ae402824d8e3903bc00fd6c096f768b4a06a6b758e0fbdb172087
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')
406efd2ab4a3c7850e7b30fa16b74f2f0cbedb32ac621c65659e8427d326c740
import decimal from django.forms import DecimalField, NumberInput, ValidationError, Widget from django.test import SimpleTestCase, override_settings 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")) 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, "'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') self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_enter_a_number_error(self): f = DecimalField(max_digits=4, decimal_places=2) values = ( '-NaN', 'NaN', '+NaN', '-sNaN', 'sNaN', '+sNaN', '-Inf', 'Inf', '+Inf', '-Infinity', 'Infinity', '+Infinity', 'a', 'łąść', '1.0a', '--0.12', ) for value in values: with self.subTest(value=value), self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean(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=4, decimal_places=2) with self.assertRaisesMessage(ValidationError, "Ensure that there are no more"): f.clean('1E+2') self.assertEqual(f.clean('1E+1'), decimal.Decimal('10')) self.assertEqual(f.clean('1E-1'), decimal.Decimal('0.1')) self.assertEqual(f.clean('0.546e+2'), decimal.Decimal('54.6')) 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)) @override_settings(USE_L10N=False, DECIMAL_SEPARATOR=',') def test_decimalfield_support_decimal_separator(self): f = DecimalField(localize=True) self.assertEqual(f.clean('1001,10'), decimal.Decimal("1001.10")) self.assertEqual(f.clean('1001.10'), decimal.Decimal("1001.10")) @override_settings(USE_L10N=False, DECIMAL_SEPARATOR=',', USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR='.') def test_decimalfield_support_thousands_separator(self): f = DecimalField(localize=True) self.assertEqual(f.clean('1.001,10'), decimal.Decimal("1001.10")) msg = "'Enter a number.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('1,001.1')
56adbe29227383e95b73aa6333417a040116b3d5e915ad31aab08d2a446d43bf
import os import unittest from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ( ClearableFileInput, FileInput, ImageField, ValidationError, Widget, ) from django.test import SimpleTestCase from . import FormFieldAssertionsMixin try: from PIL import Image except ImportError: Image = None def get_img_path(path): return os.path.join(os.path.abspath(os.path.join(__file__, '..', '..')), 'tests', path) @unittest.skipUnless(Image, "Pillow is required to test ImageField") class ImageFieldTest(FormFieldAssertionsMixin, 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') def test_file_extension_validation(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.txt', img_data) with self.assertRaisesMessage(ValidationError, "File extension 'txt' is not allowed."): f.clean(img_file) def test_widget_attrs_default_accept(self): f = ImageField() # Nothing added for non-FileInput widgets. self.assertEqual(f.widget_attrs(Widget()), {}) self.assertEqual(f.widget_attrs(FileInput()), {'accept': 'image/*'}) self.assertEqual(f.widget_attrs(ClearableFileInput()), {'accept': 'image/*'}) self.assertWidgetRendersTo(f, '<input type="file" name="f" accept="image/*" required id="id_f" />') def test_widge_attrs_accept_specified(self): f = ImageField(widget=FileInput(attrs={'accept': 'image/png'})) self.assertEqual(f.widget_attrs(f.widget), {}) self.assertWidgetRendersTo(f, '<input type="file" name="f" accept="image/png" required id="id_f" />') def test_widge_attrs_accept_false(self): f = ImageField(widget=FileInput(attrs={'accept': False})) self.assertEqual(f.widget_attrs(f.widget), {}) self.assertWidgetRendersTo(f, '<input type="file" name="f" required id="id_f" />')
e897b061e3594b0a59af8dbcabfce992143c4f1b656017b9788831495d0e9fe2
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')) def test_disabled_has_changed(self): f = BooleanField(disabled=True) self.assertIs(f.has_changed('True', 'False'), False)
5e552866ad15eccb4cc97a6e6dd577750135f907496d45b3357d4d82ad5a5234
import decimal from django.forms import TypedChoiceField, ValidationError from django.test import SimpleTestCase 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=str, 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')
89959ff1d8c8c76c0b34077cdb1029f16a9582d3accedf343c148d8a5a0efd76
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') msg = '__init__() takes 1 positional argument but 2 were given' with self.assertRaisesMessage(TypeError, msg): 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_strip_before_checking_empty(self): """ A whitespace-only value, ' ', is stripped to an empty string and then converted to the empty value, None. """ f = CharField(required=False, empty_value=None) self.assertIsNone(f.clean(' ')) def test_clean_non_string(self): """CharField.clean() calls str(value) before stripping it.""" class StringWrapper: def __init__(self, v): self.v = v def __str__(self): return self.v value = StringWrapper(' ') f1 = CharField(required=False, empty_value=None) self.assertIsNone(f1.clean(value)) f2 = CharField(strip=False) self.assertEqual(f2.clean(value), ' ') def test_charfield_disabled(self): f = CharField(disabled=True) self.assertWidgetRendersTo(f, '<input type="text" name="f" id="id_f" disabled required>') def test_null_characters_prohibited(self): f = CharField() msg = 'Null characters are not allowed.' with self.assertRaisesMessage(ValidationError, msg): f.clean('\x00something')
c80ba20477a3fa83b1e85174ac95806b8695d30d39b572569c4b9c29c1db294c
import re from django.forms import RegexField, ValidationError from django.test import SimpleTestCase 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') with self.assertRaisesMessage( ValidationError, "'Ensure this value has at least 5 characters (it has 3).', " "'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')
060efcbfdff40f9df4f6fe72a15e3f2bde91f1f2450b21a896acc1621310322a
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')
04a7ff605e4c033246ab120c614d124b335b016b9df911b608af8a8eae9133c8
from django.forms import FloatField, NumberInput, ValidationError from django.test import SimpleTestCase from django.test.utils import override_settings 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)) @override_settings(USE_L10N=False, DECIMAL_SEPARATOR=',') def test_decimalfield_support_decimal_separator(self): f = FloatField(localize=True) self.assertEqual(f.clean('1001,10'), 1001.10) self.assertEqual(f.clean('1001.10'), 1001.10) @override_settings(USE_L10N=False, DECIMAL_SEPARATOR=',', USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR='.') def test_decimalfield_support_thousands_separator(self): f = FloatField(localize=True) self.assertEqual(f.clean('1.001,10'), 1001.10) msg = "'Enter a number.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('1,001.1')
22625b57e9fa0e1152fd1ac2ada1a9c08bd0443a2e0b30c42d09948268cb406c
import os.path from django.forms import FilePathField, ValidationError from django.test import SimpleTestCase PATH = os.path.dirname(os.path.abspath(__file__)) def fix_os_paths(x): if isinstance(x, str): if x.startswith(PATH): x = x[len(PATH):] 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): expected_choices = [ ('/filepathfield_test_dir/__init__.py', '__init__.py'), ('/filepathfield_test_dir/a.py', 'a.py'), ('/filepathfield_test_dir/ab.py', 'ab.py'), ('/filepathfield_test_dir/b.py', 'b.py'), ('/filepathfield_test_dir/c/__init__.py', '__init__.py'), ('/filepathfield_test_dir/c/d.py', 'd.py'), ('/filepathfield_test_dir/c/e.py', 'e.py'), ('/filepathfield_test_dir/c/f/__init__.py', '__init__.py'), ('/filepathfield_test_dir/c/f/g.py', 'g.py'), ('/filepathfield_test_dir/h/__init__.py', '__init__.py'), ('/filepathfield_test_dir/j/__init__.py', '__init__.py'), ] path = os.path.join(PATH, 'filepathfield_test_dir') + '/' def assertChoices(self, field, expected_choices): self.assertEqual(fix_os_paths(field.choices), expected_choices) def test_fix_os_paths(self): self.assertEqual(fix_os_paths(self.path), ('/filepathfield_test_dir/')) def test_no_options(self): f = FilePathField(path=self.path) expected = [ ('/filepathfield_test_dir/README', 'README'), ] + self.expected_choices[:4] self.assertChoices(f, expected) def test_clean(self): f = FilePathField(path=self.path) msg = "'Select a valid choice. a.py is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('a.py') self.assertEqual(fix_os_paths(f.clean(self.path + 'a.py')), '/filepathfield_test_dir/a.py') def test_match(self): f = FilePathField(path=self.path, match=r'^.*?\.py$') self.assertChoices(f, self.expected_choices[:4]) def test_recursive(self): f = FilePathField(path=self.path, recursive=True, match=r'^.*?\.py$') expected = [ ('/filepathfield_test_dir/__init__.py', '__init__.py'), ('/filepathfield_test_dir/a.py', 'a.py'), ('/filepathfield_test_dir/ab.py', 'ab.py'), ('/filepathfield_test_dir/b.py', 'b.py'), ('/filepathfield_test_dir/c/__init__.py', 'c/__init__.py'), ('/filepathfield_test_dir/c/d.py', 'c/d.py'), ('/filepathfield_test_dir/c/e.py', 'c/e.py'), ('/filepathfield_test_dir/c/f/__init__.py', 'c/f/__init__.py'), ('/filepathfield_test_dir/c/f/g.py', 'c/f/g.py'), ('/filepathfield_test_dir/h/__init__.py', 'h/__init__.py'), ('/filepathfield_test_dir/j/__init__.py', 'j/__init__.py'), ] self.assertChoices(f, expected) def test_allow_folders(self): f = FilePathField(path=self.path, allow_folders=True, allow_files=False) self.assertChoices(f, [ ('/filepathfield_test_dir/c', 'c'), ('/filepathfield_test_dir/h', 'h'), ('/filepathfield_test_dir/j', 'j'), ]) def test_recursive_no_folders_or_files(self): f = FilePathField(path=self.path, recursive=True, allow_folders=False, allow_files=False) self.assertChoices(f, []) def test_recursive_folders_without_files(self): f = FilePathField(path=self.path, recursive=True, allow_folders=True, allow_files=False) self.assertChoices(f, [ ('/filepathfield_test_dir/c', 'c'), ('/filepathfield_test_dir/h', 'h'), ('/filepathfield_test_dir/j', 'j'), ('/filepathfield_test_dir/c/f', 'c/f'), ])
a26df3d95a2154ec1ebb106f23970889907137bb0dd67e5cc378f8ddbfa6f894
import datetime from collections import Counter from unittest import mock from django.forms import ( BaseForm, CharField, DateField, FileField, Form, IntegerField, SplitDateTimeField, ValidationError, formsets, ) from django.forms.formsets import BaseFormSet, all_valid, formset_factory from django.forms.utils import ErrorList from django.test import SimpleTestCase class Choice(Form): choice = CharField() votes = IntegerField() 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']) # A FormSet that takes a list of favorite drinks and raises an error if # there are any duplicates. FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3) class CustomKwargForm(Form): def __init__(self, *args, custom_kwarg, **kwargs): self.custom_kwarg = custom_kwarg super().__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. Create a FormSet for adding data. By default, it displays 1 blank form. """ 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>""" ) # FormSet are treated similarly to Forms. 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, cleaned_data # and errors will be a list of dicts rather than 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 wasn't passed any data, is_valid() and has_changed() # return False. formset = self.make_choiceformset() self.assertFalse(formset.is_valid()) self.assertFalse(formset.has_changed()) def test_form_kwargs_formset(self): """ 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): """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_validation_count(self): """ A formset's ManagementForm is validated once per FormSet.is_valid() call and each form of the formset is cleaned once. """ def make_method_counter(func): """Add a counter to func for the number of times it's called.""" counter = Counter() counter.call_count = 0 def mocked_func(*args, **kwargs): counter.call_count += 1 return func(*args, **kwargs) return mocked_func, counter mocked_is_valid, is_valid_counter = make_method_counter(formsets.ManagementForm.is_valid) mocked_full_clean, full_clean_counter = make_method_counter(BaseForm.full_clean) formset = self.make_choiceformset([('Calexico', '100'), ('Any1', '42'), ('Any2', '101')]) with mock.patch('django.forms.formsets.ManagementForm.is_valid', mocked_is_valid), \ mock.patch('django.forms.forms.BaseForm.full_clean', mocked_full_clean): self.assertTrue(formset.is_valid()) self.assertEqual(is_valid_counter.call_count, 1) self.assertEqual(full_clean_counter.call_count, 4) def test_formset_has_changed(self): """ FormSet.has_changed() is True if any data is passed to its forms, even if the formset didn't validate. """ blank_formset = self.make_choiceformset([('', '')]) self.assertFalse(blank_formset.has_changed()) # invalid formset invalid_formset = self.make_choiceformset([('Calexico', '')]) self.assertFalse(invalid_formset.is_valid()) self.assertTrue(invalid_formset.has_changed()) # valid formset 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): """ A FormSet can be prefilled with existing data by providing a list of dicts to the `initial` argument. 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>""" ) def test_blank_form_unfilled(self): """A form that's displayed as blank may be submitted as blank.""" 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): """ If at least one field is filled out on a blank form, it will be validated. """ 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): """ Deleting prefilled data is an error. Removing data from form fields isn't the proper way to delete it. """ 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): """ More than 1 empty form can be displayed using formset_factory's `extra` argument. """ 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 every form was displayed as blank, they are also accepted as # blank. This may seem a little strange, but min_num is used 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): """" More than 1 empty form can also be displayed using formset_factory's min_num argument. 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): """More than 1 empty form can be displayed using min_num.""" 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): """Just one form may 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': '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, a ValidationError is raised. 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, a ValidationError is raised. 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_unchanged_forms(self): """ min_num validation doesn't consider unchanged forms with initial data as "empty". """ initial = [ {'choice': 'Zero', 'votes': 0}, {'choice': 'One', 'votes': 0}, ] data = { 'choices-TOTAL_FORMS': '2', 'choices-INITIAL_FORMS': '2', 'choices-MIN_NUM_FORMS': '0', 'choices-MAX_NUM_FORMS': '2', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', # changed from initial } ChoiceFormSet = formset_factory(Choice, min_num=2, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices', initial=initial) self.assertFalse(formset.forms[0].has_changed()) self.assertTrue(formset.forms[1].has_changed()) self.assertTrue(formset.is_valid()) 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): """A partially completed form is invalid.""" 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 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>""" ) # Retrieving an empty form works. Tt 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): """ formset_factory's can_delete argument adds a boolean "delete" field to each form. 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, 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'}] ) def test_formset_with_deletion_remove_deletion_flag(self): """ If a form is filled with something and can_delete is also checked, that form's errors shouldn't 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 the deletion flag is removed, validation is enabled. data['check-1-DELETE'] = '' formset = CheckFormSet(data, prefix='check') self.assertFalse(formset.is_valid()) def test_formset_with_deletion_invalid_deleted_form(self): """ deleted_forms works on 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(p._errors, []) self.assertEqual(len(p.deleted_forms), 1) def test_formsets_with_ordering(self): """ formset_factory's can_order argument adds an integer field to each form. 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 its 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. If they are left blank, they'll 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 works 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.""" 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): """ Can 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): """ FormSets have a clean() hook for doing extra validation that isn't tied to any form. It follows the same pattern as the clean() hook on Forms. """ # 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.') # The valid case still works. 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 with 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), "") def test_limited_max_forms_two(self): 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>""" ) def test_limiting_extra_lest_than_max_num(self): """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. """ 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), "") def test_max_num_zero_with_initial(self): # 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 results in all initial forms being displayed (but no extra forms). """ 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>""" ) def test_more_initial_form_result_in_one(self): """ One form from initial and extra=3 with max_num=2 results 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_management_form_prefix(self): """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_non_form_errors(self): 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): """Formset instances are iterable.""" ChoiceFormset = formset_factory(Choice, extra=3) formset = ChoiceFormset() # An iterated formset yields formset.forms. forms = list(formset) self.assertEqual(forms, formset.forms) self.assertEqual(len(formset), len(forms)) # A formset may be indexed to retrieve its forms. 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().__getitem__(len(self) - idx - 1) ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3) reverse_formset = ReverseChoiceFormset() # __iter__() modifies the 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): """A formsets without any forms evaluates as True.""" ChoiceFormset = formset_factory(Choice, extra=0) formset = ChoiceFormset() self.assertEqual(len(formset.forms), 0) self.assertTrue(formset) def test_formset_splitdatetimefield(self): """ Formset works with SplitDateTimeField(initial=datetime.datetime.now). """ class SplitDateTimeForm(Form): when = SplitDateTimeField(initial=datetime.datetime.now) SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) 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): """Formset's forms use the formset's 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): """Formsets call is_valid() on each form.""" class AnotherChoice(Choice): def is_valid(self): self.is_valid_called = True return super().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): """ 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(str(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>""" ) class ArticleForm(Form): title = CharField() pub_date = DateField() ArticleFormSet = formset_factory(ArticleForm) class TestIsBoundBehavior(SimpleTestCase): def test_no_data_raises_validation_error(self): msg = 'ManagementForm data is missing or has been tampered with' with self.assertRaisesMessage(ValidationError, msg): 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): """An empty formset still calls clean()""" class EmptyFsetWontValidate(BaseFormSet): def clean(self): raise ValidationError('Clean method called') 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): """Media is available on empty formset.""" 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): """is_multipart() works with an empty formset.""" class FileForm(Form): file = FileField() self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart()) class AllValidTests(SimpleTestCase): def test_valid(self): data = { 'choices-TOTAL_FORMS': '2', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', } ChoiceFormSet = formset_factory(Choice) formset1 = ChoiceFormSet(data, auto_id=False, prefix='choices') formset2 = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertIs(all_valid((formset1, formset2)), True) expected_errors = [{}, {}] self.assertEqual(formset1._errors, expected_errors) self.assertEqual(formset2._errors, expected_errors) def test_invalid(self): """all_valid() validates all forms, even when some are invalid.""" data = { 'choices-TOTAL_FORMS': '2', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', 'choices-0-choice': 'Zero', 'choices-0-votes': '', 'choices-1-choice': 'One', 'choices-1-votes': '', } ChoiceFormSet = formset_factory(Choice) formset1 = ChoiceFormSet(data, auto_id=False, prefix='choices') formset2 = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertIs(all_valid((formset1, formset2)), False) expected_errors = [{'votes': ['This field is required.']}, {'votes': ['This field is required.']}] self.assertEqual(formset1._errors, expected_errors) self.assertEqual(formset2._errors, expected_errors)
ae276ec1db19405f5c249ac01fd2d64226a6859e96cb01b61b6dc8895e7f99bf
import copy from django.core.exceptions import ValidationError from django.forms.utils import ErrorDict, ErrorList, flatatt from django.test import SimpleTestCase from django.utils.safestring import mark_safe from django.utils.translation import gettext_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({'class': None}), '') self.assertEqual(flatatt({}), '') def test_flatatt_no_side_effects(self): """ 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( str(ErrorList(ValidationError("Not \u03C0.").messages)), '<ul class="errorlist"><li>Not π.</li></ul>' ) # Can take a lazy string. self.assertHTMLEqual( str(ErrorList(ValidationError(gettext_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.", gettext_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>' ) 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(str(e), e.__html__()) def test_error_list_html_safe(self): e = ErrorList(['Invalid username.']) self.assertTrue(hasattr(ErrorList, '__html__')) self.assertEqual(str(e), e.__html__())
1200a30b9de95f5bff9b1d36d4e2d942fb31e9afe57cccf72237df73e5e130eb
import datetime from django.core.files.uploadedfile import SimpleUploadedFile from django.db import models from django.forms import CharField, FileField, Form, ModelForm from django.forms.models import ModelFormMetaclass from django.test import SimpleTestCase, TestCase from ..models import ( BoundaryModel, ChoiceFieldModel, ChoiceModel, ChoiceOptionModel, Defaults, FileModel, 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 TestTicket14567(TestCase): """ 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()) # 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, str(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"> <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"> <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 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 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"> <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"> <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 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 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()) 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__' msg = ( "Cannot create form field for 'ref' yet, because " "its related model 'B' has not been loaded yet" ) with self.assertRaisesMessage(ValueError, msg): ModelFormMetaclass('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('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): # 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: with self.subTest(form=form): 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>""" )
217db0536c64fac1de8de7467fb5dff8dbf750f57dc42991097e60a09eb5802c
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.safestring import mark_safe from ..models import ChoiceModel class AssertFormErrorsMixin: 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.") 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.</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'])
205b59476a83bc0d24221b0b068b2adcb529476f6c38496c19e6c7008aa3c2d3
import os import unittest from django.forms.renderers import ( BaseRenderer, DjangoTemplates, Jinja2, TemplatesSetting, ) from django.test import SimpleTestCase try: import jinja2 except ImportError: jinja2 = None class SharedTests: expected_widget_dir = 'templates' def test_installed_apps_template_found(self): """Can find a custom template in INSTALLED_APPS.""" renderer = self.renderer() # Found because forms_tests is . tpl = renderer.get_template('forms_tests/custom_widget.html') expected_path = os.path.abspath( os.path.join( os.path.dirname(__file__), '..', self.expected_widget_dir + '/forms_tests/custom_widget.html', ) ) self.assertEqual(tpl.origin.name, expected_path) class BaseTemplateRendererTests(SimpleTestCase): def test_get_renderer(self): with self.assertRaisesMessage(NotImplementedError, 'subclasses must implement get_template()'): BaseRenderer().get_template('') class DjangoTemplatesTests(SharedTests, SimpleTestCase): renderer = DjangoTemplates @unittest.skipIf(jinja2 is None, 'jinja2 required') class Jinja2Tests(SharedTests, SimpleTestCase): renderer = Jinja2 expected_widget_dir = 'jinja2' class TemplatesSettingTests(SharedTests, SimpleTestCase): renderer = TemplatesSetting
a186fcf735c18d6c7305347ddacc6472769f040ba5745411e22ffb2f97f4d38f
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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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)) # 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")
cf531acda19b5c89536bbb7f6a718ab9082c5747b53500c676f9ce415d0666c6
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 class FormsI18nTests(SimpleTestCase): def test_lazy_labels(self): class SomeForm(Form): username = CharField(max_length=10, label=gettext_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=gettext_lazy('field_1')) field_2 = CharField( max_length=10, label=gettext_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()
a1128cf547be4402f3d307e5758ce9ccaf4f8f82bf940cae8f1e7e9aaf0f2827
from django.contrib.admin.tests import AdminSeleniumTestCase from django.test import override_settings from django.urls import reverse from ..models import Article @override_settings(ROOT_URLCONF='forms_tests.urls') class LiveWidgetTests(AdminSeleniumTestCase): available_apps = ['forms_tests'] + AdminSeleniumTestCase.available_apps def test_textarea_trailing_newlines(self): """ A roundtrip on a ModelForm doesn't alter the TextField value """ article = Article.objects.create(content="\nTst\n") self.selenium.get(self.live_server_url + reverse('article_form', args=[article.pk])) self.selenium.find_element_by_id('submit').submit() article = Article.objects.get(pk=article.pk) self.assertEqual(article.content, "\r\nTst\r\n")
7e0a1a9af6befaa8c17bb9f0324f03fff5f074d6decaa2d0b008325cbcf56268
from django.forms import CharField, Form, Media, MultiWidget, TextInput from django.template import Context, Template from django.test import SimpleTestCase, override_settings @override_settings( STATIC_URL='http://media.example.com/static/', ) class FormsMediaTestCase(SimpleTestCase): """Tests for the media handling on widgets and forms""" def test_construction(self): # Check construction of media objects m = Media( css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'), ) self.assertEqual( str(m), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) self.assertEqual( repr(m), "Media(css={'all': ('path/to/css1', '/path/to/css2')}, " "js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'))" ) class Foo: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') m3 = Media(Foo) self.assertEqual( str(m3), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # A widget can exist without a media definition class MyWidget(TextInput): pass w = MyWidget() self.assertEqual(str(w.media), '') def test_media_dsl(self): ############################################################### # DSL Class-based media definitions ############################################################### # A widget can define media if it needs to. # Any absolute path will be preserved; relative paths are combined # with the value of settings.MEDIA_URL class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') w1 = MyWidget1() self.assertEqual( str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # Media objects can be interrogated by media type self.assertEqual( str(w1.media['css']), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">""" ) self.assertEqual( str(w1.media['js']), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) def test_combine_media(self): # Media objects can be combined. Any given media resource will appear only # once. Duplicated media definitions are ignored. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') w1 = MyWidget1() w2 = MyWidget2() w3 = MyWidget3() self.assertEqual( str(w1.media + w2.media + w3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""" ) # media addition hasn't affected the original objects self.assertEqual( str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # Regression check for #12879: specifying the same CSS or JS file # multiple times in a single Media instance should result in that file # only being included once. class MyWidget4(TextInput): class Media: css = {'all': ('/path/to/css1', '/path/to/css1')} js = ('/path/to/js1', '/path/to/js1') w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script>""") def test_media_property(self): ############################################################### # Property-based media definitions ############################################################### # Widget media can be defined as a property class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js=('/some/js',)) media = property(_media) w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/some/js"></script>""") # Media properties can reference the media of their parents class MyWidget5(MyWidget4): def _media(self): return super().media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) media = property(_media) w5 = MyWidget5() self.assertEqual(str(w5.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet"> <link href="/other/path" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_property_parent_references(self): # Media properties can reference the media of their parents, # even if the parent media was defined using a class class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget6(MyWidget1): def _media(self): return super().media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) media = property(_media) w6 = MyWidget6() self.assertEqual( str(w6.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/other/path" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/other/js"></script>""" ) def test_media_inheritance(self): ############################################################### # Inheritance of media ############################################################### # If a widget extends another but provides no media definition, it inherits the parent widget's media class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget7(MyWidget1): pass w7 = MyWidget7() self.assertEqual( str(w7.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # If a widget extends another but defines media, it extends the parent widget's media by default class MyWidget8(MyWidget1): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w8 = MyWidget8() self.assertEqual( str(w8.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""" ) def test_media_inheritance_from_property(self): # If a widget extends another but defines media, it extends the parents widget's media, # even if the parent defined media using a property. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js=('/some/js',)) media = property(_media) class MyWidget9(MyWidget4): class Media: css = { 'all': ('/other/path',) } js = ('/other/js',) w9 = MyWidget9() self.assertEqual( str(w9.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet"> <link href="/other/path" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""" ) # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): class Media: extend = False css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w10 = MyWidget10() self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_extends(self): # A widget can explicitly enable full media inheritance by specifying 'extend=True' class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget11(MyWidget1): class Media: extend = True css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w11 = MyWidget11() self.assertEqual( str(w11.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""" ) def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying extend as a tuple class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget12(MyWidget1): class Media: extend = ('css',) css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w12 = MyWidget12() self.assertEqual( str(w12.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""" ) def test_multi_media(self): ############################################################### # Multi-media handling for CSS ############################################################### # A widget can define CSS media for multiple output media types class MultimediaWidget(TextInput): class Media: css = { 'screen, print': ('/file1', '/file2'), 'screen': ('/file3',), 'print': ('/file4',) } js = ('/path/to/js1', '/path/to/js4') multimedia = MultimediaWidget() self.assertEqual( str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet"> <link href="/file3" type="text/css" media="screen" rel="stylesheet"> <link href="/file1" type="text/css" media="screen, print" rel="stylesheet"> <link href="/file2" type="text/css" media="screen, print" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""" ) def test_multi_widget(self): ############################################################### # Multiwidget media handling ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') # MultiWidgets have a default media definition that gets all the # media from the component widgets class MyMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = [MyWidget1, MyWidget2, MyWidget3] super().__init__(widgets, attrs) mymulti = MyMultiWidget() self.assertEqual( str(mymulti.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""" ) def test_form_media(self): ############################################################### # Media processing for forms ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') # You can ask a form for the media required by its widgets. class MyForm(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) f1 = MyForm() self.assertEqual( str(f1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""" ) # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) f2 = AnotherForm() self.assertEqual( str(f1.media + f2.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""" ) # Forms can also define media, following the same rules as widgets. class FormWithMedia(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) class Media: js = ('/some/form/javascript',) css = { 'all': ('/some/form/css',) } f3 = FormWithMedia() self.assertEqual( str(f3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script>""" ) # Media works in templates self.assertEqual( Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script>""" """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet">""" ) def test_html_safe(self): media = Media(css={'all': ['/path/to/css']}, js=['/path/to/js']) self.assertTrue(hasattr(Media, '__html__')) self.assertEqual(str(media), media.__html__()) def test_merge(self): test_values = ( (([1, 2], [3, 4]), [1, 2, 3, 4]), (([1, 2], [2, 3]), [1, 2, 3]), (([2, 3], [1, 2]), [1, 2, 3]), (([1, 3], [2, 3]), [1, 2, 3]), (([1, 2], [1, 3]), [1, 2, 3]), (([1, 2], [3, 2]), [1, 3, 2]), ) for (list1, list2), expected in test_values: with self.subTest(list1=list1, list2=list2): self.assertEqual(Media.merge(list1, list2), expected) def test_merge_warning(self): msg = 'Detected duplicate Media files in an opposite order:\n1\n2' with self.assertWarnsMessage(RuntimeWarning, msg): self.assertEqual(Media.merge([1, 2], [2, 1]), [1, 2])
5b456ffc1c2d9d9cd63c57c61a9b139dcf0296dbf2a65281ddbdecd2c94d054a
import re from unittest import TestCase from django import forms from django.core import validators from django.core.exceptions import ValidationError class TestFieldWithValidators(TestCase): def test_all_errors_get_reported(self): class UserForm(forms.Form): full_name = forms.CharField( max_length=50, validators=[ validators.validate_integer, validators.validate_email, ] ) string = forms.CharField( max_length=50, validators=[ validators.RegexValidator( regex='^[a-zA-Z]*$', message="Letters only.", ) ] ) ignore_case_string = forms.CharField( max_length=50, validators=[ validators.RegexValidator( regex='^[a-z]*$', message="Letters only.", flags=re.IGNORECASE, ) ] ) form = UserForm({ 'full_name': 'not int nor mail', 'string': '2 is not correct', 'ignore_case_string': "IgnORE Case strIng", }) with self.assertRaises(ValidationError) as e: form.fields['full_name'].clean('not int nor mail') self.assertEqual(2, len(e.exception.messages)) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['string'], ["Letters only."]) self.assertEqual(form.errors['string'], ["Letters only."]) def test_field_validators_can_be_any_iterable(self): class UserForm(forms.Form): full_name = forms.CharField( max_length=50, validators=( validators.validate_integer, validators.validate_email, ) ) form = UserForm({'full_name': 'not int nor mail'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['full_name'], ['Enter a valid integer.', 'Enter a valid email address.'])
ec164814864511331648997c69baf4272ea33c945355187219ec1bd19d3de519
import copy import datetime import json import uuid from django.core.exceptions import NON_FIELD_ERRORS from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import MaxValueValidator, RegexValidator from django.forms import ( BooleanField, CharField, CheckboxSelectMultiple, ChoiceField, DateField, DateTimeField, EmailField, FileField, FloatField, Form, HiddenInput, ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput, MultiValueField, NullBooleanField, PasswordInput, RadioSelect, Select, SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeField, ValidationError, forms, ) from django.forms.renderers import DjangoTemplates, get_default_renderer from django.forms.utils import ErrorList from django.http import QueryDict from django.template import Context, Template from django.test import SimpleTestCase from django.utils.datastructures import MultiValueDict from django.utils.safestring import mark_safe class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class PersonNew(Form): first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'})) last_name = CharField() birthday = DateField() class MultiValueDictLike(dict): def getlist(self, key): return [self[key]] class FormsTestCase(SimpleTestCase): # A Form is a collection of Fields. It knows how to validate a set of data and it # knows how to render itself in a couple of default ways (e.g., an HTML table). # You can pass it data in __init__(), as a dictionary. def test_form(self): # Pass a dictionary to a Form's __init__(). p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}) self.assertTrue(p.is_bound) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertHTMLEqual(p.errors.as_ul(), '') self.assertEqual(p.errors.as_text(), '') self.assertEqual(p.cleaned_data["first_name"], 'John') self.assertEqual(p.cleaned_data["last_name"], 'Lennon') self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) self.assertHTMLEqual( str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" required>' ) self.assertHTMLEqual( str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" required>' ) self.assertHTMLEqual( str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required>' ) msg = "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, first_name, last_name." with self.assertRaisesMessage(KeyError, msg): p['nonexistentfield'] form_output = [] for boundfield in p: form_output.append(str(boundfield)) self.assertHTMLEqual( '\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" required> <input type="text" name="last_name" value="Lennon" id="id_last_name" required> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" required>""" ) form_output = [] for boundfield in p: form_output.append([boundfield.label, boundfield.data]) self.assertEqual(form_output, [ ['First name', 'John'], ['Last name', 'Lennon'], ['Birthday', '1940-10-9'] ]) self.assertHTMLEqual( str(p), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" value="John" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" value="Lennon" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></td></tr>""" ) def test_empty_dict(self): # Empty dictionaries are valid, too. p = Person({}) self.assertTrue(p.is_bound) self.assertEqual(p.errors['first_name'], ['This field is required.']) self.assertEqual(p.errors['last_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {}) self.assertHTMLEqual( str(p), """<tr><th><label for="id_first_name">First name:</label></th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="birthday" id="id_birthday" required></td></tr>""" ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="birthday" id="id_birthday" required></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""" ) def test_empty_querydict_args(self): data = QueryDict() files = QueryDict() p = Person(data, files) self.assertIs(p.data, data) self.assertIs(p.files, files) def test_unbound_form(self): # If you don't pass any values to the Form's __init__(), or if you pass None, # the Form will be considered unbound and won't do any validation. Form.errors # will be an empty dictionary *but* Form.is_valid() will return False. p = Person() self.assertFalse(p.is_bound) self.assertEqual(p.errors, {}) self.assertFalse(p.is_valid()) with self.assertRaises(AttributeError): p.cleaned_data self.assertHTMLEqual( str(p), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required></td></tr>""" ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""" ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""" ) def test_unicode_values(self): # Unicode values are handled properly. p = Person({ 'first_name': 'John', 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9' }) self.assertHTMLEqual( p.as_table(), '<tr><th><label for="id_first_name">First name:</label></th><td>' '<input type="text" name="first_name" value="John" id="id_first_name" required></td></tr>\n' '<tr><th><label for="id_last_name">Last name:</label>' '</th><td><input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"' 'id="id_last_name" required></td></tr>\n' '<tr><th><label for="id_birthday">Birthday:</label></th><td>' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></td></tr>' ) self.assertHTMLEqual( p.as_ul(), '<li><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" required></li>\n' '<li><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required></li>\n' '<li><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></li>' ) self.assertHTMLEqual( p.as_p(), '<p><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" required></p>\n' '<p><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required></p>\n' '<p><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></p>' ) p = Person({'last_name': 'Lennon'}) self.assertEqual(p.errors['first_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertFalse(p.is_valid()) self.assertEqual( p.errors, {'birthday': ['This field is required.'], 'first_name': ['This field is required.']} ) self.assertEqual(p.cleaned_data, {'last_name': 'Lennon'}) self.assertEqual(p['first_name'].errors, ['This field is required.']) self.assertHTMLEqual( p['first_name'].errors.as_ul(), '<ul class="errorlist"><li>This field is required.</li></ul>' ) self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.') p = Person() self.assertHTMLEqual( str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" required>', ) self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" required>') self.assertHTMLEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" required>') def test_cleaned_data_only_fields(self): # cleaned_data will always *only* contain a key for fields defined in the # Form, even if you pass extra data when you define the Form. In this # example, we pass a bunch of extra fields to the form constructor, # but cleaned_data contains only the form's fields. data = { 'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9', 'extra1': 'hello', 'extra2': 'hello', } p = Person(data) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], 'John') self.assertEqual(p.cleaned_data['last_name'], 'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) def test_optional_data(self): # cleaned_data will include a key and value for *all* fields defined in the Form, # even if the Form's data didn't include a value for fields that are not # required. In this example, the data dictionary doesn't include a value for the # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the # empty string. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() nick_name = CharField(required=False) data = {'first_name': 'John', 'last_name': 'Lennon'} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['nick_name'], '') self.assertEqual(f.cleaned_data['first_name'], 'John') self.assertEqual(f.cleaned_data['last_name'], 'Lennon') # For DateFields, it's set to None. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() birth_date = DateField(required=False) data = {'first_name': 'John', 'last_name': 'Lennon'} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertIsNone(f.cleaned_data['birth_date']) self.assertEqual(f.cleaned_data['first_name'], 'John') self.assertEqual(f.cleaned_data['last_name'], 'Lennon') def test_auto_id(self): # "auto_id" tells the Form to add an "id" attribute to each form element. # If it's a string that contains '%s', Django will use that as a format string # into which the field's name will be inserted. It will also put a <label> around # the human-readable labels for a field. p = Person(auto_id='%s_id') self.assertHTMLEqual( p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td> <input type="text" name="first_name" id="first_name_id" required></td></tr> <tr><th><label for="last_name_id">Last name:</label></th><td> <input type="text" name="last_name" id="last_name_id" required></td></tr> <tr><th><label for="birthday_id">Birthday:</label></th><td> <input type="text" name="birthday" id="birthday_id" required></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></li> <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></li> <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></li>""" ) self.assertHTMLEqual( p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></p> <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></p> <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></p>""" ) def test_auto_id_true(self): # If auto_id is any True value whose str() does not contain '%s', the "id" # attribute will be the name of the field. p = Person(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""" ) def test_auto_id_false(self): # If auto_id is any False value, an "id" attribute won't be output unless it # was manually entered. p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""" ) def test_id_on_field(self): # In this example, auto_id is False, but the "id" attribute for the "first_name" # field is given. Also note that field gets a <label>, while the others don't. p = PersonNew(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""" ) def test_auto_id_on_form_and_field(self): # If the "id" attribute is specified in the Form and auto_id is True, the "id" # attribute in the Form gets precedence. p = PersonNew(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""" ) def test_various_boolean_values(self): class SignupForm(Form): email = EmailField() get_spam = BooleanField() f = SignupForm(auto_id=False) self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" required>') self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required>') f = SignupForm({'email': '[email protected]', 'get_spam': True}, auto_id=False) self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" value="[email protected]" required>') self.assertHTMLEqual( str(f['get_spam']), '<input checked type="checkbox" name="get_spam" required>', ) # 'True' or 'true' should be rendered without a value attribute f = SignupForm({'email': '[email protected]', 'get_spam': 'True'}, auto_id=False) self.assertHTMLEqual( str(f['get_spam']), '<input checked type="checkbox" name="get_spam" required>', ) f = SignupForm({'email': '[email protected]', 'get_spam': 'true'}, auto_id=False) self.assertHTMLEqual( str(f['get_spam']), '<input checked type="checkbox" name="get_spam" required>') # A value of 'False' or 'false' should be rendered unchecked f = SignupForm({'email': '[email protected]', 'get_spam': 'False'}, auto_id=False) self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required>') f = SignupForm({'email': '[email protected]', 'get_spam': 'false'}, auto_id=False) self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required>') # A value of '0' should be interpreted as a True value (#16820) f = SignupForm({'email': '[email protected]', 'get_spam': '0'}) self.assertTrue(f.is_valid()) self.assertTrue(f.cleaned_data.get('get_spam')) def test_widget_output(self): # Any Field can have a Widget class passed to its constructor: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea) f = ContactForm(auto_id=False) self.assertHTMLEqual(str(f['subject']), '<input type="text" name="subject" required>') self.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="10" cols="40" required></textarea>') # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output # widget type: self.assertHTMLEqual( f['subject'].as_textarea(), '<textarea name="subject" rows="10" cols="40" required></textarea>', ) self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" required>') self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message">') # The 'widget' parameter to a Field can also be an instance: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20})) f = ContactForm(auto_id=False) self.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="80" cols="20" required></textarea>') # Instance-level attrs are *not* carried over to as_textarea(), as_text() and # as_hidden(): self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" required>') f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False) self.assertHTMLEqual( f['subject'].as_textarea(), '<textarea rows="10" cols="40" name="subject" required>Hello</textarea>' ) self.assertHTMLEqual( f['message'].as_text(), '<input type="text" name="message" value="I love you." required>', ) self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message" value="I love you.">') def test_forms_with_choices(self): # For a form with a <select>, use ChoiceField: class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')]) f = FrameworkForm(auto_id=False) self.assertHTMLEqual(str(f['language']), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""") f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) self.assertHTMLEqual(str(f['language']), """<select name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""") # A subtlety: If one of the choices' value is the empty string and the form is # unbound, then the <option> for the empty-string choice will get selected. class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')]) f = FrameworkForm(auto_id=False) self.assertHTMLEqual(str(f['language']), """<select name="language" required> <option value="" selected>------</option> <option value="P">Python</option> <option value="J">Java</option> </select>""") # You can specify widget attributes in the Widget constructor. class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'})) f = FrameworkForm(auto_id=False) self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""") f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""") # When passing a custom widget instance to ChoiceField, note that setting # 'choices' on the widget is meaningless. The widget will use the choices # defined on the Field, not the ones defined on the Widget. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""") f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""") # You can set a ChoiceField's choices after the fact. class FrameworkForm(Form): name = CharField() language = ChoiceField() f = FrameworkForm(auto_id=False) self.assertHTMLEqual(str(f['language']), """<select name="language"> </select>""") f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')] self.assertHTMLEqual(str(f['language']), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""") def test_forms_with_radio(self): # Add widget=RadioSelect to use that widget with a ChoiceField. class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect) f = FrameworkForm(auto_id=False) self.assertHTMLEqual(str(f['language']), """<ul> <li><label><input type="radio" name="language" value="P" required> Python</label></li> <li><label><input type="radio" name="language" value="J" required> Java</label></li> </ul>""") self.assertHTMLEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" required></td></tr> <tr><th>Language:</th><td><ul> <li><label><input type="radio" name="language" value="P" required> Python</label></li> <li><label><input type="radio" name="language" value="J" required> Java</label></li> </ul></td></tr>""") self.assertHTMLEqual(f.as_ul(), """<li>Name: <input type="text" name="name" required></li> <li>Language: <ul> <li><label><input type="radio" name="language" value="P" required> Python</label></li> <li><label><input type="radio" name="language" value="J" required> Java</label></li> </ul></li>""") # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button # gets a distinct ID, formed by appending an underscore plus the button's # zero-based index. f = FrameworkForm(auto_id='id_%s') self.assertHTMLEqual( str(f['language']), """<ul id="id_language"> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required> Java</label></li> </ul>""" ) # When RadioSelect is used with auto_id, and the whole form is printed using # either as_table() or as_ul(), the label for the RadioSelect will point to the # ID of the *first* radio button. self.assertHTMLEqual( f.as_table(), """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" required></td></tr> <tr><th><label for="id_language_0">Language:</label></th><td><ul id="id_language"> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required> Java</label></li> </ul></td></tr>""" ) self.assertHTMLEqual( f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li><label for="id_language_0">Language:</label> <ul id="id_language"> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required> Java</label></li> </ul></li>""" ) self.assertHTMLEqual( f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p><label for="id_language_0">Language:</label> <ul id="id_language"> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required> Java</label></li> </ul></p>""" ) # Test iterating on individual radios in a template t = Template('{% for radio in form.language %}<div class="myradio">{{ radio }}</div>{% endfor %}') self.assertHTMLEqual( t.render(Context({'form': f})), """<div class="myradio"><label for="id_language_0"> <input id="id_language_0" name="language" type="radio" value="P" required> Python</label></div> <div class="myradio"><label for="id_language_1"> <input id="id_language_1" name="language" type="radio" value="J" required> Java</label></div>""" ) def test_form_with_iterable_boundfield(self): class BeatleForm(Form): name = ChoiceField( choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect, ) f = BeatleForm(auto_id=False) self.assertHTMLEqual( '\n'.join(str(bf) for bf in f['name']), """<label><input type="radio" name="name" value="john" required> John</label> <label><input type="radio" name="name" value="paul" required> Paul</label> <label><input type="radio" name="name" value="george" required> George</label> <label><input type="radio" name="name" value="ringo" required> Ringo</label>""" ) self.assertHTMLEqual( '\n'.join('<div>%s</div>' % bf for bf in f['name']), """<div><label><input type="radio" name="name" value="john" required> John</label></div> <div><label><input type="radio" name="name" value="paul" required> Paul</label></div> <div><label><input type="radio" name="name" value="george" required> George</label></div> <div><label><input type="radio" name="name" value="ringo" required> Ringo</label></div>""" ) def test_form_with_iterable_boundfield_id(self): class BeatleForm(Form): name = ChoiceField( choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect, ) fields = list(BeatleForm()['name']) self.assertEqual(len(fields), 4) self.assertEqual(fields[0].id_for_label, 'id_name_0') self.assertEqual(fields[0].choice_label, 'John') self.assertHTMLEqual( fields[0].tag(), '<input type="radio" name="name" value="john" id="id_name_0" required>' ) self.assertHTMLEqual( str(fields[0]), '<label for="id_name_0"><input type="radio" name="name" ' 'value="john" id="id_name_0" required> John</label>' ) self.assertEqual(fields[1].id_for_label, 'id_name_1') self.assertEqual(fields[1].choice_label, 'Paul') self.assertHTMLEqual( fields[1].tag(), '<input type="radio" name="name" value="paul" id="id_name_1" required>' ) self.assertHTMLEqual( str(fields[1]), '<label for="id_name_1"><input type="radio" name="name" ' 'value="paul" id="id_name_1" required> Paul</label>' ) def test_iterable_boundfield_select(self): class BeatleForm(Form): name = ChoiceField(choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')]) fields = list(BeatleForm(auto_id=False)['name']) self.assertEqual(len(fields), 4) self.assertEqual(fields[0].id_for_label, 'id_name_0') self.assertEqual(fields[0].choice_label, 'John') self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>') self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>') def test_form_with_noniterable_boundfield(self): # You can iterate over any BoundField, not just those with widget=RadioSelect. class BeatleForm(Form): name = CharField() f = BeatleForm(auto_id=False) self.assertHTMLEqual('\n'.join(str(bf) for bf in f['name']), '<input type="text" name="name" required>') def test_boundfield_slice(self): class BeatleForm(Form): name = ChoiceField( choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect, ) f = BeatleForm() bf = f['name'] self.assertEqual( [str(item) for item in bf[1:]], [str(bf[1]), str(bf[2]), str(bf[3])], ) def test_boundfield_bool(self): """BoundField without any choices (subwidgets) evaluates to True.""" class TestForm(Form): name = ChoiceField(choices=[]) self.assertIs(bool(TestForm()['name']), True) def test_forms_with_multiple_choice(self): # MultipleChoiceField is a special case, as its data is required to be a list: class SongForm(Form): name = CharField() composers = MultipleChoiceField() f = SongForm(auto_id=False) self.assertHTMLEqual(str(f['composers']), """<select multiple name="composers" required> </select>""") class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')]) f = SongForm(auto_id=False) self.assertHTMLEqual(str(f['composers']), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P">Paul McCartney</option> </select>""") f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) self.assertHTMLEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" required>') self.assertHTMLEqual(str(f['composers']), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P" selected>Paul McCartney</option> </select>""") def test_form_with_disabled_fields(self): class PersonForm(Form): name = CharField() birthday = DateField(disabled=True) class PersonFormFieldInitial(Form): name = CharField() birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16)) # Disabled fields are generally not transmitted by user agents. # The value from the form's initial data is used. f1 = PersonForm({'name': 'John Doe'}, initial={'birthday': datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial({'name': 'John Doe'}) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {'birthday': datetime.date(1974, 8, 16), 'name': 'John Doe'} ) # Values provided in the form's data are ignored. data = {'name': 'John Doe', 'birthday': '1984-11-10'} f1 = PersonForm(data, initial={'birthday': datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {'birthday': datetime.date(1974, 8, 16), 'name': 'John Doe'} ) # Initial data remains present on invalid forms. data = {} f1 = PersonForm(data, initial={'birthday': datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertFalse(form.is_valid()) self.assertEqual(form['birthday'].value(), datetime.date(1974, 8, 16)) def test_hidden_data(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')]) # MultipleChoiceField rendered as_hidden() is a special case. Because it can # have multiple values, its as_hidden() renders multiple <input type="hidden"> # tags. f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) self.assertHTMLEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P">') f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False) self.assertHTMLEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P"> <input type="hidden" name="composers" value="J">""") # DateTimeField rendered as_hidden() is special too class MessageForm(Form): when = SplitDateTimeField() f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'}) self.assertTrue(f.is_valid()) self.assertHTMLEqual( str(f['when']), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" required>' '<input type="text" name="when_1" value="01:01" id="id_when_1" required>' ) self.assertHTMLEqual( f['when'].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0">' '<input type="hidden" name="when_1" value="01:01" id="id_when_1">' ) def test_multiple_choice_checkbox(self): # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple, ) f = SongForm(auto_id=False) self.assertHTMLEqual(str(f['composers']), """<ul> <li><label><input type="checkbox" name="composers" value="J"> John Lennon</label></li> <li><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></li> </ul>""") f = SongForm({'composers': ['J']}, auto_id=False) self.assertHTMLEqual(str(f['composers']), """<ul> <li><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></li> <li><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></li> </ul>""") f = SongForm({'composers': ['J', 'P']}, auto_id=False) self.assertHTMLEqual(str(f['composers']), """<ul> <li><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></li> <li><label><input checked type="checkbox" name="composers" value="P"> Paul McCartney</label></li> </ul>""") # Test iterating on individual checkboxes in a template t = Template('{% for checkbox in form.composers %}<div class="mycheckbox">{{ checkbox }}</div>{% endfor %}') self.assertHTMLEqual(t.render(Context({'form': f})), """<div class="mycheckbox"><label> <input checked name="composers" type="checkbox" value="J"> John Lennon</label></div> <div class="mycheckbox"><label> <input checked name="composers" type="checkbox" value="P"> Paul McCartney</label></div>""") def test_checkbox_auto_id(self): # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox # gets a distinct ID, formed by appending an underscore plus the checkbox's # zero-based index. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple, ) f = SongForm(auto_id='%s_id') self.assertHTMLEqual( str(f['composers']), """<ul id="composers_id"> <li><label for="composers_id_0"> <input type="checkbox" name="composers" value="J" id="composers_id_0"> John Lennon</label></li> <li><label for="composers_id_1"> <input type="checkbox" name="composers" value="P" id="composers_id_1"> Paul McCartney</label></li> </ul>""" ) def test_multiple_choice_list_data(self): # Data for a MultipleChoiceField should be a list. QueryDict and # MultiValueDict conveniently work with this. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple, ) data = {'name': 'Yesterday', 'composers': ['J', 'P']} f = SongForm(data) self.assertEqual(f.errors, {}) data = QueryDict('name=Yesterday&composers=J&composers=P') f = SongForm(data) self.assertEqual(f.errors, {}) data = MultiValueDict({'name': ['Yesterday'], 'composers': ['J', 'P']}) f = SongForm(data) self.assertEqual(f.errors, {}) # SelectMultiple uses ducktyping so that MultiValueDictLike.getlist() # is called. f = SongForm(MultiValueDictLike({'name': 'Yesterday', 'composers': 'J'})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], ['J']) def test_multiple_hidden(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple, ) # The MultipleHiddenInput widget renders multiple values as hidden fields. class SongFormHidden(Form): name = CharField() composers = MultipleChoiceField( choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput, ) f = SongFormHidden(MultiValueDict({'name': ['Yesterday'], 'composers': ['J', 'P']}), auto_id=False) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" required> <input type="hidden" name="composers" value="J"> <input type="hidden" name="composers" value="P"></li>""" ) # When using CheckboxSelectMultiple, the framework expects a list of input and # returns a list of input. f = SongForm({'name': 'Yesterday'}, auto_id=False) self.assertEqual(f.errors['composers'], ['This field is required.']) f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], ['J']) self.assertEqual(f.cleaned_data['name'], 'Yesterday') f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], ['J', 'P']) self.assertEqual(f.cleaned_data['name'], 'Yesterday') # MultipleHiddenInput uses ducktyping so that # MultiValueDictLike.getlist() is called. f = SongForm(MultiValueDictLike({'name': 'Yesterday', 'composers': 'J'})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], ['J']) def test_escaping(self): # Validation errors are HTML-escaped when output as HTML. class EscapingForm(Form): special_name = CharField(label="<em>Special</em> Field") special_safe_name = CharField(label=mark_safe("<em>Special</em> Field")) def clean_special_name(self): raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name']) def clean_special_safe_name(self): raise ValidationError( mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name']) ) f = EscapingForm({ 'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape", }, auto_id=False) self.assertHTMLEqual( f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td> <ul class="errorlist"><li>Something&#39;s wrong with &#39;Nothing to escape&#39;</li></ul> <input type="text" name="special_name" value="Nothing to escape" required></td></tr> <tr><th><em>Special</em> Field:</th><td> <ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul> <input type="text" name="special_safe_name" value="Nothing to escape" required></td></tr>""" ) f = EscapingForm({ 'special_name': "Should escape < & > and <script>alert('xss')</script>", 'special_safe_name': "<i>Do not escape</i>" }, auto_id=False) self.assertHTMLEqual( f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td> <ul class="errorlist"><li>Something&#39;s wrong with &#39;Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;&#39;</li></ul> <input type="text" name="special_name" value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;" required></td></tr> <tr><th><em>Special</em> Field:</th><td> <ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul> <input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>""" ) def test_validating_multiple_fields(self): # There are a couple of ways to do multiple-field validation. If you want the # validation message to be associated with a particular field, implement the # clean_XXX() method on the Form, where XXX is the field name. As in # Field.clean(), the clean_XXX() method should return the cleaned value. In the # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary # of all the data that has been cleaned *so far*, in order by the fields, # including the current field (e.g., the field XXX if you're in clean_XXX()). class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean_password2(self): if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') return self.cleaned_data['password2'] f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertEqual(f.errors['username'], ['This field is required.']) self.assertEqual(f.errors['password1'], ['This field is required.']) self.assertEqual(f.errors['password2'], ['This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) self.assertEqual(f.errors['password2'], ['Please make sure your passwords match.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['username'], 'adrian') self.assertEqual(f.cleaned_data['password1'], 'foo') self.assertEqual(f.cleaned_data['password2'], 'foo') # Another way of doing multiple-field validation is by implementing the # Form's clean() method. Usually ValidationError raised by that method # will not be associated with a particular field and will have a # special-case association with the field named '__all__'. It's # possible to associate the errors to particular field with the # Form.add_error() method or by passing a dictionary that maps each # field to one or more errors. # # Note that in Form.clean(), you have access to self.cleaned_data, a # dictionary of all the fields/values that have *not* raised a # ValidationError. Also note Form.clean() is required to return a # dictionary of all clean data. class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): # Test raising a ValidationError as NON_FIELD_ERRORS. if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') # Test raising ValidationError that targets multiple fields. errors = {} if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE': errors['password1'] = 'Forbidden value.' if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE': errors['password2'] = ['Forbidden value.'] if errors: raise ValidationError(errors) # Test Form.add_error() if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE2': self.add_error(None, 'Non-field error 1.') self.add_error('password1', 'Forbidden value 2.') if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE2': self.add_error('password2', 'Forbidden value 2.') raise ValidationError('Non-field error 2.') return self.cleaned_data f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertHTMLEqual( f.as_table(), """<tr><th>Username:</th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="username" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password2" required></td></tr>""" ) self.assertEqual(f.errors['username'], ['This field is required.']) self.assertEqual(f.errors['password1'], ['This field is required.']) self.assertEqual(f.errors['password2'], ['This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.']) self.assertHTMLEqual( f.as_table(), """<tr><td colspan="2"> <ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr> <tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" required></td></tr>""" ) self.assertHTMLEqual( f.as_ul(), """<li><ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></li> <li>Username: <input type="text" name="username" value="adrian" maxlength="10" required></li> <li>Password1: <input type="password" name="password1" required></li> <li>Password2: <input type="password" name="password2" required></li>""" ) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['username'], 'adrian') self.assertEqual(f.cleaned_data['password1'], 'foo') self.assertEqual(f.cleaned_data['password2'], 'foo') f = UserRegistration({ 'username': 'adrian', 'password1': 'FORBIDDEN_VALUE', 'password2': 'FORBIDDEN_VALUE', }, auto_id=False) self.assertEqual(f.errors['password1'], ['Forbidden value.']) self.assertEqual(f.errors['password2'], ['Forbidden value.']) f = UserRegistration({ 'username': 'adrian', 'password1': 'FORBIDDEN_VALUE2', 'password2': 'FORBIDDEN_VALUE2', }, auto_id=False) self.assertEqual(f.errors['__all__'], ['Non-field error 1.', 'Non-field error 2.']) self.assertEqual(f.errors['password1'], ['Forbidden value 2.']) self.assertEqual(f.errors['password2'], ['Forbidden value 2.']) with self.assertRaisesMessage(ValueError, "has no field named"): f.add_error('missing_field', 'Some error.') def test_update_error_dict(self): class CodeForm(Form): code = CharField(max_length=10) def clean(self): try: raise ValidationError({'code': [ValidationError('Code error 1.')]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({'code': [ValidationError('Code error 2.')]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({'code': forms.ErrorList(['Code error 3.'])}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError('Non-field error 1.') except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError([ValidationError('Non-field error 2.')]) except ValidationError as e: self._errors = e.update_error_dict(self._errors) # The newly added list of errors is an instance of ErrorList. for field, error_list in self._errors.items(): if not isinstance(error_list, self.error_class): self._errors[field] = self.error_class(error_list) form = CodeForm({'code': 'hello'}) # Trigger validation. self.assertFalse(form.is_valid()) # update_error_dict didn't lose track of the ErrorDict type. self.assertIsInstance(form._errors, forms.ErrorDict) self.assertEqual(dict(form.errors), { 'code': ['Code error 1.', 'Code error 2.', 'Code error 3.'], NON_FIELD_ERRORS: ['Non-field error 1.', 'Non-field error 2.'], }) def test_has_error(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput, min_length=5) password2 = CharField(widget=PasswordInput) def clean(self): if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError( 'Please make sure your passwords match.', code='password_mismatch', ) f = UserRegistration(data={}) self.assertTrue(f.has_error('password1')) self.assertTrue(f.has_error('password1', 'required')) self.assertFalse(f.has_error('password1', 'anything')) f = UserRegistration(data={'password1': 'Hi', 'password2': 'Hi'}) self.assertTrue(f.has_error('password1')) self.assertTrue(f.has_error('password1', 'min_length')) self.assertFalse(f.has_error('password1', 'anything')) self.assertFalse(f.has_error('password2')) self.assertFalse(f.has_error('password2', 'anything')) f = UserRegistration(data={'password1': 'Bonjour', 'password2': 'Hello'}) self.assertFalse(f.has_error('password1')) self.assertFalse(f.has_error('password1', 'required')) self.assertTrue(f.has_error(NON_FIELD_ERRORS)) self.assertTrue(f.has_error(NON_FIELD_ERRORS, 'password_mismatch')) self.assertFalse(f.has_error(NON_FIELD_ERRORS, 'anything')) def test_dynamic_construction(self): # It's possible to construct a Form dynamically by adding to the self.fields # dictionary in __init__(). Don't forget to call Form.__init__() within the # subclass' __init__(). class Person(Form): first_name = CharField() last_name = CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['birthday'] = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" required></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" required></td></tr> <tr><th>Birthday:</th><td><input type="text" name="birthday" required></td></tr>""" ) # Instances of a dynamic Form do not persist fields from one Form instance to # the next. class MyForm(Form): def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [('field1', CharField()), ('field2', CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>""" ) field_list = [('field3', CharField()), ('field4', CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>""" ) class MyForm(Form): default_field_1 = CharField() default_field_2 = CharField() def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [('field1', CharField()), ('field2', CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required></td></tr> <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>""" ) field_list = [('field3', CharField()), ('field4', CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>""" ) # Similarly, changes to field attributes do not persist from one Form instance # to the next. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) def __init__(self, names_required=False, *args, **kwargs): super().__init__(*args, **kwargs) if names_required: self.fields['first_name'].required = True self.fields['first_name'].widget.attrs['class'] = 'required' self.fields['last_name'].required = True self.fields['last_name'].widget.attrs['class'] = 'required' f = Person(names_required=False) self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False)) self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {})) f = Person(names_required=True) self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True)) self.assertEqual( f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'reuired'}, {'class': 'required'}) ) f = Person(names_required=False) self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False)) self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {})) class Person(Form): first_name = CharField(max_length=30) last_name = CharField(max_length=30) def __init__(self, name_max_length=None, *args, **kwargs): super().__init__(*args, **kwargs) if name_max_length: self.fields['first_name'].max_length = name_max_length self.fields['last_name'].max_length = name_max_length f = Person(name_max_length=None) self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30)) f = Person(name_max_length=20) self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20)) f = Person(name_max_length=None) self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30)) # Similarly, choices do not persist from one Form instance to the next. # Refs #15127. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male'))) def __init__(self, allow_unspec_gender=False, *args, **kwargs): super().__init__(*args, **kwargs) if allow_unspec_gender: self.fields['gender'].choices += (('u', 'Unspecified'),) f = Person() self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')]) f = Person(allow_unspec_gender=True) self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')]) f = Person() self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')]) def test_validators_independence(self): """ The list of form field validators can be modified without polluting other forms. """ class MyForm(Form): myfield = CharField(max_length=25) f1 = MyForm() f2 = MyForm() f1.fields['myfield'].validators[0] = MaxValueValidator(12) self.assertNotEqual(f1.fields['myfield'].validators[0], f2.fields['myfield'].validators[0]) def test_hidden_widget(self): # HiddenInput widgets are displayed differently in the as_table(), as_ul()) # and as_p() output of a Form -- their verbose names are not displayed, and a # separate row is not displayed. They're displayed in the last row of the # form, directly after that row's form element. class Person(Form): first_name = CharField() last_name = CharField() hidden_text = CharField(widget=HiddenInput) birthday = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" required></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" required></td></tr> <tr><th>Birthday:</th> <td><input type="text" name="birthday" required><input type="hidden" name="hidden_text"></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required><input type="hidden" name="hidden_text"></li>""" ) self.assertHTMLEqual( p.as_p(), """<p>First name: <input type="text" name="first_name" required></p> <p>Last name: <input type="text" name="last_name" required></p> <p>Birthday: <input type="text" name="birthday" required><input type="hidden" name="hidden_text"></p>""" ) # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. p = Person(auto_id='id_%s') self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></li>""" ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></p>""" ) # If a field with a HiddenInput has errors, the as_table() and as_ul() output # will include the error message(s) with the text "(Hidden field [fieldname]) " # prepended. This message is displayed at the top of the output, regardless of # its field's order in the form. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"> <ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr> <tr><th>First name:</th><td><input type="text" name="first_name" value="John" required></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" required></td></tr> <tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></li> <li>First name: <input type="text" name="first_name" value="John" required></li> <li>Last name: <input type="text" name="last_name" value="Lennon" required></li> <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></li>""" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul> <p>First name: <input type="text" name="first_name" value="John" required></p> <p>Last name: <input type="text" name="last_name" value="Lennon" required></p> <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></p>""" ) # A corner case: It's possible for a form to have only HiddenInputs. class TestForm(Form): foo = CharField(widget=HiddenInput) bar = CharField(widget=HiddenInput) p = TestForm(auto_id=False) self.assertHTMLEqual(p.as_table(), '<input type="hidden" name="foo"><input type="hidden" name="bar">') self.assertHTMLEqual(p.as_ul(), '<input type="hidden" name="foo"><input type="hidden" name="bar">') self.assertHTMLEqual(p.as_p(), '<input type="hidden" name="foo"><input type="hidden" name="bar">') def test_field_order(self): # A Form's fields are displayed in the same order in which they were defined. class TestForm(Form): field1 = CharField() field2 = CharField() field3 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field7 = CharField() field8 = CharField() field9 = CharField() field10 = CharField() field11 = CharField() field12 = CharField() field13 = CharField() field14 = CharField() p = TestForm(auto_id=False) self.assertHTMLEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> <tr><th>Field5:</th><td><input type="text" name="field5" required></td></tr> <tr><th>Field6:</th><td><input type="text" name="field6" required></td></tr> <tr><th>Field7:</th><td><input type="text" name="field7" required></td></tr> <tr><th>Field8:</th><td><input type="text" name="field8" required></td></tr> <tr><th>Field9:</th><td><input type="text" name="field9" required></td></tr> <tr><th>Field10:</th><td><input type="text" name="field10" required></td></tr> <tr><th>Field11:</th><td><input type="text" name="field11" required></td></tr> <tr><th>Field12:</th><td><input type="text" name="field12" required></td></tr> <tr><th>Field13:</th><td><input type="text" name="field13" required></td></tr> <tr><th>Field14:</th><td><input type="text" name="field14" required></td></tr>""") def test_explicit_field_order(self): class TestFormParent(Form): field1 = CharField() field2 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field_order = ['field6', 'field5', 'field4', 'field2', 'field1'] class TestForm(TestFormParent): field3 = CharField() field_order = ['field2', 'field4', 'field3', 'field5', 'field6'] class TestFormRemove(TestForm): field1 = None class TestFormMissing(TestForm): field_order = ['field2', 'field4', 'field3', 'field5', 'field6', 'field1'] field1 = None class TestFormInit(TestFormParent): field3 = CharField() field_order = None def __init__(self, **kwargs): super().__init__(**kwargs) self.order_fields(field_order=TestForm.field_order) p = TestFormParent() self.assertEqual(list(p.fields), TestFormParent.field_order) p = TestFormRemove() self.assertEqual(list(p.fields), TestForm.field_order) p = TestFormMissing() self.assertEqual(list(p.fields), TestForm.field_order) p = TestForm() self.assertEqual(list(p.fields), TestFormMissing.field_order) p = TestFormInit() order = list(TestForm.field_order) + ['field1'] self.assertEqual(list(p.fields), order) TestForm.field_order = ['unknown'] p = TestForm() self.assertEqual(list(p.fields), ['field1', 'field2', 'field4', 'field5', 'field6', 'field3']) def test_form_html_attributes(self): # Some Field classes have an effect on the HTML attributes of their associated # Widget. If you set max_length in a CharField and its associated widget is # either a TextInput or PasswordInput, then the widget's rendered HTML will # include the "maxlength" attribute. class UserRegistration(Form): username = CharField(max_length=10) # uses TextInput by default password = CharField(max_length=10, widget=PasswordInput) realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" maxlength="10" required></li> <li>Realname: <input type="text" name="realname" maxlength="10" required></li> <li>Address: <input type="text" name="address" required></li>""" ) # If you specify a custom "attrs" that includes the "maxlength" attribute, # the Field's max_length attribute will override whatever "maxlength" you specify # in "attrs". class UserRegistration(Form): username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20})) password = CharField(max_length=10, widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" maxlength="10" required></li>""" ) def test_specifying_labels(self): # You can specify the label for a field by using the 'label' argument to a Field # class. If you don't specify 'label', Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. class UserRegistration(Form): username = CharField(max_length=10, label='Your username') password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)') p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Your username: <input type="text" name="username" maxlength="10" required></li> <li>Password1: <input type="password" name="password1" required></li> <li>Contraseña (de nuevo): <input type="password" name="password2" required></li>""" ) # Labels for as_* methods will only end in a colon if they don't end in other # punctuation already. class Questions(Form): q1 = CharField(label='The first question') q2 = CharField(label='What is your name?') q3 = CharField(label='The answer to life is:') q4 = CharField(label='Answer this question!') q5 = CharField(label='The last question. Period.') self.assertHTMLEqual( Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" required></p> <p>What is your name? <input type="text" name="q2" required></p> <p>The answer to life is: <input type="text" name="q3" required></p> <p>Answer this question! <input type="text" name="q4" required></p> <p>The last question. Period. <input type="text" name="q5" required></p>""" ) self.assertHTMLEqual( Questions().as_p(), """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required></p> <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required></p> <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required></p> <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required></p> <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required></p>""" ) # If a label is set to the empty string for a field, that field won't get a label. class UserRegistration(Form): username = CharField(max_length=10, label='') password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""") p = UserRegistration(auto_id='id_%s') self.assertHTMLEqual( p.as_ul(), """<li> <input id="id_username" type="text" name="username" maxlength="10" required></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li>""" ) # If label is None, Django will auto-create the label from the field name. This # is default behavior. class UserRegistration(Form): username = CharField(max_length=10, label=None) password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) p = UserRegistration(auto_id='id_%s') self.assertHTMLEqual( p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" required></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li>""" ) def test_label_suffix(self): # You can specify the 'label_suffix' argument to a Form class to modify the # punctuation symbol used at the end of a label. By default, the colon (:) is # used, and is only appended to the label if the label doesn't already end with a # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will # be appended regardless of the last character of the label. class FavoriteForm(Form): color = CharField(label='Favorite color?') animal = CharField(label='Favorite animal') answer = CharField(label='Secret answer', label_suffix=' =') f = FavoriteForm(auto_id=False) self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal: <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""") f = FavoriteForm(auto_id=False, label_suffix='?') self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal? <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""") f = FavoriteForm(auto_id=False, label_suffix='') self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""") f = FavoriteForm(auto_id=False, label_suffix='\u2192') self.assertHTMLEqual( f.as_ul(), '<li>Favorite color? <input type="text" name="color" required></li>\n' '<li>Favorite animal\u2192 <input type="text" name="animal" required></li>\n' '<li>Secret answer = <input type="text" name="answer" required></li>' ) def test_initial_data(self): # You can specify initial data for a field by using the 'initial' argument to a # Field class. This initial data is displayed when a Form is rendered with *no* # data. It is not displayed when a Form is rendered with any data (including an # empty dictionary). Also, the initial value is *not* used if data for a # particular required field isn't provided. class UserRegistration(Form): username = CharField(max_length=10, initial='django') password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) # Here, we're submitting data, so the initial value will *not* be displayed. p = UserRegistration({}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) p = UserRegistration({'username': ''}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) p = UserRegistration({'username': 'foo'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) # An 'initial' value is *not* used as a fallback if data is not provided. In this # example, we don't provide a value for 'username', and the form raises a # validation error rather than using the initial value for 'username'. p = UserRegistration({'password': 'secret'}) self.assertEqual(p.errors['username'], ['This field is required.']) self.assertFalse(p.is_valid()) def test_dynamic_initial_data(self): # The previous technique dealt with "hard-coded" initial data, but it's also # possible to specify initial data after you've already created the Form class # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This # should be a dictionary containing initial values for one or more fields in the # form, keyed by field name. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) p = UserRegistration(initial={'username': 'stephane'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) p = UserRegistration({'username': ''}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) p = UserRegistration({'username': 'foo'}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) # A dynamic 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the form raises a # validation error rather than using the initial value for 'username'. p = UserRegistration({'password': 'secret'}, initial={'username': 'django'}) self.assertEqual(p.errors['username'], ['This field is required.']) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), # then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial='django') password = CharField(widget=PasswordInput) p = UserRegistration(initial={'username': 'babik'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="babik" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) def test_callable_initial_data(self): # The previous technique dealt with raw values as initial data, but it's also # possible to specify callable data. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')]) # We need to define functions that get called later.) def initial_django(): return 'django' def initial_stephane(): return 'stephane' def initial_options(): return ['f', 'b'] def initial_other_options(): return ['b', 'w'] # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li>""" ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""" ) p = UserRegistration({'username': ''}, initial={'username': initial_django}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""" ) p = UserRegistration( {'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li>""" ) # A callable 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the form raises a # validation error rather than using the initial value for 'username'. p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options}) self.assertEqual(p.errors['username'], ['This field is required.']) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), # then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial=initial_django) password = CharField(widget=PasswordInput) options = MultipleChoiceField( choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')], initial=initial_other_options, ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b" selected>bar</option> <option value="w" selected>whiz</option> </select></li>""" ) p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li>""" ) def test_get_initial_for_field(self): class PersonForm(Form): first_name = CharField(initial='John') last_name = CharField(initial='Doe') age = IntegerField() occupation = CharField(initial=lambda: 'Unknown') form = PersonForm(initial={'first_name': 'Jane'}) self.assertEqual(form.get_initial_for_field(form.fields['age'], 'age'), None) self.assertEqual(form.get_initial_for_field(form.fields['last_name'], 'last_name'), 'Doe') # Form.initial overrides Field.initial. self.assertEqual(form.get_initial_for_field(form.fields['first_name'], 'first_name'), 'Jane') # Callables are evaluated. self.assertEqual(form.get_initial_for_field(form.fields['occupation'], 'occupation'), 'Unknown') def test_changed_data(self): class Person(Form): first_name = CharField(initial='Hans') last_name = CharField(initial='Greatel') birthday = DateField(initial=datetime.date(1974, 8, 16)) p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16'}) self.assertTrue(p.is_valid()) self.assertNotIn('first_name', p.changed_data) self.assertIn('last_name', p.changed_data) self.assertNotIn('birthday', p.changed_data) # A field raising ValidationError is always in changed_data class PedanticField(forms.Field): def to_python(self, value): raise ValidationError('Whatever') class Person2(Person): pedantic = PedanticField(initial='whatever', show_hidden_initial=True) p = Person2(data={ 'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16', 'initial-pedantic': 'whatever', }) self.assertFalse(p.is_valid()) self.assertIn('pedantic', p.changed_data) def test_boundfield_values(self): # It's possible to get to the value which would be used for rendering # the widget for a field by using the BoundField's value method. class UserRegistration(Form): username = CharField(max_length=10, initial='djangonaut') password = CharField(widget=PasswordInput) unbound = UserRegistration() bound = UserRegistration({'password': 'foo'}) self.assertIsNone(bound['username'].value()) self.assertEqual(unbound['username'].value(), 'djangonaut') self.assertEqual(bound['password'].value(), 'foo') self.assertIsNone(unbound['password'].value()) def test_boundfield_initial_called_once(self): """ Multiple calls to BoundField().value() in an unbound form should return the same result each time (#24391). """ class MyForm(Form): name = CharField(max_length=10, initial=uuid.uuid4) form = MyForm() name = form['name'] self.assertEqual(name.value(), name.value()) # BoundField is also cached self.assertIs(form['name'], name) def test_boundfield_value_disabled_callable_initial(self): class PersonForm(Form): name = CharField(initial=lambda: 'John Doe', disabled=True) # Without form data. form = PersonForm() self.assertEqual(form['name'].value(), 'John Doe') # With form data. As the field is disabled, the value should not be # affected by the form data. form = PersonForm({}) self.assertEqual(form['name'].value(), 'John Doe') def test_custom_boundfield(self): class CustomField(CharField): def get_bound_field(self, form, name): return (form, name) class SampleForm(Form): name = CustomField() f = SampleForm() self.assertEqual(f['name'], (f, 'name')) def test_initial_datetime_values(self): now = datetime.datetime.now() # Nix microseconds (since they should be ignored). #22502 now_no_ms = now.replace(microsecond=0) if now == now_no_ms: now = now.replace(microsecond=1) def delayed_now(): return now def delayed_now_time(): return now.time() class HiddenInputWithoutMicrosec(HiddenInput): supports_microseconds = False class TextInputWithoutMicrosec(TextInput): supports_microseconds = False class DateTimeForm(Form): auto_timestamp = DateTimeField(initial=delayed_now) auto_time_only = TimeField(initial=delayed_now_time) supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput) hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput) hi_without_microsec = DateTimeField(initial=delayed_now, widget=HiddenInputWithoutMicrosec) ti_without_microsec = DateTimeField(initial=delayed_now, widget=TextInputWithoutMicrosec) unbound = DateTimeForm() self.assertEqual(unbound['auto_timestamp'].value(), now_no_ms) self.assertEqual(unbound['auto_time_only'].value(), now_no_ms.time()) self.assertEqual(unbound['supports_microseconds'].value(), now) self.assertEqual(unbound['hi_default_microsec'].value(), now) self.assertEqual(unbound['hi_without_microsec'].value(), now_no_ms) self.assertEqual(unbound['ti_without_microsec'].value(), now_no_ms) def test_datetime_clean_initial_callable_disabled(self): now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456) class DateTimeForm(forms.Form): dt = DateTimeField(initial=lambda: now, disabled=True) form = DateTimeForm({}) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {'dt': now}) def test_datetime_changed_data_callable_with_microseconds(self): class DateTimeForm(forms.Form): dt = DateTimeField(initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True) form = DateTimeForm({'dt': '2006-10-25 14:30:45'}) self.assertEqual(form.changed_data, []) def test_help_text(self): # You can specify descriptive text for a field by using the 'help_text' argument) class UserRegistration(Form): username = CharField(max_length=10, help_text='e.g., [email protected]') password = CharField(widget=PasswordInput, help_text='Wählen Sie mit Bedacht.') p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""" ) self.assertHTMLEqual( p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></p> <p>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></p>""" ) self.assertHTMLEqual( p.as_table(), """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required><br> <span class="helptext">e.g., [email protected]</span></td></tr> <tr><th>Password:</th><td><input type="password" name="password" required><br> <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""" ) # The help text is displayed whether or not data is provided for the form. p = UserRegistration({'username': 'foo'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""" ) # help_text is not displayed for hidden fields. It can be used for documentation # purposes, though. class UserRegistration(Form): username = CharField(max_length=10, help_text='e.g., [email protected]') password = CharField(widget=PasswordInput) next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination') p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <input type="hidden" name="next" value="/"></li>""" ) def test_subclassing_forms(self): # You can subclass a Form to add fields. The resulting form subclass will have # all of the fields of the parent Form, plus whichever fields you define in the # subclass. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Musician(Person): instrument = CharField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""" ) m = Musician(auto_id=False) self.assertHTMLEqual( m.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Instrument: <input type="text" name="instrument" required></li>""" ) # Yes, you can subclass multiple forms. The fields are added in the order in # which the parent classes are listed. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Instrument(Form): instrument = CharField() class Beatle(Person, Instrument): haircut_type = CharField() b = Beatle(auto_id=False) self.assertHTMLEqual(b.as_ul(), """<li>Instrument: <input type="text" name="instrument" required></li> <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Haircut type: <input type="text" name="haircut_type" required></li>""") def test_forms_with_prefixes(self): # Sometimes it's necessary to have multiple forms display on the same HTML page, # or multiple copies of the same form. We can accomplish this with form prefixes. # Pass the keyword argument 'prefix' to the Form constructor to use this feature. # This value will be prepended to each HTML form field name. One way to think # about this is "namespaces for HTML forms". Notice that in the data argument, # each field's key has the prefix, in this case 'person1', prepended to the # actual field name. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() data = { 'person1-first_name': 'John', 'person1-last_name': 'Lennon', 'person1-birthday': '1940-10-9' } p = Person(data, prefix='person1') self.assertHTMLEqual( p.as_ul(), """<li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required></li> <li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required></li> <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required></li>""" ) self.assertHTMLEqual( str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required>' ) self.assertHTMLEqual( str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required>' ) self.assertHTMLEqual( str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required>' ) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], 'John') self.assertEqual(p.cleaned_data['last_name'], 'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) # Let's try submitting some bad data to make sure form.errors and field.errors # work as expected. data = { 'person1-first_name': '', 'person1-last_name': '', 'person1-birthday': '' } p = Person(data, prefix='person1') self.assertEqual(p.errors['first_name'], ['This field is required.']) self.assertEqual(p.errors['last_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertEqual(p['first_name'].errors, ['This field is required.']) # Accessing a nonexistent field. with self.assertRaises(KeyError): p['person1-first_name'].errors # In this example, the data doesn't have a prefix, but the form requires it, so # the form doesn't "see" the fields. data = { 'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9' } p = Person(data, prefix='person1') self.assertEqual(p.errors['first_name'], ['This field is required.']) self.assertEqual(p.errors['last_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) # With prefixes, a single data dictionary can hold data for multiple instances # of the same form. data = { 'person1-first_name': 'John', 'person1-last_name': 'Lennon', 'person1-birthday': '1940-10-9', 'person2-first_name': 'Jim', 'person2-last_name': 'Morrison', 'person2-birthday': '1943-12-8' } p1 = Person(data, prefix='person1') self.assertTrue(p1.is_valid()) self.assertEqual(p1.cleaned_data['first_name'], 'John') self.assertEqual(p1.cleaned_data['last_name'], 'Lennon') self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9)) p2 = Person(data, prefix='person2') self.assertTrue(p2.is_valid()) self.assertEqual(p2.cleaned_data['first_name'], 'Jim') self.assertEqual(p2.cleaned_data['last_name'], 'Morrison') self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8)) # By default, forms append a hyphen between the prefix and the field name, but a # form can alter that behavior by implementing the add_prefix() method. This # method takes a field name and returns the prefixed field, according to # self.prefix. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() def add_prefix(self, field_name): return '%s-prefix-%s' % (self.prefix, field_name) if self.prefix else field_name p = Person(prefix='foo') self.assertHTMLEqual( p.as_ul(), """<li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required></li> <li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required></li> <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required></li>""" ) data = { 'foo-prefix-first_name': 'John', 'foo-prefix-last_name': 'Lennon', 'foo-prefix-birthday': '1940-10-9' } p = Person(data, prefix='foo') self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], 'John') self.assertEqual(p.cleaned_data['last_name'], 'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) def test_class_prefix(self): # Prefix can be also specified at the class level. class Person(Form): first_name = CharField() prefix = 'foo' p = Person() self.assertEqual(p.prefix, 'foo') p = Person(prefix='bar') self.assertEqual(p.prefix, 'bar') def test_forms_with_null_boolean(self): # NullBooleanField is a bit of a special case because its presentation (widget) # is different than its data. This is handled transparently, though. class Person(Form): name = CharField() is_cool = NullBooleanField() p = Person({'name': 'Joe'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1" selected>Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': '1'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1" selected>Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': '2'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2" selected>Yes</option> <option value="3">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': '3'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2">Yes</option> <option value="3" selected>No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': True}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2" selected>Yes</option> <option value="3">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': False}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2">Yes</option> <option value="3" selected>No</option> </select>""") def test_forms_with_file_fields(self): # FileFields are a special case because they take their data from the request.FILES, # not request.POST. class FileForm(Form): file1 = FileField() f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>', ) f = FileForm(data={}, files={}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="file" name="file1" required></td></tr>' ) f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'')}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td>' '<ul class="errorlist"><li>The submitted file is empty.</li></ul>' '<input type="file" name="file1" required></td></tr>' ) f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td>' '<ul class="errorlist"><li>No file was submitted. Check the ' 'encoding type on the form.</li></ul>' '<input type="file" name="file1" required></td></tr>' ) f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'some content')}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>', ) self.assertTrue(f.is_valid()) file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode()) f = FileForm(data={}, files={'file1': file1}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>', ) # A required file field with initial data should not contain the # required HTML attribute. The file input is left blank by the user to # keep the existing, initial value. f = FileForm(initial={'file1': 'resume.txt'}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_filefield_initial_callable(self): class FileForm(forms.Form): file1 = forms.FileField(initial=lambda: 'resume.txt') f = FileForm({}) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['file1'], 'resume.txt') def test_basic_processing_in_view(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') return self.cleaned_data def my_function(method, post_data): if method == 'POST': form = UserRegistration(post_data, auto_id=False) else: form = UserRegistration(auto_id=False) if form.is_valid(): return 'VALID: %r' % sorted(form.cleaned_data.items()) t = Template( '<form method="post">\n' '<table>\n{{ form }}\n</table>\n<input type="submit" required>\n</form>' ) return t.render(Context({'form': form})) # Case 1: GET (an empty form, with no errors).) self.assertHTMLEqual(my_function('GET', {}), """<form method="post"> <table> <tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" required></td></tr> </table> <input type="submit" required> </form>""") # Case 2: POST with erroneous data (a redisplayed form, with errors).) self.assertHTMLEqual( my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """<form method="post"> <table> <tr><td colspan="2"><ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr> <tr><th>Username:</th><td><ul class="errorlist"> <li>Ensure this value has at most 10 characters (it has 23).</li></ul> <input type="text" name="username" value="this-is-a-long-username" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" required></td></tr> </table> <input type="submit" required> </form>""" ) # Case 3: POST with valid data (the success message).) self.assertEqual( my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: [('password1', 'secret'), ('password2', 'secret'), ('username', 'adrian')]" ) def test_templates_with_forms(self): class UserRegistration(Form): username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.") password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') return self.cleaned_data # You have full flexibility in displaying form fields in a template. Just pass a # Form instance to the template, and use "dot" access to refer to individual # fields. Note, however, that this flexibility comes with the responsibility of # displaying all the errors, including any that might not be associated with a # particular field. t = Template('''<form> {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> <input type="submit" required> </form>''') self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form> <p><label>Your username: <input type="text" name="username" maxlength="10" required></label></p> <p><label>Password: <input type="password" name="password1" required></label></p> <p><label>Password (again): <input type="password" name="password2" required></label></p> <input type="submit" required> </form>""") self.assertHTMLEqual( t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """<form> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required></label></p> <ul class="errorlist"><li>This field is required.</li></ul><p> <label>Password: <input type="password" name="password1" required></label></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label>Password (again): <input type="password" name="password2" required></label></p> <input type="submit" required> </form>""" ) # Use form.[field].label to output a field's label. You can specify the label for # a field by using the 'label' argument to a Field class. If you don't specify # 'label', Django will use the field name with underscores converted to spaces, # and the initial letter capitalized. t = Template('''<form> <p><label>{{ form.username.label }}: {{ form.username }}</label></p> <p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p> <p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p> <input type="submit" required> </form>''') self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form> <p><label>Username: <input type="text" name="username" maxlength="10" required></label></p> <p><label>Password1: <input type="password" name="password1" required></label></p> <p><label>Password2: <input type="password" name="password2" required></label></p> <input type="submit" required> </form>""") # User form.[field].label_tag to output a field's label with a <label> tag # wrapped around it, but *only* if the given field has an "id" attribute. # Recall from above that passing the "auto_id" argument to a Form gives each # field an "id" attribute. t = Template('''<form> <p>{{ form.username.label_tag }} {{ form.username }}</p> <p>{{ form.password1.label_tag }} {{ form.password1 }}</p> <p>{{ form.password2.label_tag }} {{ form.password2 }}</p> <input type="submit" required> </form>''') self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form> <p>Username: <input type="text" name="username" maxlength="10" required></p> <p>Password1: <input type="password" name="password1" required></p> <p>Password2: <input type="password" name="password2" required></p> <input type="submit" required> </form>""") self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form> <p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" required></p> <p><label for="id_password1">Password1:</label> <input type="password" name="password1" id="id_password1" required></p> <p><label for="id_password2">Password2:</label> <input type="password" name="password2" id="id_password2" required></p> <input type="submit" required> </form>""") # User form.[field].help_text to output a field's help text. If the given field # does not have help text, nothing will be output. t = Template('''<form> <p>{{ form.username.label_tag }} {{ form.username }}<br>{{ form.username.help_text }}</p> <p>{{ form.password1.label_tag }} {{ form.password1 }}</p> <p>{{ form.password2.label_tag }} {{ form.password2 }}</p> <input type="submit" required> </form>''') self.assertHTMLEqual( t.render(Context({'form': UserRegistration(auto_id=False)})), """<form> <p>Username: <input type="text" name="username" maxlength="10" required><br> Good luck picking a username that doesn&#39;t already exist.</p> <p>Password1: <input type="password" name="password1" required></p> <p>Password2: <input type="password" name="password2" required></p> <input type="submit" required> </form>""" ) self.assertEqual( Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), '' ) # To display the errors that aren't associated with a particular field -- e.g., # the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the # template. If used on its own, it is displayed as a <ul> (or an empty string, if # the list of errors is empty). You can also use it in {% if %} statements. t = Template('''<form> {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> <input type="submit" required> </form>''') self.assertHTMLEqual( t.render(Context({ 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) })), """<form> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required></label></p> <p><label>Password: <input type="password" name="password1" required></label></p> <p><label>Password (again): <input type="password" name="password2" required></label></p> <input type="submit" required> </form>""" ) t = Template('''<form> {{ form.non_field_errors }} {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> <input type="submit" required> </form>''') self.assertHTMLEqual( t.render(Context({ 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) })), """<form> <ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required></label></p> <p><label>Password: <input type="password" name="password1" required></label></p> <p><label>Password (again): <input type="password" name="password2" required></label></p> <input type="submit" required> </form>""" ) def test_empty_permitted(self): # Sometimes (pretty much in formsets) we want to allow a form to pass validation # if it is completely empty. We can accomplish this by using the empty_permitted # argument to a form constructor. class SongForm(Form): artist = CharField() name = CharField() # First let's show what happens id empty_permitted=False (the default): data = {'artist': '', 'song': ''} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'name': ['This field is required.'], 'artist': ['This field is required.']}) self.assertEqual(form.cleaned_data, {}) # Now let's show what happens when empty_permitted=True and the form is empty. form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {}) # But if we fill in data for one of the fields, the form is no longer empty and # the whole thing must pass validation. data = {'artist': 'The Doors', 'song': ''} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'name': ['This field is required.']}) self.assertEqual(form.cleaned_data, {'artist': 'The Doors'}) # If a field is not given in the data then None is returned for its data. Lets # make sure that when checking for empty_permitted that None is treated # accordingly. data = {'artist': None, 'song': ''} form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) # However, we *really* need to be sure we are checking for None as any data in # initial that returns False on a boolean call needs to be treated literally. class PriceForm(Form): amount = FloatField() qty = IntegerField() data = {'amount': '0.0', 'qty': ''} form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) def test_empty_permitted_and_use_required_attribute(self): msg = ( 'The empty_permitted and use_required_attribute arguments may not ' 'both be True.' ) with self.assertRaisesMessage(ValueError, msg): Person(empty_permitted=True, use_required_attribute=True) def test_extracting_hidden_and_visible(self): class SongForm(Form): token = CharField(widget=HiddenInput) artist = CharField() name = CharField() form = SongForm() self.assertEqual([f.name for f in form.hidden_fields()], ['token']) self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name']) def test_hidden_initial_gets_id(self): class MyForm(Form): field1 = CharField(max_length=50, show_hidden_initial=True) self.assertHTMLEqual( MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th>' '<td><input id="id_field1" type="text" name="field1" maxlength="50" required>' '<input type="hidden" name="initial-field1" id="initial-id_field1"></td></tr>' ) def test_error_html_required_html_classes(self): class Person(Form): name = CharField() is_cool = NullBooleanField() email = EmailField(required=False) age = IntegerField() p = Person({}) p.error_css_class = 'error' p.required_css_class = 'required' self.assertHTMLEqual( p.as_ul(), """<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li class="required"><label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="1" selected>Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select></li> <li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li> <li class="required error"><ul class="errorlist"><li>This field is required.</li></ul> <label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>""" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p class="required"><label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="1" selected>Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select></p> <p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p> <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></p>""" ) self.assertHTMLEqual( p.as_table(), """<tr class="required error"> <th><label class="required" for="id_name">Name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="name" id="id_name" required></td></tr> <tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th> <td><select name="is_cool" id="id_is_cool"> <option value="1" selected>Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select></td></tr> <tr><th><label for="id_email">Email:</label></th><td> <input type="email" name="email" id="id_email"></td></tr> <tr class="required error"><th><label class="required" for="id_age">Age:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="number" name="age" id="id_age" required></td></tr>""" ) def test_label_has_required_css_class(self): """ #17922 - required_css_class is added to the label_tag() of required fields. """ class SomeForm(Form): required_css_class = 'required' field = CharField(max_length=10) field2 = IntegerField(required=False) f = SomeForm({'field': 'test'}) self.assertHTMLEqual(f['field'].label_tag(), '<label for="id_field" class="required">Field:</label>') self.assertHTMLEqual( f['field'].label_tag(attrs={'class': 'foo'}), '<label for="id_field" class="foo required">Field:</label>' ) self.assertHTMLEqual(f['field2'].label_tag(), '<label for="id_field2">Field2:</label>') def test_label_split_datetime_not_displayed(self): class EventForm(Form): happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) form = EventForm() self.assertHTMLEqual( form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0">' '<input type="hidden" name="happened_at_1" id="id_happened_at_1">' ) def test_multivalue_field_validation(self): def bad_names(value): if value == 'bad value': raise ValidationError('bad value not allowed') class NameField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (CharField(label='First name', max_length=10), CharField(label='Last name', max_length=10)) super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): return ' '.join(data_list) class NameForm(Form): name = NameField(validators=[bad_names]) form = NameForm(data={'name': ['bad', 'value']}) form.full_clean() self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'name': ['bad value not allowed']}) form = NameForm(data={'name': ['should be overly', 'long for the field names']}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'name': ['Ensure this value has at most 10 characters (it has 16).', 'Ensure this value has at most 10 characters (it has 24).']}) form = NameForm(data={'name': ['fname', 'lname']}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {'name': 'fname lname'}) def test_multivalue_deep_copy(self): """ #19298 -- MultiValueField needs to override the default as it needs to deep-copy subfields: """ class ChoicesField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( ChoiceField(label='Rank', choices=((1, 1), (2, 2))), CharField(label='Name', max_length=10), ) super().__init__(fields=fields, *args, **kwargs) field = ChoicesField() field2 = copy.deepcopy(field) self.assertIsInstance(field2, ChoicesField) self.assertIsNot(field2.fields, field.fields) self.assertIsNot(field2.fields[0].choices, field.fields[0].choices) def test_multivalue_initial_data(self): """ #23674 -- invalid initial data should not break form.changed_data() """ class DateAgeField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (DateField(label="Date"), IntegerField(label="Age")) super().__init__(fields=fields, *args, **kwargs) class DateAgeForm(Form): date_age = DateAgeField() data = {"date_age": ["1998-12-06", 16]} form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]}) self.assertTrue(form.has_changed()) def test_multivalue_optional_subfields(self): class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = ( CharField(label='Country Code', validators=[ RegexValidator(r'^\+[0-9]{1,2}$', message='Enter a valid country code.')]), CharField(label='Phone Number'), CharField(label='Extension', error_messages={'incomplete': 'Enter an extension.'}), CharField(label='Label', required=False, help_text='E.g. home, work.'), ) super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return '%s.%s ext. %s (label: %s)' % tuple(data_list) return None # An empty value for any field will raise a `required` error on a # required `MultiValueField`. f = PhoneField() 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, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(['+61']) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(['+61', '287654321', '123']) self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home'])) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) # Empty values for fields will NOT raise a `required` error on an # optional `MultiValueField` f = PhoneField(required=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) self.assertEqual('+61. ext. (label: )', f.clean(['+61'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home'])) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) # For a required `MultiValueField` with `require_all_fields=False`, a # `required` error will only be raised if all fields are empty. Fields # can individually be required or optional. An empty value for any # required field will raise an `incomplete` error. f = PhoneField(require_all_fields=False) 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, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(['+61']) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.', 'Enter an extension.'"): f.clean(['', '', '', 'Home']) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) # For an optional `MultiValueField` with `require_all_fields=False`, we # don't get any `required` error but we still get `incomplete` errors. f = PhoneField(required=False, require_all_fields=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(['+61']) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.', 'Enter an extension.'"): f.clean(['', '', '', 'Home']) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) def test_custom_empty_values(self): """ Form fields can customize what is considered as an empty value for themselves (#19997). """ class CustomJSONField(CharField): empty_values = [None, ''] def to_python(self, value): # Fake json.loads if value == '{}': return {} return super().to_python(value) class JSONForm(forms.Form): json = CustomJSONField() form = JSONForm(data={'json': '{}'}) form.full_clean() self.assertEqual(form.cleaned_data, {'json': {}}) def test_boundfield_label_tag(self): class SomeForm(Form): field = CharField() boundfield = SomeForm()['field'] testcases = [ # (args, kwargs, expected) # without anything: just print the <label> ((), {}, '<label for="id_field">Field:</label>'), # passing just one argument: overrides the field's label (('custom',), {}, '<label for="id_field">custom:</label>'), # the overridden label is escaped (('custom&',), {}, '<label for="id_field">custom&amp;:</label>'), ((mark_safe('custom&'),), {}, '<label for="id_field">custom&:</label>'), # Passing attrs to add extra attributes on the <label> ((), {'attrs': {'class': 'pretty'}}, '<label for="id_field" class="pretty">Field:</label>') ] for args, kwargs, expected in testcases: with self.subTest(args=args, kwargs=kwargs): self.assertHTMLEqual(boundfield.label_tag(*args, **kwargs), expected) def test_boundfield_label_tag_no_id(self): """ If a widget has no id, label_tag just returns the text with no surrounding <label>. """ class SomeForm(Form): field = CharField() boundfield = SomeForm(auto_id='')['field'] self.assertHTMLEqual(boundfield.label_tag(), 'Field:') self.assertHTMLEqual(boundfield.label_tag('Custom&'), 'Custom&amp;:') def test_boundfield_label_tag_custom_widget_id_for_label(self): class CustomIdForLabelTextInput(TextInput): def id_for_label(self, id): return 'custom_' + id class EmptyIdForLabelTextInput(TextInput): def id_for_label(self, id): return None class SomeForm(Form): custom = CharField(widget=CustomIdForLabelTextInput) empty = CharField(widget=EmptyIdForLabelTextInput) form = SomeForm() self.assertHTMLEqual(form['custom'].label_tag(), '<label for="custom_id_custom">Custom:</label>') self.assertHTMLEqual(form['empty'].label_tag(), '<label>Empty:</label>') def test_boundfield_empty_label(self): class SomeForm(Form): field = CharField(label='') boundfield = SomeForm()['field'] self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>') def test_boundfield_id_for_label(self): class SomeForm(Form): field = CharField(label='') self.assertEqual(SomeForm()['field'].id_for_label, 'id_field') def test_boundfield_id_for_label_override_by_attrs(self): """ If an id is provided in `Widget.attrs`, it overrides the generated ID, unless it is `None`. """ class SomeForm(Form): field = CharField(widget=TextInput(attrs={'id': 'myCustomID'})) field_none = CharField(widget=TextInput(attrs={'id': None})) form = SomeForm() self.assertEqual(form['field'].id_for_label, 'myCustomID') self.assertEqual(form['field_none'].id_for_label, 'id_field_none') def test_label_tag_override(self): """ BoundField label_suffix (if provided) overrides Form label_suffix """ class SomeForm(Form): field = CharField() boundfield = SomeForm(label_suffix='!')['field'] self.assertHTMLEqual(boundfield.label_tag(label_suffix='$'), '<label for="id_field">Field$</label>') def test_field_name(self): """#5749 - `field_name` may be used as a key in _html_output().""" class SomeForm(Form): some_field = CharField() def as_p(self): return self._html_output( normal_row='<p id="p_%(field_name)s"></p>', error_row='%s', row_ender='</p>', help_text_html=' %s', errors_on_separate_row=True, ) form = SomeForm() self.assertHTMLEqual(form.as_p(), '<p id="p_some_field"></p>') def test_field_without_css_classes(self): """ `css_classes` may be used as a key in _html_output() (empty classes). """ class SomeForm(Form): some_field = CharField() def as_p(self): return self._html_output( normal_row='<p class="%(css_classes)s"></p>', error_row='%s', row_ender='</p>', help_text_html=' %s', errors_on_separate_row=True, ) form = SomeForm() self.assertHTMLEqual(form.as_p(), '<p class=""></p>') def test_field_with_css_class(self): """ `css_classes` may be used as a key in _html_output() (class comes from required_css_class in this case). """ class SomeForm(Form): some_field = CharField() required_css_class = 'foo' def as_p(self): return self._html_output( normal_row='<p class="%(css_classes)s"></p>', error_row='%s', row_ender='</p>', help_text_html=' %s', errors_on_separate_row=True, ) form = SomeForm() self.assertHTMLEqual(form.as_p(), '<p class="foo"></p>') def test_field_name_with_hidden_input(self): """ BaseForm._html_output() should merge all the hidden input fields and put them in the last row. """ class SomeForm(Form): hidden1 = CharField(widget=HiddenInput) custom = CharField() hidden2 = CharField(widget=HiddenInput) def as_p(self): return self._html_output( normal_row='<p%(html_class_attr)s>%(field)s %(field_name)s</p>', error_row='%s', row_ender='</p>', help_text_html=' %s', errors_on_separate_row=True, ) form = SomeForm() self.assertHTMLEqual( form.as_p(), '<p><input id="id_custom" name="custom" type="text" required> custom' '<input id="id_hidden1" name="hidden1" type="hidden">' '<input id="id_hidden2" name="hidden2" type="hidden"></p>' ) def test_field_name_with_hidden_input_and_non_matching_row_ender(self): """ BaseForm._html_output() should merge all the hidden input fields and put them in the last row ended with the specific row ender. """ class SomeForm(Form): hidden1 = CharField(widget=HiddenInput) custom = CharField() hidden2 = CharField(widget=HiddenInput) def as_p(self): return self._html_output( normal_row='<p%(html_class_attr)s>%(field)s %(field_name)s</p>', error_row='%s', row_ender='<hr><hr>', help_text_html=' %s', errors_on_separate_row=True ) form = SomeForm() self.assertHTMLEqual( form.as_p(), '<p><input id="id_custom" name="custom" type="text" required> custom</p>\n' '<input id="id_hidden1" name="hidden1" type="hidden">' '<input id="id_hidden2" name="hidden2" type="hidden"><hr><hr>' ) def test_error_dict(self): class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError('Non-field error.', code='secret', params={'a': 1, 'b': 2}) form = MyForm({}) self.assertIs(form.is_valid(), False) errors = form.errors.as_text() control = [ '* foo\n * This field is required.', '* bar\n * This field is required.', '* __all__\n * Non-field error.', ] for error in control: self.assertIn(error, errors) errors = form.errors.as_ul() control = [ '<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul></li>', ] for error in control: self.assertInHTML(error, errors) errors = form.errors.get_json_data() control = { 'foo': [{'code': 'required', 'message': 'This field is required.'}], 'bar': [{'code': 'required', 'message': 'This field is required.'}], '__all__': [{'code': 'secret', 'message': 'Non-field error.'}] } self.assertEqual(errors, control) self.assertEqual(json.dumps(errors), form.errors.as_json()) def test_error_dict_as_json_escape_html(self): """#21962 - adding html escape flag to ErrorDict""" class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( '<p>Non-field error.</p>', code='secret', params={'a': 1, 'b': 2}, ) control = { 'foo': [{'code': 'required', 'message': 'This field is required.'}], 'bar': [{'code': 'required', 'message': 'This field is required.'}], '__all__': [{'code': 'secret', 'message': '<p>Non-field error.</p>'}] } form = MyForm({}) self.assertFalse(form.is_valid()) errors = json.loads(form.errors.as_json()) self.assertEqual(errors, control) escaped_error = '&lt;p&gt;Non-field error.&lt;/p&gt;' self.assertEqual( form.errors.get_json_data(escape_html=True)['__all__'][0]['message'], escaped_error ) errors = json.loads(form.errors.as_json(escape_html=True)) control['__all__'][0]['message'] = escaped_error self.assertEqual(errors, control) def test_error_list(self): e = ErrorList() e.append('Foo') e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'})) self.assertIsInstance(e, list) self.assertIn('Foo', e) self.assertIn('Foo', forms.ValidationError(e)) self.assertEqual( e.as_text(), '* Foo\n* Foobar' ) self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) errors = e.get_json_data() self.assertEqual( errors, [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}] ) self.assertEqual(json.dumps(errors), e.as_json()) def test_error_list_class_not_specified(self): e = ErrorList() e.append('Foo') e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'})) self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) def test_error_list_class_has_one_class_specified(self): e = ErrorList(error_class='foobar-error-class') e.append('Foo') e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'})) self.assertEqual( e.as_ul(), '<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>' ) def test_error_list_with_hidden_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField(widget=HiddenInput) p = Person({'first_name': 'John'}) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></li><li> <label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></li>""" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></p>""" ) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></td></tr>""" ) def test_error_list_with_non_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField() def clean(self): raise ValidationError('Generic validation error') p = Person({'first_name': 'John', 'last_name': 'Lennon'}) self.assertHTMLEqual( str(p.non_field_errors()), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>' ) self.assertHTMLEqual( p.as_ul(), """<li> <ul class="errorlist nonfield"><li>Generic validation error</li></ul></li> <li><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></li> <li><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></li>""" ) self.assertHTMLEqual( p.non_field_errors().as_text(), '* Generic validation error' ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>Generic validation error</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></p> <p><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></p>""" ) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"><li>Generic validation error</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></td></tr>""" ) def test_errorlist_override(self): class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return '<div class="errorlist">%s</div>' % ''.join( '<div class="error">%s</div>' % e for e in self) class CommentForm(Form): name = CharField(max_length=50, required=False) email = EmailField() comment = CharField() data = {'email': 'invalid'} f = CommentForm(data, auto_id=False, error_class=DivErrorList) self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50"></p> <div class="errorlist"><div class="error">Enter a valid email address.</div></div> <p>Email: <input type="email" name="email" value="invalid" required></p> <div class="errorlist"><div class="error">This field is required.</div></div> <p>Comment: <input type="text" name="comment" required></p>""") def test_error_escaping(self): class TestForm(Form): hidden = CharField(widget=HiddenInput(), required=False) visible = CharField() def clean_hidden(self): raise ValidationError('Foo & "bar"!') clean_visible = clean_hidden form = TestForm({'hidden': 'a', 'visible': 'b'}) form.is_valid() self.assertHTMLEqual( form.as_ul(), '<li><ul class="errorlist nonfield"><li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>' '<li><ul class="errorlist"><li>Foo &amp; &quot;bar&quot;!</li></ul>' '<label for="id_visible">Visible:</label> ' '<input type="text" name="visible" value="b" id="id_visible" required>' '<input type="hidden" name="hidden" value="a" id="id_hidden"></li>' ) def test_baseform_repr(self): """ BaseForm.__repr__() should contain some basic information about the form. """ p = Person() self.assertEqual(repr(p), "<Person bound=False, valid=Unknown, fields=(first_name;last_name;birthday)>") p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}) self.assertEqual(repr(p), "<Person bound=True, valid=Unknown, fields=(first_name;last_name;birthday)>") p.is_valid() self.assertEqual(repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>") p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'}) p.is_valid() self.assertEqual(repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>") def test_baseform_repr_dont_trigger_validation(self): """ BaseForm.__repr__() shouldn't trigger the form validation. """ p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'}) repr(p) with self.assertRaises(AttributeError): p.cleaned_data self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {'first_name': 'John', 'last_name': 'Lennon'}) def test_accessing_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data if not self.errors: data['username'] = data['username'].lower() return data f = UserForm({'username': 'SirRobin', 'password': 'blue'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['username'], 'sirrobin') def test_changing_cleaned_data_nothing_returned(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): self.cleaned_data['username'] = self.cleaned_data['username'].lower() # don't return anything f = UserForm({'username': 'SirRobin', 'password': 'blue'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['username'], 'sirrobin') def test_changing_cleaned_data_in_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data # Return a different dict. We have not changed self.cleaned_data. return { 'username': data['username'].lower(), 'password': 'this_is_not_a_secret', } f = UserForm({'username': 'SirRobin', 'password': 'blue'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['username'], 'sirrobin') def test_multipart_encoded_form(self): class FormWithoutFile(Form): username = CharField() class FormWithFile(Form): username = CharField() file = FileField() class FormWithImage(Form): image = ImageField() self.assertFalse(FormWithoutFile().is_multipart()) self.assertTrue(FormWithFile().is_multipart()) self.assertTrue(FormWithImage().is_multipart()) def test_html_safe(self): class SimpleForm(Form): username = CharField() form = SimpleForm() self.assertTrue(hasattr(SimpleForm, '__html__')) self.assertEqual(str(form), form.__html__()) self.assertTrue(hasattr(form['username'], '__html__')) self.assertEqual(str(form['username']), form['username'].__html__()) def test_use_required_attribute_true(self): class MyForm(Form): use_required_attribute = True f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" required></p>' '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>' '</textarea></p>' '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></p>', ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label> ' '<input id="id_f1" maxlength="30" name="f1" type="text" required></li>' '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>' '</textarea></li>' '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></li>', ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text" required></td></tr>' '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th>' '<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>' '</textarea></td></tr>' '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></td></tr>', ) def test_use_required_attribute_false(self): class MyForm(Form): use_required_attribute = False f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text"></p>' '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">' '</textarea></p>' '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></p>', ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text"></li>' '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">' '</textarea></li>' '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></li>', ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>' '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th><td><textarea cols="40" id="id_f3" name="f3" rows="10">' '</textarea></td></tr>' '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></td></tr>', ) def test_only_hidden_fields(self): # A form with *only* hidden fields that has errors is going to be very unusual. class HiddenForm(Form): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield">' '<li>(Hidden field data) This field is required.</li></ul>\n<p> ' '<input type="hidden" name="data" id="id_data"></p>' ) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield">' '<li>(Hidden field data) This field is required.</li></ul>' '<input type="hidden" name="data" id="id_data"></td></tr>' ) def test_field_named_data(self): class DataForm(Form): data = CharField(max_length=10) f = DataForm({'data': 'xyzzy'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {'data': 'xyzzy'}) class CustomRenderer(DjangoTemplates): pass class RendererTests(SimpleTestCase): def test_default(self): form = Form() self.assertEqual(form.renderer, get_default_renderer()) def test_kwarg_instance(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_kwarg_class(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_attribute_instance(self): class CustomForm(Form): default_renderer = DjangoTemplates() form = CustomForm() self.assertEqual(form.renderer, CustomForm.default_renderer) def test_attribute_class(self): class CustomForm(Form): default_renderer = CustomRenderer form = CustomForm() self.assertTrue(isinstance(form.renderer, CustomForm.default_renderer)) def test_attribute_override(self): class CustomForm(Form): default_renderer = DjangoTemplates() custom = CustomRenderer() form = CustomForm(renderer=custom) self.assertEqual(form.renderer, custom)
ea19b5e6aeff913b906cfd314ac43bd03e978fe2aebb8f47e35e4d50b143c458
import sys from types import ModuleType from django.conf import Settings from django.test import SimpleTestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango30Warning class DefaultContentTypeTests(SimpleTestCase): msg = 'The DEFAULT_CONTENT_TYPE setting is deprecated.' @ignore_warnings(category=RemovedInDjango30Warning) def test_default_content_type_is_text_html(self): """ Content-Type of the default error responses is text/html. Refs #20822. """ with self.settings(DEFAULT_CONTENT_TYPE='text/xml'): response = self.client.get('/raises400/') self.assertEqual(response['Content-Type'], 'text/html') response = self.client.get('/raises403/') self.assertEqual(response['Content-Type'], 'text/html') response = self.client.get('/nonexistent_url/') self.assertEqual(response['Content-Type'], 'text/html') response = self.client.get('/server_error/') self.assertEqual(response['Content-Type'], 'text/html') def test_override_settings_warning(self): with self.assertRaisesMessage(RemovedInDjango30Warning, self.msg): with self.settings(DEFAULT_CONTENT_TYPE='text/xml'): pass def test_settings_init_warning(self): settings_module = ModuleType('fake_settings_module') settings_module.DEFAULT_CONTENT_TYPE = 'text/xml' settings_module.SECRET_KEY = 'abc' sys.modules['fake_settings_module'] = settings_module try: with self.assertRaisesMessage(RemovedInDjango30Warning, self.msg): Settings('fake_settings_module') finally: del sys.modules['fake_settings_module']
227d14a3ab460c484d94b2908f18dfc8db55ab91393d3b20222dffb5b1b5cb10
import mimetypes import unittest from os import path from urllib.parse import quote from django.conf.urls.static import static from django.core.exceptions import ImproperlyConfigured from django.http import FileResponse, HttpResponseNotModified from django.test import SimpleTestCase, override_settings from django.utils.http import http_date from django.views.static import was_modified_since from .. import urls from ..urls import media_dir @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') class StaticTests(SimpleTestCase): """Tests django views in django/views/static.py""" prefix = 'site_media' def test_serve(self): "The static view can serve static media" media_files = ['file.txt', 'file.txt.gz', '%2F.txt'] for filename in media_files: response = self.client.get('/%s/%s' % (self.prefix, quote(filename))) response_content = b''.join(response) file_path = path.join(media_dir, filename) with open(file_path, 'rb') as fp: self.assertEqual(fp.read(), response_content) self.assertEqual(len(response_content), int(response['Content-Length'])) self.assertEqual(mimetypes.guess_type(file_path)[1], response.get('Content-Encoding', None)) def test_chunked(self): "The static view should stream files in chunks to avoid large memory usage" response = self.client.get('/%s/%s' % (self.prefix, 'long-line.txt')) first_chunk = next(response.streaming_content) self.assertEqual(len(first_chunk), FileResponse.block_size) second_chunk = next(response.streaming_content) response.close() # strip() to prevent OS line endings from causing differences self.assertEqual(len(second_chunk.strip()), 1449) def test_unknown_mime_type(self): response = self.client.get('/%s/file.unknown' % self.prefix) self.assertEqual('application/octet-stream', response['Content-Type']) response.close() def test_copes_with_empty_path_component(self): file_name = 'file.txt' response = self.client.get('/%s//%s' % (self.prefix, file_name)) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) def test_is_modified_since(self): file_name = 'file.txt' response = self.client.get( '/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE='Thu, 1 Jan 1970 00:00:00 GMT' ) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) def test_not_modified_since(self): file_name = 'file.txt' response = self.client.get( '/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE='Mon, 18 Jan 2038 05:14:07 GMT' # This is 24h before max Unix time. Remember to fix Django and # update this test well before 2038 :) ) self.assertIsInstance(response, HttpResponseNotModified) def test_invalid_if_modified_since(self): """Handle bogus If-Modified-Since values gracefully Assume that a file is modified since an invalid timestamp as per RFC 2616, section 14.25. """ file_name = 'file.txt' invalid_date = 'Mon, 28 May 999999999999 28:25:26 GMT' response = self.client.get('/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE=invalid_date) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) self.assertEqual(len(response_content), int(response['Content-Length'])) def test_invalid_if_modified_since2(self): """Handle even more bogus If-Modified-Since values gracefully Assume that a file is modified since an invalid timestamp as per RFC 2616, section 14.25. """ file_name = 'file.txt' invalid_date = ': 1291108438, Wed, 20 Oct 2010 14:05:00 GMT' response = self.client.get('/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE=invalid_date) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) self.assertEqual(len(response_content), int(response['Content-Length'])) def test_404(self): response = self.client.get('/%s/nonexistent_resource' % self.prefix) self.assertEqual(404, response.status_code) def test_index(self): response = self.client.get('/%s/' % self.prefix) self.assertContains(response, 'Index of ./') @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { 'static/directory_index.html': 'Test index', }), ], }, }]) def test_index_custom_template(self): response = self.client.get('/%s/' % self.prefix) self.assertEqual(response.content, b'Test index') class StaticHelperTest(StaticTests): """ Test case to make sure the static URL pattern helper works as expected """ def setUp(self): super().setUp() self._old_views_urlpatterns = urls.urlpatterns[:] urls.urlpatterns += static('/media/', document_root=media_dir) def tearDown(self): super().tearDown() urls.urlpatterns = self._old_views_urlpatterns def test_prefix(self): self.assertEqual(static('test')[0].pattern.regex.pattern, '^test(?P<path>.*)$') @override_settings(DEBUG=False) def test_debug_off(self): """No URLs are served if DEBUG=False.""" self.assertEqual(static('test'), []) def test_empty_prefix(self): with self.assertRaisesMessage(ImproperlyConfigured, 'Empty static prefix not permitted'): static('') def test_special_prefix(self): """No URLs are served if prefix contains '://'.""" self.assertEqual(static('http://'), []) class StaticUtilsTests(unittest.TestCase): def test_was_modified_since_fp(self): """ A floating point mtime does not disturb was_modified_since (#18675). """ mtime = 1343416141.107817 header = http_date(mtime) self.assertFalse(was_modified_since(header, mtime))
7e7fee6af4134a8c116004f3d154a116be89f1640c4bdad8cfdef1000fe21374
import datetime from django.contrib.sites.models import Site from django.http import Http404 from django.template import TemplateDoesNotExist from django.test import RequestFactory, TestCase from django.test.utils import override_settings from django.views.defaults import ( bad_request, page_not_found, permission_denied, server_error, ) from ..models import Article, Author, UrlArticle @override_settings(ROOT_URLCONF='view_tests.urls') class DefaultsTests(TestCase): """Test django views in django/views/defaults.py""" nonexistent_urls = [ '/nonexistent_url/', # this is in urls.py '/other_nonexistent_url/', # this NOT in urls.py ] @classmethod def setUpTestData(cls): Author.objects.create(name='Boris') Article.objects.create( title='Old Article', slug='old_article', author_id=1, date_created=datetime.datetime(2001, 1, 1, 21, 22, 23) ) Article.objects.create( title='Current Article', slug='current_article', author_id=1, date_created=datetime.datetime(2007, 9, 17, 21, 22, 23) ) Article.objects.create( title='Future Article', slug='future_article', author_id=1, date_created=datetime.datetime(3000, 1, 1, 21, 22, 23) ) UrlArticle.objects.create( title='Old Article', slug='old_article', author_id=1, date_created=datetime.datetime(2001, 1, 1, 21, 22, 23) ) Site(id=1, domain='testserver', name='testserver').save() def test_page_not_found(self): "A 404 status is returned by the page_not_found view" for url in self.nonexistent_urls: response = self.client.get(url) self.assertEqual(response.status_code, 404) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '404.html': '{{ csrf_token }}', }), ], }, }]) def test_csrf_token_in_404(self): """ The 404 page should have the csrf_token available in the context """ # See ticket #14565 for url in self.nonexistent_urls: response = self.client.get(url) self.assertNotEqual(response.content, b'NOTPROVIDED') self.assertNotEqual(response.content, b'') def test_server_error(self): "The server_error view raises a 500 status" response = self.client.get('/server_error/') self.assertEqual(response.status_code, 500) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '404.html': 'This is a test template for a 404 error ' '(path: {{ request_path }}, exception: {{ exception }}).', '500.html': 'This is a test template for a 500 error.', }), ], }, }]) def test_custom_templates(self): """ 404.html and 500.html templates are picked by their respective handler. """ response = self.client.get('/server_error/') self.assertContains(response, "test template for a 500 error", status_code=500) response = self.client.get('/no_such_url/') self.assertContains(response, 'path: /no_such_url/', status_code=404) self.assertContains(response, 'exception: Resolver404', status_code=404) response = self.client.get('/technical404/') self.assertContains(response, 'exception: Testing technical 404.', status_code=404) def test_get_absolute_url_attributes(self): "A model can set attributes on the get_absolute_url method" self.assertTrue(getattr(UrlArticle.get_absolute_url, 'purge', False), 'The attributes of the original get_absolute_url must be added.') article = UrlArticle.objects.get(pk=1) self.assertTrue(getattr(article.get_absolute_url, 'purge', False), 'The attributes of the original get_absolute_url must be added.') def test_custom_templates_wrong(self): """ Default error views should raise TemplateDoesNotExist when passed a template that doesn't exist. """ rf = RequestFactory() request = rf.get('/') with self.assertRaises(TemplateDoesNotExist): bad_request(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): permission_denied(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): page_not_found(request, Http404(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): server_error(request, template_name='nonexistent')
639104a6e99b21cf0909edf352280e27152888588a57eddab523750a9c60a5a3
from django.template import TemplateDoesNotExist from django.test import ( Client, RequestFactory, SimpleTestCase, override_settings, ) from django.utils.translation import override from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure @override_settings(ROOT_URLCONF='view_tests.urls') class CsrfViewTests(SimpleTestCase): def setUp(self): super().setUp() self.client = Client(enforce_csrf_checks=True) @override_settings( USE_I18N=True, MIDDLEWARE=[ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ], ) def test_translation(self): """An invalid request is rejected with a localized error message.""" response = self.client.post('/') self.assertContains(response, 'Forbidden', status_code=403) self.assertContains(response, 'CSRF verification failed. Request aborted.', status_code=403) with self.settings(LANGUAGE_CODE='nl'), override('en-us'): response = self.client.post('/') self.assertContains(response, 'Verboden', status_code=403) self.assertContains(response, 'CSRF-verificatie mislukt. Verzoek afgebroken.', status_code=403) @override_settings( SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https') ) def test_no_referer(self): """ Referer header is strictly checked for POST over HTTPS. Trigger the exception by sending an incorrect referer. """ response = self.client.post('/', HTTP_X_FORWARDED_PROTO='https') self.assertContains( response, 'You are seeing this message because this HTTPS site requires a ' '&#39;Referer header&#39; to be sent by your Web browser, but ' 'none was sent.', status_code=403, ) self.assertContains( response, 'If you have configured your browser to disable &#39;Referer&#39; ' 'headers, please re-enable them, at least for this site, or for ' 'HTTPS connections, or for &#39;same-origin&#39; requests.', status_code=403, ) self.assertContains( response, 'If you are using the &lt;meta name=&quot;referrer&quot; ' 'content=&quot;no-referrer&quot;&gt; tag or including the ' '&#39;Referrer-Policy: no-referrer&#39; header, please remove them.', status_code=403, ) def test_no_cookies(self): """ The CSRF cookie is checked for POST. Failure to send this cookie should provide a nice error message. """ response = self.client.post('/') self.assertContains( response, 'You are seeing this message because this site requires a CSRF ' 'cookie when submitting forms. This cookie is required for ' 'security reasons, to ensure that your browser is not being ' 'hijacked by third parties.', status_code=403, ) @override_settings(TEMPLATES=[]) def test_no_django_template_engine(self): """ The CSRF view doesn't depend on the TEMPLATES configuration (#24388). """ response = self.client.post('/') self.assertContains(response, 'Forbidden', status_code=403) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { CSRF_FAILURE_TEMPLATE_NAME: 'Test template for CSRF failure' }), ], }, }]) def test_custom_template(self): """A custom CSRF_FAILURE_TEMPLATE_NAME is used.""" response = self.client.post('/') self.assertContains(response, 'Test template for CSRF failure', status_code=403) def test_custom_template_does_not_exist(self): """An exception is raised if a nonexistent template is supplied.""" factory = RequestFactory() request = factory.post('/') with self.assertRaises(TemplateDoesNotExist): csrf_failure(request, template_name='nonexistent.html')
a45884d27230621dc827f9d448477d84a9450410241aba5f8b2c1b49fca6a225
import gettext import json from os import path from django.conf import settings from django.test import ( RequestFactory, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.test.selenium import SeleniumTestCase from django.urls import reverse from django.utils.translation import ( LANGUAGE_SESSION_KEY, get_language, override, ) from django.views.i18n import JavaScriptCatalog, get_formats from ..urls import locale_dir @override_settings(ROOT_URLCONF='view_tests.urls') class SetLanguageTests(TestCase): """Test the django.views.i18n.set_language view.""" def _get_inactive_language_code(self): """Return language code for a language which is not activated.""" current_language = get_language() return [code for code, name in settings.LANGUAGES if not code == current_language][0] def test_setlang(self): """ The set_language view can be used to change the session language. The user is redirected to the 'next' argument if provided. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code, 'next': '/'} response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i_should_not_be_used/') self.assertRedirects(response, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) # The language is set in a cookie. language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME] self.assertEqual(language_cookie.value, lang_code) self.assertEqual(language_cookie['domain'], '') self.assertEqual(language_cookie['path'], '/') self.assertEqual(language_cookie['max-age'], '') def test_setlang_unsafe_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe". """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code, 'next': '//unsafe/redirection/'} response = self.client.post('/i18n/setlang/', data=post_data) self.assertEqual(response.url, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_http_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe" and its scheme is https if the request was sent over https. """ lang_code = self._get_inactive_language_code() non_https_next_url = 'http://testserver/redirection/' post_data = {'language': lang_code, 'next': non_https_next_url} # Insecure URL in POST data. response = self.client.post('/i18n/setlang/', data=post_data, secure=True) self.assertEqual(response.url, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) # Insecure URL in HTTP referer. response = self.client.post('/i18n/setlang/', secure=True, HTTP_REFERER=non_https_next_url) self.assertEqual(response.url, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_redirect_to_referer(self): """ The set_language view redirects to the URL in the referer header when there isn't a "next" parameter. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code} response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i18n/') self.assertRedirects(response, '/i18n/', fetch_redirect_response=False) self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_default_redirect(self): """ The set_language view redirects to '/' when there isn't a referer or "next" parameter. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code} response = self.client.post('/i18n/setlang/', post_data) self.assertRedirects(response, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_performs_redirect_for_ajax_if_explicitly_requested(self): """ The set_language view redirects to the "next" parameter for AJAX calls. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code, 'next': '/'} response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertRedirects(response, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_doesnt_perform_a_redirect_to_referer_for_ajax(self): """ The set_language view doesn't redirect to the HTTP referer header for AJAX calls. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code} headers = {'HTTP_REFERER': '/', 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'} response = self.client.post('/i18n/setlang/', post_data, **headers) self.assertEqual(response.status_code, 204) self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_doesnt_perform_a_default_redirect_for_ajax(self): """ The set_language view returns 204 for AJAX calls by default. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code} response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 204) self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_unsafe_next_for_ajax(self): """ The fallback to root URL for the set_language view works for AJAX calls. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code, 'next': '//unsafe/redirection/'} response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.url, '/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_reversal(self): self.assertEqual(reverse('set_language'), '/i18n/setlang/') def test_setlang_cookie(self): # we force saving language to a cookie rather than a session # by excluding session middleware and those which do require it test_settings = { 'MIDDLEWARE': ['django.middleware.common.CommonMiddleware'], 'LANGUAGE_COOKIE_NAME': 'mylanguage', 'LANGUAGE_COOKIE_AGE': 3600 * 7 * 2, 'LANGUAGE_COOKIE_DOMAIN': '.example.com', 'LANGUAGE_COOKIE_PATH': '/test/', } with self.settings(**test_settings): post_data = {'language': 'pl', 'next': '/views/'} response = self.client.post('/i18n/setlang/', data=post_data) language_cookie = response.cookies.get('mylanguage') self.assertEqual(language_cookie.value, 'pl') self.assertEqual(language_cookie['domain'], '.example.com') self.assertEqual(language_cookie['path'], '/test/') self.assertEqual(language_cookie['max-age'], 3600 * 7 * 2) def test_setlang_decodes_http_referer_url(self): """ The set_language view decodes the HTTP_REFERER URL. """ # The url() & view must exist for this to work as a regression test. self.assertEqual(reverse('with_parameter', kwargs={'parameter': 'x'}), '/test-setlang/x/') lang_code = self._get_inactive_language_code() encoded_url = '/test-setlang/%C3%A4/' # (%C3%A4 decodes to ä) response = self.client.post('/i18n/setlang/', {'language': lang_code}, HTTP_REFERER=encoded_url) self.assertRedirects(response, encoded_url, fetch_redirect_response=False) self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) @modify_settings(MIDDLEWARE={ 'append': 'django.middleware.locale.LocaleMiddleware', }) def test_lang_from_translated_i18n_pattern(self): response = self.client.post( '/i18n/setlang/', data={'language': 'nl'}, follow=True, HTTP_REFERER='/en/translated/' ) self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'nl') self.assertRedirects(response, '/nl/vertaald/') # And reverse response = self.client.post( '/i18n/setlang/', data={'language': 'en'}, follow=True, HTTP_REFERER='/nl/vertaald/' ) self.assertRedirects(response, '/en/translated/') @override_settings(ROOT_URLCONF='view_tests.urls') class I18NViewTests(SimpleTestCase): """Test django.views.i18n views other than set_language.""" @override_settings(LANGUAGE_CODE='de') def test_get_formats(self): formats = get_formats() # Test 3 possible types in get_formats: integer, string, and list. self.assertEqual(formats['FIRST_DAY_OF_WEEK'], 0) self.assertEqual(formats['DECIMAL_SEPARATOR'], '.') self.assertEqual(formats['TIME_INPUT_FORMATS'], ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']) def test_jsi18n(self): """The javascript_catalog can be deployed with language settings""" for lang_code in ['es', 'fr', 'ru']: with override(lang_code): catalog = gettext.translation('djangojs', locale_dir, [lang_code]) trans_txt = catalog.gettext('this is to be translated') response = self.client.get('/jsi18n/') self.assertEqual(response['Content-Type'], 'text/javascript; charset="utf-8"') # response content must include a line like: # "this is to be translated": <value of trans_txt Python variable> # json.dumps() is used to be able to check unicode strings self.assertContains(response, json.dumps(trans_txt), 1) if lang_code == 'fr': # Message with context (msgctxt) self.assertContains(response, '"month name\\u0004May": "mai"', 1) @override_settings(USE_I18N=False) def test_jsi18n_USE_I18N_False(self): response = self.client.get('/jsi18n/') # default plural function self.assertContains(response, 'django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };') self.assertNotContains(response, 'var newcatalog =') def test_jsoni18n(self): """ The json_catalog returns the language catalog and settings as JSON. """ with override('de'): response = self.client.get('/jsoni18n/') data = json.loads(response.content.decode()) self.assertIn('catalog', data) self.assertIn('formats', data) self.assertEqual(data['formats']['TIME_INPUT_FORMATS'], ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']) self.assertEqual(data['formats']['FIRST_DAY_OF_WEEK'], 0) self.assertIn('plural', data) self.assertEqual(data['catalog']['month name\x04May'], 'Mai') self.assertIn('DATETIME_FORMAT', data['formats']) self.assertEqual(data['plural'], '(n != 1)') def test_jsi18n_with_missing_en_files(self): """ The javascript_catalog shouldn't load the fallback language in the case that the current selected language is actually the one translated from, and hence missing translation files completely. This happens easily when you're translating from English to other languages and you've set settings.LANGUAGE_CODE to some other language than English. """ with self.settings(LANGUAGE_CODE='es'), override('en-us'): response = self.client.get('/jsi18n/') self.assertNotContains(response, 'esto tiene que ser traducido') def test_jsoni18n_with_missing_en_files(self): """ Same as above for the json_catalog view. Here we also check for the expected JSON format. """ with self.settings(LANGUAGE_CODE='es'), override('en-us'): response = self.client.get('/jsoni18n/') data = json.loads(response.content.decode()) self.assertIn('catalog', data) self.assertIn('formats', data) self.assertIn('plural', data) self.assertEqual(data['catalog'], {}) self.assertIn('DATETIME_FORMAT', data['formats']) self.assertIsNone(data['plural']) def test_jsi18n_fallback_language(self): """ Let's make sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'), override('fi'): response = self.client.get('/jsi18n/') self.assertContains(response, 'il faut le traduire') self.assertNotContains(response, "Untranslated string") def test_i18n_fallback_language_plural(self): """ The fallback to a language with less plural forms maintains the real language's number of plural forms and correct translations. """ with self.settings(LANGUAGE_CODE='pt'), override('ru'): response = self.client.get('/jsi18n/') self.assertEqual( response.context['catalog']['{count} plural3'], ['{count} plural3 p3', '{count} plural3 p3s', '{count} plural3 p3t'] ) self.assertEqual( response.context['catalog']['{count} plural2'], ['{count} plural2', '{count} plural2s', ''] ) with self.settings(LANGUAGE_CODE='ru'), override('pt'): response = self.client.get('/jsi18n/') self.assertEqual( response.context['catalog']['{count} plural3'], ['{count} plural3', '{count} plural3s'] ) self.assertEqual( response.context['catalog']['{count} plural2'], ['{count} plural2', '{count} plural2s'] ) def test_i18n_english_variant(self): with override('en-gb'): response = self.client.get('/jsi18n/') self.assertIn( '"this color is to be translated": "this colour is to be translated"', response.context['catalog_str'] ) def test_i18n_language_non_english_default(self): """ Check if the Javascript i18n view returns an empty language catalog if the default language is non-English, the selected language is English and there is not 'en' translation available. See #13388, #3594 and #13726 for more details. """ with self.settings(LANGUAGE_CODE='fr'), override('en-us'): response = self.client.get('/jsi18n/') self.assertNotContains(response, 'Choisir une heure') @modify_settings(INSTALLED_APPS={'append': 'view_tests.app0'}) def test_non_english_default_english_userpref(self): """ Same as above with the difference that there IS an 'en' translation available. The Javascript i18n view must return a NON empty language catalog with the proper English translations. See #13726 for more details. """ with self.settings(LANGUAGE_CODE='fr'), override('en-us'): response = self.client.get('/jsi18n_english_translation/') self.assertContains(response, 'this app0 string is to be translated') def test_i18n_language_non_english_fallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'), override('none'): response = self.client.get('/jsi18n/') self.assertContains(response, 'Choisir une heure') def test_escaping(self): # Force a language via GET otherwise the gettext functions are a noop! response = self.client.get('/jsi18n_admin/?language=de') self.assertContains(response, '\\x04') @modify_settings(INSTALLED_APPS={'append': ['view_tests.app5']}) def test_non_BMP_char(self): """ Non-BMP characters should not break the javascript_catalog (#21725). """ with self.settings(LANGUAGE_CODE='en-us'), override('fr'): response = self.client.get('/jsi18n/app5/') self.assertContains(response, 'emoji') self.assertContains(response, '\\ud83d\\udca9') @modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']}) def test_i18n_language_english_default(self): """ Check if the JavaScript i18n view returns a complete language catalog if the default language is en-us, the selected language has a translation available and a catalog composed by djangojs domain translations of multiple Python packages is requested. See #13388, #3594 and #13514 for more details. """ base_trans_string = 'il faut traduire cette cha\\u00eene de caract\\u00e8res de ' app1_trans_string = base_trans_string + 'app1' app2_trans_string = base_trans_string + 'app2' with self.settings(LANGUAGE_CODE='en-us'), override('fr'): response = self.client.get('/jsi18n_multi_packages1/') self.assertContains(response, app1_trans_string) self.assertContains(response, app2_trans_string) response = self.client.get('/jsi18n/app1/') self.assertContains(response, app1_trans_string) self.assertNotContains(response, app2_trans_string) response = self.client.get('/jsi18n/app2/') self.assertNotContains(response, app1_trans_string) self.assertContains(response, app2_trans_string) @modify_settings(INSTALLED_APPS={'append': ['view_tests.app3', 'view_tests.app4']}) def test_i18n_different_non_english_languages(self): """ Similar to above but with neither default or requested language being English. """ with self.settings(LANGUAGE_CODE='fr'), override('es-ar'): response = self.client.get('/jsi18n_multi_packages2/') self.assertContains(response, 'este texto de app3 debe ser traducido') def test_i18n_with_locale_paths(self): extended_locale_paths = settings.LOCALE_PATHS + [ path.join( path.dirname(path.dirname(path.abspath(__file__))), 'app3', 'locale', ), ] with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths): with override('es-ar'): response = self.client.get('/jsi18n/') self.assertContains(response, 'este texto de app3 debe ser traducido') def test_i18n_unknown_package_error(self): view = JavaScriptCatalog.as_view() request = RequestFactory().get('/') msg = 'Invalid package(s) provided to JavaScriptCatalog: unknown_package' with self.assertRaisesMessage(ValueError, msg): view(request, packages='unknown_package') msg += ',unknown_package2' with self.assertRaisesMessage(ValueError, msg): view(request, packages='unknown_package+unknown_package2') @override_settings(ROOT_URLCONF='view_tests.urls') class I18nSeleniumTests(SeleniumTestCase): # The test cases use fixtures & translations from these apps. available_apps = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'view_tests', ] @override_settings(LANGUAGE_CODE='de') def test_javascript_gettext(self): self.selenium.get(self.live_server_url + '/jsi18n_template/') elem = self.selenium.find_element_by_id("gettext") self.assertEqual(elem.text, "Entfernen") elem = self.selenium.find_element_by_id("ngettext_sing") self.assertEqual(elem.text, "1 Element") elem = self.selenium.find_element_by_id("ngettext_plur") self.assertEqual(elem.text, "455 Elemente") elem = self.selenium.find_element_by_id("pgettext") self.assertEqual(elem.text, "Kann") elem = self.selenium.find_element_by_id("npgettext_sing") self.assertEqual(elem.text, "1 Resultat") elem = self.selenium.find_element_by_id("npgettext_plur") self.assertEqual(elem.text, "455 Resultate") elem = self.selenium.find_element_by_id("formats") self.assertEqual( elem.text, "DATE_INPUT_FORMATS is an object; DECIMAL_SEPARATOR is a string; FIRST_DAY_OF_WEEK is a number;" ) @modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']}) @override_settings(LANGUAGE_CODE='fr') def test_multiple_catalogs(self): self.selenium.get(self.live_server_url + '/jsi18n_multi_catalogs/') elem = self.selenium.find_element_by_id('app1string') self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app1') elem = self.selenium.find_element_by_id('app2string') self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app2')
9d7761741b92f97d64b8a8ea20ea85ab8ab2da3dc3fc639defc77be5d75245f7
from django.test import SimpleTestCase, override_settings @override_settings(ROOT_URLCONF='view_tests.generic_urls') class URLHandling(SimpleTestCase): """ Tests for URL handling in views and responses. """ redirect_target = "/%E4%B8%AD%E6%96%87/target/" def test_nonascii_redirect(self): """ A non-ASCII argument to HttpRedirect is handled properly. """ response = self.client.get('/nonascii_redirect/') self.assertRedirects(response, self.redirect_target) def test_permanent_nonascii_redirect(self): """ A non-ASCII argument to HttpPermanentRedirect is handled properly. """ response = self.client.get('/permanent_nonascii_redirect/') self.assertRedirects(response, self.redirect_target, status_code=301)
fcab070b90ef27375e9f682884bc1608521809d113f196670bf2564164313d83
import importlib import inspect import os import re import sys import tempfile from io import StringIO from pathlib import Path from django.conf.urls import url from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.db import DatabaseError, connection from django.shortcuts import render from django.template import TemplateDoesNotExist from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.urls import reverse from django.utils.functional import SimpleLazyObject from django.utils.safestring import mark_safe from django.utils.version import PY36 from django.views.debug import ( CLEANSED_SUBSTITUTE, CallableSettingWrapper, ExceptionReporter, cleanse_setting, technical_500_response, ) from ..views import ( custom_exception_reporter_filter_view, index_page, multivalue_dict_key_error, non_sensitive_view, paranoid_view, sensitive_args_function_caller, sensitive_kwargs_function_caller, sensitive_method_view, sensitive_view, ) class User: def __str__(self): return 'jacob' class WithoutEmptyPathUrls: urlpatterns = [url(r'url/$', index_page, name='url')] class CallableSettingWrapperTests(SimpleTestCase): """ Unittests for CallableSettingWrapper """ def test_repr(self): class WrappedCallable: def __repr__(self): return "repr from the wrapped callable" def __call__(self): pass actual = repr(CallableSettingWrapper(WrappedCallable())) self.assertEqual(actual, "repr from the wrapped callable") @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') class DebugViewTests(SimpleTestCase): def test_files(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises/') self.assertEqual(response.status_code, 500) data = { 'file_data.txt': SimpleUploadedFile('file_data.txt', b'haha'), } with self.assertLogs('django.request', 'ERROR'): response = self.client.post('/raises/', data) self.assertContains(response, 'file_data.txt', status_code=500) self.assertNotContains(response, 'haha', status_code=500) def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) # Ensure no 403.html template exists to test the default case. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', }]) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) # Set up a test 403.html template. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '403.html': 'This is a test template for a 403 error ({{ exception }}).', }), ], }, }]) def test_403_template(self): response = self.client.get('/raises403/') self.assertContains(response, 'test template', status_code=403) self.assertContains(response, '(Insufficient Permissions).', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertEqual(response.status_code, 404) def test_raised_404(self): response = self.client.get('/views/raises404/') self.assertContains(response, "<code>not-in-urls</code>, didn't match", status_code=404) def test_404_not_in_urls(self): response = self.client.get('/not-in-urls') self.assertNotContains(response, "Raised by:", status_code=404) self.assertContains(response, "Django tried these URL patterns", status_code=404) self.assertContains(response, "<code>not-in-urls</code>, didn't match", status_code=404) # Pattern and view name of a RegexURLPattern appear. self.assertContains(response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404) self.assertContains(response, "[name='regex-post']", status_code=404) # Pattern and view name of a RoutePattern appear. self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404) self.assertContains(response, "[name='path-post']", status_code=404) @override_settings(ROOT_URLCONF=WithoutEmptyPathUrls) def test_404_empty_path_not_in_urls(self): response = self.client.get('/') self.assertContains(response, "The empty path didn't match any of these.", status_code=404) def test_technical_404(self): response = self.client.get('/views/technical404/') self.assertContains(response, "Raised by:", status_code=404) self.assertContains(response, "view_tests.views.technical404", status_code=404) def test_classbased_technical_404(self): response = self.client.get('/views/classbased404/') self.assertContains(response, "Raised by:", status_code=404) self.assertContains(response, "view_tests.views.Http404View", status_code=404) def test_non_l10ned_numeric_ids(self): """ Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized. """ with self.settings(DEBUG=True, USE_L10N=True): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') # We look for a HTML fragment of the form # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"' self.assertContains(response, '<div class="context" id="', status_code=500) match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content) self.assertIsNotNone(match) id_repr = match.group('id') self.assertFalse( re.search(b'[^c0-9]', id_repr), "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr.decode() ) def test_template_exceptions(self): with self.assertLogs('django.request', 'ERROR'): try: self.client.get(reverse('template_exception')) except Exception: raising_loc = inspect.trace()[-1][-2][0].strip() self.assertNotEqual( raising_loc.find("raise Exception('boom')"), -1, "Failed to find 'raise Exception' in last frame of " "traceback, instead found: %s" % raising_loc ) def test_template_loader_postmortem(self): """Tests for not existing file""" template_name = "notfound.html" with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) with override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [tempdir], }]), self.assertLogs('django.request', 'ERROR'): response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name})) self.assertContains(response, "%s (Source does not exist)" % template_path, status_code=500, count=2) # Assert as HTML. self.assertContains( response, '<li><code>django.template.loaders.filesystem.Loader</code>: ' '%s (Source does not exist)</li>' % os.path.join(tempdir, 'notfound.html'), status_code=500, html=True, ) def test_no_template_source_loaders(self): """ Make sure if you don't specify a template, the debug view doesn't blow up. """ with self.assertLogs('django.request', 'ERROR'): with self.assertRaises(TemplateDoesNotExist): self.client.get('/render_no_template/') @override_settings(ROOT_URLCONF='view_tests.default_urls') def test_default_urlconf_template(self): """ Make sure that the default URLconf template is shown shown instead of the technical 404 page, if the user has not altered their URLconf yet. """ response = self.client.get('/') self.assertContains( response, "<h2>The install worked successfully! Congratulations!</h2>" ) @override_settings(ROOT_URLCONF='view_tests.regression_21530_urls') def test_regression_21530(self): """ Regression test for bug #21530. If the admin app include is replaced with exactly one url pattern, then the technical 404 template should be displayed. The bug here was that an AttributeError caused a 500 response. """ response = self.client.get('/') self.assertContains( response, "Page not found <span>(404)</span>", status_code=404 ) class DebugViewQueriesAllowedTests(SimpleTestCase): # May need a query to initialize MySQL connection allow_database_queries = True def test_handle_db_exception(self): """ Ensure the debug view works when a database exception is raised by performing an invalid query and passing the exception to the debug view. """ with connection.cursor() as cursor: try: cursor.execute('INVALID SQL') except DatabaseError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get('/'), *exc_info) self.assertContains(response, 'OperationalError at /', status_code=500) @override_settings( DEBUG=True, ROOT_URLCONF='view_tests.urls', # No template directories are configured, so no templates will be found. TEMPLATES=[{ 'BACKEND': 'django.template.backends.dummy.TemplateStrings', }], ) class NonDjangoTemplatesDebugViewTests(SimpleTestCase): def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertEqual(response.status_code, 404) def test_template_not_found_error(self): # Raises a TemplateDoesNotExist exception and shows the debug view. url = reverse('raises_template_does_not_exist', kwargs={"path": "notfound.html"}) with self.assertLogs('django.request', 'ERROR'): response = self.client.get(url) self.assertContains(response, '<div class="context" id="', status_code=500) class ExceptionReporterTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Can&#39;t find my keys</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>jacob</p>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) self.assertIn('<p>No POST data</p>', html) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError</h1>', html) self.assertIn('<pre class="exception_value">Can&#39;t find my keys</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_eol_support(self): """The ExceptionReporter supports Unix, Windows and Macintosh EOL markers""" LINES = ['print %d' % i for i in range(1, 6)] reporter = ExceptionReporter(None, None, None, None) for newline in ['\n', '\r\n', '\r']: fd, filename = tempfile.mkstemp(text=False) os.write(fd, (newline.join(LINES) + newline).encode()) os.close(fd) try: self.assertEqual( reporter._get_lines_from_file(filename, 3, 2), (1, LINES[1:3], LINES[3], LINES[4:]) ) finally: os.unlink(filename) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">No exception message supplied</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_reporting_of_nested_exceptions(self): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError(mark_safe('<p>Second exception</p>')) from explicit except ValueError: raise IndexError(mark_safe('<p>Final exception</p>')) except Exception: # Custom exception handler, just pass it into ExceptionReporter exc_type, exc_value, tb = sys.exc_info() explicit_exc = 'The above exception ({0}) was the direct cause of the following exception:' implicit_exc = 'During handling of the above exception ({0}), another exception occurred:' reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2, html.count(implicit_exc.format('&lt;p&gt;Second exception&lt;/p&gt;'))) self.assertEqual(10, html.count('&lt;p&gt;Final exception&lt;/p&gt;')) text = reporter.get_traceback_text() self.assertIn(explicit_exc.format('<p>Top level</p>'), text) self.assertIn(implicit_exc.format('<p>Second exception</p>'), text) self.assertEqual(3, text.count('<p>Final exception</p>')) def test_reporting_frames_without_source(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, 'generated', 'exec') exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame['context_line'], '<source code not available>') self.assertEqual(last_frame['filename'], 'generated') self.assertEqual(last_frame['function'], 'funcName') self.assertEqual(last_frame['lineno'], 2) html = reporter.get_traceback_html() self.assertIn('generated in funcName', html) text = reporter.get_traceback_text() self.assertIn('"generated" in funcName', text) def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">I&#39;m a little teapot</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report</h1>', html) self.assertIn('<pre class="exception_value">I&#39;m a little teapot</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_non_utf8_values_handling(self): "Non-UTF-8 exceptions/values should not make the output generation choke." try: class NonUtf8Output(Exception): def __repr__(self): return b'EXC\xe9EXC' somevar = b'VAL\xe9VAL' # NOQA raise NonUtf8Output() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('VAL\\xe9VAL', html) self.assertIn('EXC\\xe9EXC', html) def test_local_variable_escaping(self): """Safe strings in local variables are escaped.""" try: local = mark_safe('<p>Local variable</p>') raise ValueError(local) except Exception: exc_type, exc_value, tb = sys.exc_info() html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html() self.assertIn('<td class="code"><pre>&#39;&lt;p&gt;Local variable&lt;/p&gt;&#39;</pre></td>', html) def test_unprintable_values_handling(self): "Unprintable values should not make the output generation choke." try: class OomOutput: def __repr__(self): raise MemoryError('OOM') oomvalue = OomOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<td class="code"><pre>Error in formatting', html) def test_too_large_values_handling(self): "Large values should not create a large HTML." large = 256 * 1024 repr_of_str_adds = len(repr('')) try: class LargeOutput: def __repr__(self): return repr('A' * large) largevalue = LargeOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertEqual(len(html) // 1024 // 128, 0) # still fit in 128Kb self.assertIn('&lt;trimmed %d bytes string&gt;' % (large + repr_of_str_adds,), html) def test_encoding_error(self): """ A UnicodeError displays a portion of the problematic string. HTML in safe strings is escaped. """ try: mark_safe('abcdefghijkl<p>mnὀp</p>qrstuwxyz').encode('ascii') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<h2>Unicode error hint</h2>', html) self.assertIn('The string that could not be encoded/decoded was: ', html) self.assertIn('<strong>&lt;p&gt;mnὀp&lt;/p&gt;</strong>', html) def test_unfrozen_importlib(self): """ importlib is not a frozen app, but its loader thinks it's frozen which results in an ImportError. Refs #21443. """ try: request = self.rf.get('/test_view/') importlib.import_module('abc.def.invalid.name') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>%sError at /test_view/</h1>' % ('ModuleNotFound' if PY36 else 'Import'), html) def test_ignore_traceback_evaluation_exceptions(self): """ Don't trip over exceptions generated by crafted objects when evaluating them while cleansing (#24455). """ class BrokenEvaluation(Exception): pass def broken_setup(): raise BrokenEvaluation request = self.rf.get('/test_view/') broken_lazy = SimpleLazyObject(broken_setup) try: bool(broken_lazy) except BrokenEvaluation: exc_type, exc_value, tb = sys.exc_info() self.assertIn( "BrokenEvaluation", ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(), "Evaluation exception reason not mentioned in traceback" ) @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertIn("http://evil.com/", html) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ value = '<td>items</td><td class="code"><pre>&#39;Oops&#39;</pre></td>' # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: ' 'items (application/octet-stream)&gt;</pre></td>', html ) # COOKES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<td>items</td><td class="code"><pre>&#39;Oops&#39;</pre></td>', html) def test_exception_fetching_user(self): """ The error page can be rendered if the current user can't be retrieved (such as when the database is unavailable). """ class ExceptionUser: def __str__(self): raise Exception() request = self.rf.get('/test_view/') request.user = ExceptionUser() try: raise ValueError('Oops') except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>[unable to retrieve the current user]</p>', html) text = reporter.get_traceback_text() self.assertIn('USER: [unable to retrieve the current user]', text) class PlainTextReportTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError at /test_view/', text) self.assertIn("Can't find my keys", text) self.assertIn('Request Method:', text) self.assertIn('Request URL:', text) self.assertIn('USER: jacob', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback:', text) self.assertIn('Request information:', text) self.assertNotIn('Request data not supplied', text) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError', text) self.assertIn("Can't find my keys", text) self.assertNotIn('Request Method:', text) self.assertNotIn('Request URL:', text) self.assertNotIn('USER:', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback:', text) self.assertIn('Request data not supplied', text) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) reporter.get_traceback_text() def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(DEBUG=True) def test_template_exception(self): request = self.rf.get('/test_view/') try: render(request, 'debug/template_error.html') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() templ_path = Path(Path(__file__).parent.parent, 'templates', 'debug', 'template_error.html') self.assertIn( 'Template error:\n' 'In template %(path)s, error at line 2\n' ' \'cycle\' tag requires at least two arguments\n' ' 1 : Template with error:\n' ' 2 : {%% cycle %%} \n' ' 3 : ' % {'path': templ_path}, text ) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn('items = <InMemoryUploadedFile:', text) # COOKES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("http://evil.com/", text) class ExceptionReportTestMixin: # Mixin used in the ExceptionReporterFilterTests and # AjaxResponseExceptionReporterFilter tests below breakfast_data = {'sausage-key': 'sausage-value', 'baked-beans-key': 'baked-beans-value', 'hash-brown-key': 'hash-brown-value', 'bacon-key': 'bacon-value'} def verify_unsafe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # All variables are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertContains(response, k, status_code=500) self.assertContains(response, v, status_code=500) def verify_safe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Non-sensitive variable's name and value are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) # Sensitive variable's name is shown but not its value. self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # Non-sensitive POST parameters' values are shown. self.assertContains(response, 'baked-beans-value', status_code=500) self.assertContains(response, 'hash-brown-value', status_code=500) # Sensitive POST parameters' values are not shown. self.assertNotContains(response, 'sausage-value', status_code=500) self.assertNotContains(response, 'bacon-value', status_code=500) def verify_paranoid_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that no variables or POST parameters are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Show variable names but not their values. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertNotContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # No POST parameters' values are shown. self.assertNotContains(response, v, status_code=500) def verify_unsafe_email(self, view, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertIn('worcestershire', body_html) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertIn(k, body_plain) self.assertIn(v, body_plain) self.assertIn(k, body_html) self.assertIn(v, body_html) def verify_safe_email(self, view, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertNotIn('worcestershire', body_html) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertIn(k, body_plain) # Non-sensitive POST parameters' values are shown. self.assertIn('baked-beans-value', body_plain) self.assertIn('hash-brown-value', body_plain) self.assertIn('baked-beans-value', body_html) self.assertIn('hash-brown-value', body_html) # Sensitive POST parameters' values are not shown. self.assertNotIn('sausage-value', body_plain) self.assertNotIn('bacon-value', body_plain) self.assertNotIn('sausage-value', body_html) self.assertNotIn('bacon-value', body_html) def verify_paranoid_email(self, view): """ Asserts that no variables or POST parameters are displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body = str(email.body) self.assertNotIn('cooked_eggs', body) self.assertNotIn('scrambled', body) self.assertNotIn('sauce', body) self.assertNotIn('worcestershire', body) for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertIn(k, body) # No POST parameters' values are shown. self.assertNotIn(v, body) @override_settings(ROOT_URLCONF='view_tests.urls') class ExceptionReporterFilterTests(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports (#14614). """ rf = RequestFactory() def test_non_sensitive_request(self): """ Everything (request info and frame variables) can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) def test_sensitive_request(self): """ Sensitive POST parameters and frame variables cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view) self.verify_unsafe_email(sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view) self.verify_safe_email(sensitive_view) def test_paranoid_request(self): """ No POST parameters and frame variables can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view) self.verify_unsafe_email(paranoid_view) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view) self.verify_paranoid_email(paranoid_view) def test_multivalue_dict_key_error(self): """ #21098 -- Sensitive POST parameters cannot be seen in the error reports for if request.POST['nonexistent_key'] throws an error. """ with self.settings(DEBUG=True): self.verify_unsafe_response(multivalue_dict_key_error) self.verify_unsafe_email(multivalue_dict_key_error) with self.settings(DEBUG=False): self.verify_safe_response(multivalue_dict_key_error) self.verify_safe_email(multivalue_dict_key_error) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) def test_sensitive_method(self): """ The sensitive_variables decorator works with object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_method_view, check_for_POST_params=False) self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_method_view, check_for_POST_params=False) self.verify_safe_email(sensitive_method_view, check_for_POST_params=False) def test_sensitive_function_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_args_function_caller) self.verify_unsafe_email(sensitive_args_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_args_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_args_function_caller, check_for_POST_params=False) def test_sensitive_function_keyword_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as keyword arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_kwargs_function_caller) self.verify_unsafe_email(sensitive_kwargs_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_kwargs_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_kwargs_function_caller, check_for_POST_params=False) def test_callable_settings(self): """ Callable settings should not be evaluated in the debug page (#21345). """ def callable_setting(): return "This should not be displayed" with self.settings(DEBUG=True, FOOBAR=callable_setting): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_callable_settings_forbidding_to_set_attributes(self): """ Callable settings which forbid to set attributes should not break the debug page (#23070). """ class CallableSettingWithSlots: __slots__ = [] def __call__(self): return "This should not be displayed" with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_dict_setting_with_non_str_key(self): """ A dict setting containing a non-string key should not break the debug page (#12744). """ with self.settings(DEBUG=True, FOOBAR={42: None}): response = self.client.get('/raises500/') self.assertContains(response, 'FOOBAR', status_code=500) def test_sensitive_settings(self): """ The debug page should not show some sensitive settings (password, secret key, ...). """ sensitive_settings = [ 'SECRET_KEY', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: with self.settings(DEBUG=True, **{setting: "should not be displayed"}): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) def test_settings_with_sensitive_keys(self): """ The debug page should filter out some sensitive information found in dict settings. """ sensitive_settings = [ 'SECRET_KEY', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: FOOBAR = { setting: "should not be displayed", 'recursive': {setting: "should not be displayed"}, } with self.settings(DEBUG=True, FOOBAR=FOOBAR): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) class AjaxResponseExceptionReporterFilter(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports. Here we specifically test the plain text 500 debug-only error page served when it has been detected the request was sent by JS code. We don't check for (non)existence of frames vars in the traceback information section of the response content because we don't include them in these error pages. Refs #14614. """ rf = RequestFactory(HTTP_X_REQUESTED_WITH='XMLHttpRequest') def test_non_sensitive_request(self): """ Request info can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) def test_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view, check_for_vars=False) def test_paranoid_request(self): """ No POST parameters can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view, check_for_vars=False) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') def test_ajax_response_encoding(self): response = self.client.get('/raises500/', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response['Content-Type'], 'text/plain; charset=utf-8') class HelperFunctionTests(SimpleTestCase): def test_cleanse_setting_basic(self): self.assertEqual(cleanse_setting('TEST', 'TEST'), 'TEST') self.assertEqual(cleanse_setting('PASSWORD', 'super_secret'), CLEANSED_SUBSTITUTE) def test_cleanse_setting_ignore_case(self): self.assertEqual(cleanse_setting('password', 'super_secret'), CLEANSED_SUBSTITUTE) def test_cleanse_setting_recurses_in_dictionary(self): initial = {'login': 'cooper', 'password': 'secret'} expected = {'login': 'cooper', 'password': CLEANSED_SUBSTITUTE} self.assertEqual(cleanse_setting('SETTING_NAME', initial), expected)