repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_multiple/__init__.py
tests/m2m_multiple/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_multiple/tests.py
tests/m2m_multiple/tests.py
from datetime import datetime from django.test import TestCase from .models import Article, Category class M2MMultipleTests(TestCase): def test_multiple(self): c1, c2, c3, c4 = [ Category.objects.create(name=name) for name in ["Sports", "News", "Crime", "Life"] ] a1 = Article.objects.create( headline="Parrot steals", pub_date=datetime(2005, 11, 27) ) a1.primary_categories.add(c2, c3) a1.secondary_categories.add(c4) a2 = Article.objects.create( headline="Parrot runs", pub_date=datetime(2005, 11, 28) ) a2.primary_categories.add(c1, c2) a2.secondary_categories.add(c4) self.assertQuerySetEqual( a1.primary_categories.all(), [ "Crime", "News", ], lambda c: c.name, ) self.assertQuerySetEqual( a2.primary_categories.all(), [ "News", "Sports", ], lambda c: c.name, ) self.assertQuerySetEqual( a1.secondary_categories.all(), [ "Life", ], lambda c: c.name, ) self.assertQuerySetEqual( c1.primary_article_set.all(), [ "Parrot runs", ], lambda a: a.headline, ) self.assertQuerySetEqual(c1.secondary_article_set.all(), []) self.assertQuerySetEqual( c2.primary_article_set.all(), [ "Parrot steals", "Parrot runs", ], lambda a: a.headline, ) self.assertQuerySetEqual(c2.secondary_article_set.all(), []) self.assertQuerySetEqual( c3.primary_article_set.all(), [ "Parrot steals", ], lambda a: a.headline, ) self.assertQuerySetEqual(c3.secondary_article_set.all(), []) self.assertQuerySetEqual(c4.primary_article_set.all(), []) self.assertQuerySetEqual( c4.secondary_article_set.all(), [ "Parrot steals", "Parrot runs", ], lambda a: a.headline, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/known_related_objects/models.py
tests/known_related_objects/models.py
""" Existing related object instance caching. Queries are not redone when going back through known relations. """ from django.db import models class Tournament(models.Model): name = models.CharField(max_length=30) class Organiser(models.Model): name = models.CharField(max_length=30) class Pool(models.Model): name = models.CharField(max_length=30) tournament = models.ForeignKey(Tournament, models.CASCADE) organiser = models.ForeignKey(Organiser, models.CASCADE) class PoolStyle(models.Model): name = models.CharField(max_length=30) pool = models.OneToOneField(Pool, models.CASCADE) another_pool = models.OneToOneField( Pool, models.CASCADE, null=True, related_name="another_style" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/known_related_objects/__init__.py
tests/known_related_objects/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/known_related_objects/tests.py
tests/known_related_objects/tests.py
from django.db.models import FilteredRelation from django.test import TestCase from .models import Organiser, Pool, PoolStyle, Tournament class ExistingRelatedInstancesTests(TestCase): @classmethod def setUpTestData(cls): cls.t1 = Tournament.objects.create(name="Tourney 1") cls.t2 = Tournament.objects.create(name="Tourney 2") cls.o1 = Organiser.objects.create(name="Organiser 1") cls.p1 = Pool.objects.create( name="T1 Pool 1", tournament=cls.t1, organiser=cls.o1 ) cls.p2 = Pool.objects.create( name="T1 Pool 2", tournament=cls.t1, organiser=cls.o1 ) cls.p3 = Pool.objects.create( name="T2 Pool 1", tournament=cls.t2, organiser=cls.o1 ) cls.p4 = Pool.objects.create( name="T2 Pool 2", tournament=cls.t2, organiser=cls.o1 ) cls.ps1 = PoolStyle.objects.create(name="T1 Pool 2 Style", pool=cls.p2) cls.ps2 = PoolStyle.objects.create(name="T2 Pool 1 Style", pool=cls.p3) cls.ps3 = PoolStyle.objects.create( name="T1 Pool 1/3 Style", pool=cls.p1, another_pool=cls.p3 ) def test_foreign_key(self): with self.assertNumQueries(2): tournament = Tournament.objects.get(pk=self.t1.pk) pool = tournament.pool_set.all()[0] self.assertIs(tournament, pool.tournament) def test_foreign_key_prefetch_related(self): with self.assertNumQueries(2): tournament = Tournament.objects.prefetch_related("pool_set").get( pk=self.t1.pk ) pool = tournament.pool_set.all()[0] self.assertIs(tournament, pool.tournament) def test_foreign_key_multiple_prefetch(self): with self.assertNumQueries(2): tournaments = list( Tournament.objects.prefetch_related("pool_set").order_by("pk") ) pool1 = tournaments[0].pool_set.all()[0] self.assertIs(tournaments[0], pool1.tournament) pool2 = tournaments[1].pool_set.all()[0] self.assertIs(tournaments[1], pool2.tournament) def test_queryset_or(self): tournament_1 = self.t1 tournament_2 = self.t2 with self.assertNumQueries(1): pools = tournament_1.pool_set.all() | tournament_2.pool_set.all() related_objects = {pool.tournament for pool in pools} self.assertEqual(related_objects, {tournament_1, tournament_2}) def test_queryset_or_different_cached_items(self): tournament = self.t1 organiser = self.o1 with self.assertNumQueries(1): pools = tournament.pool_set.all() | organiser.pool_set.all() first = pools.filter(pk=self.p1.pk)[0] self.assertIs(first.tournament, tournament) self.assertIs(first.organiser, organiser) def test_queryset_or_only_one_with_precache(self): tournament_1 = self.t1 tournament_2 = self.t2 # 2 queries here as pool 3 has tournament 2, which is not cached with self.assertNumQueries(2): pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=self.p3.pk) related_objects = {pool.tournament for pool in pools} self.assertEqual(related_objects, {tournament_1, tournament_2}) # and the other direction with self.assertNumQueries(2): pools = Pool.objects.filter(pk=self.p3.pk) | tournament_1.pool_set.all() related_objects = {pool.tournament for pool in pools} self.assertEqual(related_objects, {tournament_1, tournament_2}) def test_queryset_and(self): tournament = self.t1 organiser = self.o1 with self.assertNumQueries(1): pools = tournament.pool_set.all() & organiser.pool_set.all() first = pools.filter(pk=self.p1.pk)[0] self.assertIs(first.tournament, tournament) self.assertIs(first.organiser, organiser) def test_one_to_one(self): with self.assertNumQueries(2): style = PoolStyle.objects.get(pk=self.ps1.pk) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_select_related(self): with self.assertNumQueries(1): style = PoolStyle.objects.select_related("pool").get(pk=self.ps1.pk) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_multi_select_related(self): with self.assertNumQueries(1): poolstyles = list(PoolStyle.objects.select_related("pool").order_by("pk")) self.assertIs(poolstyles[0], poolstyles[0].pool.poolstyle) self.assertIs(poolstyles[1], poolstyles[1].pool.poolstyle) def test_one_to_one_prefetch_related(self): with self.assertNumQueries(2): style = PoolStyle.objects.prefetch_related("pool").get(pk=self.ps1.pk) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_multi_prefetch_related(self): with self.assertNumQueries(2): poolstyles = list(PoolStyle.objects.prefetch_related("pool").order_by("pk")) self.assertIs(poolstyles[0], poolstyles[0].pool.poolstyle) self.assertIs(poolstyles[1], poolstyles[1].pool.poolstyle) def test_reverse_one_to_one(self): with self.assertNumQueries(2): pool = Pool.objects.get(pk=self.p2.pk) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_select_related(self): with self.assertNumQueries(1): pool = Pool.objects.select_related("poolstyle").get(pk=self.p2.pk) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_prefetch_related(self): with self.assertNumQueries(2): pool = Pool.objects.prefetch_related("poolstyle").get(pk=self.p2.pk) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_multi_select_related(self): with self.assertNumQueries(1): pools = list(Pool.objects.select_related("poolstyle").order_by("pk")) self.assertIs(pools[1], pools[1].poolstyle.pool) self.assertIs(pools[2], pools[2].poolstyle.pool) def test_reverse_one_to_one_multi_prefetch_related(self): with self.assertNumQueries(2): pools = list(Pool.objects.prefetch_related("poolstyle").order_by("pk")) self.assertIs(pools[1], pools[1].poolstyle.pool) self.assertIs(pools[2], pools[2].poolstyle.pool) def test_reverse_fk_select_related_multiple(self): with self.assertNumQueries(1): ps = list( PoolStyle.objects.annotate( pool_1=FilteredRelation("pool"), pool_2=FilteredRelation("another_pool"), ) .select_related("pool_1", "pool_2") .order_by("-pk") ) self.assertIs(ps[0], ps[0].pool_1.poolstyle) self.assertIs(ps[0], ps[0].pool_2.another_style) def test_multilevel_reverse_fk_cyclic_select_related(self): with self.assertNumQueries(3): p = list( PoolStyle.objects.annotate( tournament_pool=FilteredRelation("pool__tournament__pool"), ).select_related("tournament_pool", "tournament_pool__tournament") ) self.assertEqual(p[0].tournament_pool.tournament, p[0].pool.tournament) def test_multilevel_reverse_fk_select_related(self): with self.assertNumQueries(2): p = list( Tournament.objects.filter(id=self.t2.id) .annotate( style=FilteredRelation("pool__another_style"), ) .select_related("style") ) self.assertEqual(p[0].style.another_pool, self.p3)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/sites_tests/__init__.py
tests/sites_tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/sites_tests/tests.py
tests/sites_tests/tests.py
from django.apps import apps from django.apps.registry import Apps from django.conf import settings from django.contrib.sites import models from django.contrib.sites.checks import check_site_id from django.contrib.sites.management import create_default_site from django.contrib.sites.middleware import CurrentSiteMiddleware from django.contrib.sites.models import Site, clear_site_cache from django.contrib.sites.requests import RequestSite from django.contrib.sites.shortcuts import get_current_site from django.core import checks from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db.models.signals import post_migrate from django.http import HttpRequest, HttpResponse from django.test import SimpleTestCase, TestCase, modify_settings, override_settings from django.test.utils import captured_stdout @modify_settings(INSTALLED_APPS={"append": "django.contrib.sites"}) class SitesFrameworkTests(TestCase): databases = {"default", "other"} @classmethod def setUpTestData(cls): cls.site = Site(id=settings.SITE_ID, domain="example.com", name="example.com") cls.site.save() def setUp(self): Site.objects.clear_cache() self.addCleanup(Site.objects.clear_cache) def test_site_manager(self): # Make sure that get_current() does not return a deleted Site object. s = Site.objects.get_current() self.assertIsInstance(s, Site) s.delete() with self.assertRaises(ObjectDoesNotExist): Site.objects.get_current() def test_site_cache(self): # After updating a Site object (e.g. via the admin), we shouldn't # return a bogus value from the SITE_CACHE. site = Site.objects.get_current() self.assertEqual("example.com", site.name) s2 = Site.objects.get(id=settings.SITE_ID) s2.name = "Example site" s2.save() site = Site.objects.get_current() self.assertEqual("Example site", site.name) def test_delete_all_sites_clears_cache(self): # When all site objects are deleted the cache should also # be cleared and get_current() should raise a DoesNotExist. self.assertIsInstance(Site.objects.get_current(), Site) Site.objects.all().delete() with self.assertRaises(Site.DoesNotExist): Site.objects.get_current() @override_settings(ALLOWED_HOSTS=["example.com"]) def test_get_current_site(self): # The correct Site object is returned request = HttpRequest() request.META = { "SERVER_NAME": "example.com", "SERVER_PORT": "80", } site = get_current_site(request) self.assertIsInstance(site, Site) self.assertEqual(site.id, settings.SITE_ID) # An exception is raised if the sites framework is installed # but there is no matching Site site.delete() with self.assertRaises(ObjectDoesNotExist): get_current_site(request) # A RequestSite is returned if the sites framework is not installed with self.modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"}): site = get_current_site(request) self.assertIsInstance(site, RequestSite) self.assertEqual(site.name, "example.com") @override_settings(SITE_ID=None, ALLOWED_HOSTS=["example.com"]) def test_get_current_site_no_site_id(self): request = HttpRequest() request.META = { "SERVER_NAME": "example.com", "SERVER_PORT": "80", } del settings.SITE_ID site = get_current_site(request) self.assertEqual(site.name, "example.com") @override_settings(SITE_ID=None, ALLOWED_HOSTS=["example.com"]) def test_get_current_site_host_with_trailing_dot(self): """ The site is matched if the name in the request has a trailing dot. """ request = HttpRequest() request.META = { "SERVER_NAME": "example.com.", "SERVER_PORT": "80", } site = get_current_site(request) self.assertEqual(site.name, "example.com") @override_settings(SITE_ID=None, ALLOWED_HOSTS=["example.com", "example.net"]) def test_get_current_site_no_site_id_and_handle_port_fallback(self): request = HttpRequest() s1 = self.site s2 = Site.objects.create(domain="example.com:80", name="example.com:80") # Host header without port request.META = {"HTTP_HOST": "example.com"} site = get_current_site(request) self.assertEqual(site, s1) # Host header with port - match, no fallback without port request.META = {"HTTP_HOST": "example.com:80"} site = get_current_site(request) self.assertEqual(site, s2) # Host header with port - no match, fallback without port request.META = {"HTTP_HOST": "example.com:81"} site = get_current_site(request) self.assertEqual(site, s1) # Host header with non-matching domain request.META = {"HTTP_HOST": "example.net"} with self.assertRaises(ObjectDoesNotExist): get_current_site(request) # Ensure domain for RequestSite always matches host header with self.modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"}): request.META = {"HTTP_HOST": "example.com"} site = get_current_site(request) self.assertEqual(site.name, "example.com") request.META = {"HTTP_HOST": "example.com:80"} site = get_current_site(request) self.assertEqual(site.name, "example.com:80") def test_domain_name_with_whitespaces(self): # Regression for #17320 # Domain names are not allowed contain whitespace characters site = Site(name="test name", domain="test test") with self.assertRaises(ValidationError): site.full_clean() site.domain = "test\ttest" with self.assertRaises(ValidationError): site.full_clean() site.domain = "test\ntest" with self.assertRaises(ValidationError): site.full_clean() @override_settings(ALLOWED_HOSTS=["example.com"]) def test_clear_site_cache(self): request = HttpRequest() request.META = { "SERVER_NAME": "example.com", "SERVER_PORT": "80", } self.assertEqual(models.SITE_CACHE, {}) get_current_site(request) expected_cache = {self.site.id: self.site} self.assertEqual(models.SITE_CACHE, expected_cache) with self.settings(SITE_ID=None): get_current_site(request) expected_cache.update({self.site.domain: self.site}) self.assertEqual(models.SITE_CACHE, expected_cache) clear_site_cache(Site, instance=self.site, using="default") self.assertEqual(models.SITE_CACHE, {}) @override_settings(SITE_ID=None, ALLOWED_HOSTS=["example2.com"]) def test_clear_site_cache_domain(self): site = Site.objects.create(name="example2.com", domain="example2.com") request = HttpRequest() request.META = { "SERVER_NAME": "example2.com", "SERVER_PORT": "80", } get_current_site(request) # prime the models.SITE_CACHE expected_cache = {site.domain: site} self.assertEqual(models.SITE_CACHE, expected_cache) # Site exists in 'default' database so using='other' shouldn't clear. clear_site_cache(Site, instance=site, using="other") self.assertEqual(models.SITE_CACHE, expected_cache) # using='default' should clear. clear_site_cache(Site, instance=site, using="default") self.assertEqual(models.SITE_CACHE, {}) def test_unique_domain(self): site = Site(domain=self.site.domain) msg = "Site with this Domain name already exists." with self.assertRaisesMessage(ValidationError, msg): site.validate_unique() def test_site_natural_key(self): self.assertEqual(Site.objects.get_by_natural_key(self.site.domain), self.site) self.assertEqual(self.site.natural_key(), (self.site.domain,)) @override_settings(SITE_ID="1") def test_check_site_id(self): self.assertEqual( check_site_id(None), [ checks.Error( msg="The SITE_ID setting must be an integer", id="sites.E101", ), ], ) def test_valid_site_id(self): for site_id in [1, None]: with self.subTest(site_id=site_id), self.settings(SITE_ID=site_id): self.assertEqual(check_site_id(None), []) @override_settings(ALLOWED_HOSTS=["example.com"]) class RequestSiteTests(SimpleTestCase): def setUp(self): request = HttpRequest() request.META = {"HTTP_HOST": "example.com"} self.site = RequestSite(request) def test_init_attributes(self): self.assertEqual(self.site.domain, "example.com") self.assertEqual(self.site.name, "example.com") def test_str(self): self.assertEqual(str(self.site), "example.com") def test_save(self): msg = "RequestSite cannot be saved." with self.assertRaisesMessage(NotImplementedError, msg): self.site.save() def test_delete(self): msg = "RequestSite cannot be deleted." with self.assertRaisesMessage(NotImplementedError, msg): self.site.delete() class JustOtherRouter: def allow_migrate(self, db, app_label, **hints): return db == "other" @modify_settings(INSTALLED_APPS={"append": "django.contrib.sites"}) class CreateDefaultSiteTests(TestCase): databases = {"default", "other"} @classmethod def setUpTestData(cls): # Delete the site created as part of the default migration process. Site.objects.all().delete() def setUp(self): self.app_config = apps.get_app_config("sites") def test_basic(self): """ #15346, #15573 - create_default_site() creates an example site only if none exist. """ with captured_stdout() as stdout: create_default_site(self.app_config) self.assertEqual(Site.objects.count(), 1) self.assertIn("Creating example.com", stdout.getvalue()) with captured_stdout() as stdout: create_default_site(self.app_config) self.assertEqual(Site.objects.count(), 1) self.assertEqual("", stdout.getvalue()) @override_settings(DATABASE_ROUTERS=[JustOtherRouter()]) def test_multi_db_with_router(self): """ #16353, #16828 - The default site creation should respect db routing. """ create_default_site(self.app_config, using="default", verbosity=0) create_default_site(self.app_config, using="other", verbosity=0) self.assertFalse(Site.objects.using("default").exists()) self.assertTrue(Site.objects.using("other").exists()) def test_multi_db(self): create_default_site(self.app_config, using="default", verbosity=0) create_default_site(self.app_config, using="other", verbosity=0) self.assertTrue(Site.objects.using("default").exists()) self.assertTrue(Site.objects.using("other").exists()) def test_save_another(self): """ #17415 - Another site can be created right after the default one. On some backends the sequence needs to be reset after saving with an explicit ID. There shouldn't be a sequence collisions by saving another site. This test is only meaningful with databases that use sequences for automatic primary keys such as PostgreSQL and Oracle. """ create_default_site(self.app_config, verbosity=0) Site(domain="example2.com", name="example2.com").save() def test_signal(self): """ #23641 - Sending the ``post_migrate`` signal triggers creation of the default site. """ post_migrate.send( sender=self.app_config, app_config=self.app_config, verbosity=0 ) self.assertTrue(Site.objects.exists()) @override_settings(SITE_ID=35696) def test_custom_site_id(self): """ #23945 - The configured ``SITE_ID`` should be respected. """ create_default_site(self.app_config, verbosity=0) self.assertEqual(Site.objects.get().pk, 35696) @override_settings() # Restore original ``SITE_ID`` afterward. def test_no_site_id(self): """ #24488 - The pk should default to 1 if no ``SITE_ID`` is configured. """ del settings.SITE_ID create_default_site(self.app_config, verbosity=0) self.assertEqual(Site.objects.get().pk, 1) def test_unavailable_site_model(self): """ #24075 - A Site shouldn't be created if the model isn't available. """ apps = Apps() create_default_site(self.app_config, verbosity=0, apps=apps) self.assertFalse(Site.objects.exists()) class MiddlewareTest(TestCase): def test_request(self): def get_response(request): return HttpResponse(str(request.site.id)) response = CurrentSiteMiddleware(get_response)(HttpRequest()) self.assertContains(response, settings.SITE_ID)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/configured_settings_manage.py
tests/admin_scripts/configured_settings_manage.py
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if __name__ == "__main__": settings.configure(DEBUG=True, CUSTOM=1) execute_from_command_line(sys.argv)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/configured_dynamic_settings_manage.py
tests/admin_scripts/configured_dynamic_settings_manage.py
#!/usr/bin/env python import sys from django.conf import global_settings, settings from django.core.management import execute_from_command_line class Settings: def __getattr__(self, name): if name == "FOO": return "bar" return getattr(global_settings, name) def __dir__(self): return super().__dir__() + dir(global_settings) + ["FOO"] if __name__ == "__main__": settings.configure(Settings()) execute_from_command_line(sys.argv)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/__init__.py
tests/admin_scripts/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/tests.py
tests/admin_scripts/tests.py
""" A series of tests to establish that the command-line management tools work as advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ import os import re import shutil import socket import stat import subprocess import sys import tempfile import unittest from io import StringIO from unittest import mock from user_commands.utils import AssertFormatterFailureCaughtContext from django import conf, get_version from django.conf import settings from django.core.checks import Error, Tags, register from django.core.checks.registry import registry from django.core.management import ( BaseCommand, CommandError, call_command, color, execute_from_command_line, ) from django.core.management.base import LabelCommand, SystemCheckError from django.core.management.commands.loaddata import Command as LoaddataCommand from django.core.management.commands.runserver import Command as RunserverCommand from django.core.management.commands.testserver import Command as TestserverCommand from django.db import ConnectionHandler, connection from django.db.migrations.recorder import MigrationRecorder from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings from django.test.utils import captured_stderr, captured_stdout from django.urls import path from django.utils.version import PY313, PY314, get_docs_version from django.views.static import serve from . import urls custom_templates_dir = os.path.join(os.path.dirname(__file__), "custom_templates") SYSTEM_CHECK_MSG = "System check identified no issues" HAS_BLACK = shutil.which("black") class AdminScriptTestCase(SimpleTestCase): def setUp(self): tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) # os.path.realpath() is required for temporary directories on macOS, # where `/var` is a symlink to `/private/var`. self.test_dir = os.path.realpath(os.path.join(tmpdir.name, "test_project")) os.mkdir(self.test_dir) def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None): if is_dir: settings_dir = os.path.join(self.test_dir, filename) os.mkdir(settings_dir) settings_file_path = os.path.join(settings_dir, "__init__.py") else: settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, "w") as settings_file: settings_file.write( "# Settings file automatically generated by admin_scripts test case\n" ) if extra: settings_file.write("%s\n" % extra) exports = [ "DATABASES", "ROOT_URLCONF", "SECRET_KEY", "USE_TZ", ] for s in exports: if hasattr(settings, s): o = getattr(settings, s) if not isinstance(o, (dict, tuple, list)): o = "'%s'" % o settings_file.write("%s = %s\n" % (s, o)) if apps is None: apps = [ "django.contrib.auth", "django.contrib.contenttypes", "admin_scripts", ] settings_file.write("INSTALLED_APPS = %s\n" % apps) if sdict: for k, v in sdict.items(): settings_file.write("%s = %s\n" % (k, v)) def _ext_backend_paths(self): """ Returns the paths for any external backend packages. """ paths = [] for backend in settings.DATABASES.values(): package = backend["ENGINE"].split(".")[0] if package != "django": backend_pkg = __import__(package) backend_dir = os.path.dirname(backend_pkg.__file__) paths.append(os.path.dirname(backend_dir)) return paths def run_test(self, args, settings_file=None, apps=None, umask=-1): base_dir = os.path.dirname(self.test_dir) # The base dir for Django's tests is one level up. tests_dir = os.path.dirname(os.path.dirname(__file__)) # The base dir for Django is one level above the test dir. We don't use # `import django` to figure that out, so we don't pick up a Django # from site-packages or similar. django_dir = os.path.dirname(tests_dir) ext_backend_base_dirs = self._ext_backend_paths() # Define a temporary environment for the subprocess test_environ = os.environ.copy() # Set the test environment if settings_file: test_environ["DJANGO_SETTINGS_MODULE"] = settings_file elif "DJANGO_SETTINGS_MODULE" in test_environ: del test_environ["DJANGO_SETTINGS_MODULE"] python_path = [base_dir, django_dir, tests_dir] python_path.extend(ext_backend_base_dirs) test_environ["PYTHONPATH"] = os.pathsep.join(python_path) test_environ["PYTHONWARNINGS"] = "" p = subprocess.run( [sys.executable, *args], capture_output=True, cwd=self.test_dir, env=test_environ, text=True, umask=umask, ) return p.stdout, p.stderr def run_django_admin(self, args, settings_file=None, umask=-1): return self.run_test(["-m", "django", *args], settings_file, umask=umask) def run_manage(self, args, settings_file=None, manage_py=None): template_manage_py = ( os.path.join(os.path.dirname(__file__), manage_py) if manage_py else os.path.join( os.path.dirname(conf.__file__), "project_template", "manage.py-tpl" ) ) test_manage_py = os.path.join(self.test_dir, "manage.py") shutil.copyfile(template_manage_py, test_manage_py) with open(test_manage_py) as fp: manage_py_contents = fp.read() manage_py_contents = manage_py_contents.replace( "{{ project_name }}", "test_project" ) with open(test_manage_py, "w") as fp: fp.write(manage_py_contents) return self.run_test(["./manage.py", *args], settings_file) def assertInAfterFormatting(self, member, container, msg=None): if HAS_BLACK: import black # Black does not have a stable API, but this is still less fragile # than attempting to filter out all paths where it is available. member = black.format_str(member, mode=black.FileMode()) self.assertIn(member, container, msg=msg) def assertNoOutput(self, stream): "Utility assertion: assert that the given stream is empty" self.assertEqual( len(stream), 0, "Stream should be empty: actually contains '%s'" % stream ) def assertOutput(self, stream, msg, regex=False): "Utility assertion: assert that the given message exists in the output" if regex: self.assertIsNotNone( re.search(msg, stream), "'%s' does not match actual output text '%s'" % (msg, stream), ) else: self.assertIn( msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream), ) def assertNotInOutput(self, stream, msg): """ Utility assertion: assert that the given message doesn't exist in the output """ self.assertNotIn( msg, stream, "'%s' matches actual output text '%s'" % (msg, stream) ) ########################################################################## # DJANGO ADMIN TESTS # This first series of test classes checks the environment processing # of the django-admin. ########################################################################## class DjangoAdminNoSettings(AdminScriptTestCase): "A series of tests for django-admin when there is no settings.py file." def test_builtin_command(self): """ no settings: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_bad_settings(self): """ no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_commands_with_invalid_settings(self): """ Commands that don't require settings succeed if the settings file doesn't exist. """ args = ["startproject"] out, err = self.run_django_admin(args, settings_file="bad_settings") self.assertNoOutput(out) self.assertOutput(err, "You must provide a project name", regex=True) class DjangoAdminDefaultSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings("settings.py") def test_builtin_command(self): """ default: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ default: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ default: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ default: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ default: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ default: django-admin can't execute user commands if it isn't provided settings. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ default: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ default: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings( "settings.py", [ "django.contrib.auth", "django.contrib.contenttypes", "admin_scripts", "admin_scripts.complex_app", ], ) def test_builtin_command(self): """ fulldefault: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ fulldefault: django-admin builtin commands succeed if a settings file is provided. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ fulldefault: django-admin builtin commands succeed if the environment contains settings. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ fulldefault: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ fulldefault: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ fulldefault: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMinimalSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) def test_builtin_command(self): """ minimal: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ minimal: django-admin builtin commands fail if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): """ minimal: django-admin builtin commands fail if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): """ minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ minimal: django-admin can't execute user commands unless settings are provided """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ minimal: django-admin can't execute user commands, even if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): """ minimal: django-admin can't execute user commands, even if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class DjangoAdminAlternateSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings("alternate_settings.py") def test_builtin_command(self): """ alternate: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ alternate: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ alternate: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ alternate: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ alternate: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.alternate_settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ alternate: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMultipleSettings(AdminScriptTestCase): """ A series of tests for django-admin when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) self.write_settings("alternate_settings.py") def test_builtin_command(self): """ alternate: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ alternate: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ alternate: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ alternate: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ alternate: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.alternate_settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ alternate: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminSettingsDirectory(AdminScriptTestCase): """ A series of tests for django-admin when the settings file is in a directory. (see #9751). """ def setUp(self): super().setUp() self.write_settings("settings", is_dir=True) def test_setup_environ(self): "directory: startapp creates the correct directory" args = ["startapp", "settings_test"] app_path = os.path.join(self.test_dir, "settings_test") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, "apps.py")) as f: content = f.read() self.assertIn("class SettingsTestConfig(AppConfig)", content) self.assertInAfterFormatting("name = 'settings_test'", content) def test_setup_environ_custom_template(self): """ directory: startapp creates the correct directory with a custom template """ template_path = os.path.join(custom_templates_dir, "app_template") args = ["startapp", "--template", template_path, "custom_settings_test"] app_path = os.path.join(self.test_dir, "custom_settings_test") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) self.assertTrue(os.path.exists(os.path.join(app_path, "api.py"))) def test_startapp_unicode_name(self): """startapp creates the correct directory with Unicode characters.""" args = ["startapp", "こんにちは"] app_path = os.path.join(self.test_dir, "こんにちは") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, "apps.py"), encoding="utf8") as f: content = f.read() self.assertIn("class こんにちはConfig(AppConfig)", content) self.assertInAfterFormatting("name = 'こんにちは'", content) def test_builtin_command(self): """ directory: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_bad_settings(self): """ directory: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ directory: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ directory: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_builtin_with_settings(self): """ directory: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ directory: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) ########################################################################## # MANAGE.PY TESTS # This next series of test classes checks the environment processing # of the generated manage.py script ########################################################################## class ManageManuallyConfiguredSettings(AdminScriptTestCase): """Customized manage.py calling settings.configure().""" def test_non_existent_command_output(self): out, err = self.run_manage( ["invalid_command"], manage_py="configured_settings_manage.py" ) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'invalid_command'") self.assertNotInOutput(err, "No Django settings specified") class ManageNoSettings(AdminScriptTestCase): "A series of tests for manage.py when there is no settings.py file." def test_builtin_command(self): """ no settings: manage.py builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/urls.py
tests/admin_scripts/urls.py
import os from django.urls import path from django.views.static import serve here = os.path.dirname(__file__) urlpatterns = [ path( "custom_templates/<path:path>", serve, {"document_root": os.path.join(here, "custom_templates")}, ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/custom_templates/app_template/api.py
tests/admin_scripts/custom_templates/app_template/api.py
# your API code
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/custom_templates/app_template/__init__.py
tests/admin_scripts/custom_templates/app_template/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/custom_templates/project_template/.hidden/render.py
tests/admin_scripts/custom_templates/project_template/.hidden/render.py
# The {{ project_name }} should be rendered.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/custom_templates/project_template/additional_dir/additional_file.py
tests/admin_scripts/custom_templates/project_template/additional_dir/additional_file.py
# some file for {{ project_name }} test project
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/custom_templates/project_template/additional_dir/extra.py
tests/admin_scripts/custom_templates/project_template/additional_dir/extra.py
# this file uses the {{ extra }} variable
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/custom_templates/project_template/additional_dir/localized.py
tests/admin_scripts/custom_templates/project_template/additional_dir/localized.py
# Regression for #22699. # Generated at {% now "DATE_FORMAT" %}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/custom_templates/project_template/project_name/settings.py
tests/admin_scripts/custom_templates/project_template/project_name/settings.py
# Django settings for {{ project_name }} test project.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/custom_templates/project_template/project_name/__init__.py
tests/admin_scripts/custom_templates/project_template/project_name/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/management/__init__.py
tests/admin_scripts/management/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/management/commands/custom_startproject.py
tests/admin_scripts/management/commands/custom_startproject.py
from django.core.management.commands.startproject import Command as BaseCommand class Command(BaseCommand): def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "--extra", help="An arbitrary extra value passed to the context" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/management/commands/noargs_command.py
tests/admin_scripts/management/commands/noargs_command.py
from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Test No-args commands" requires_system_checks = [] def handle(self, **options): print("EXECUTE: noargs_command options=%s" % sorted(options.items()))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/management/commands/app_command.py
tests/admin_scripts/management/commands/app_command.py
from django.core.management.base import AppCommand class Command(AppCommand): help = "Test Application-based commands" requires_system_checks = [] def handle_app_config(self, app_config, **options): print( "EXECUTE:AppCommand name=%s, options=%s" % (app_config.name, sorted(options.items())) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/management/commands/base_command.py
tests/admin_scripts/management/commands/base_command.py
from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Test basic commands" requires_system_checks = [] def add_arguments(self, parser): parser.add_argument("args", nargs="*") parser.add_argument("--option_a", "-a", default="1") parser.add_argument("--option_b", "-b", default="2") parser.add_argument("--option_c", "-c", default="3") def handle(self, *labels, **options): print( "EXECUTE:BaseCommand labels=%s, options=%s" % (labels, sorted(options.items())) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/management/commands/label_command.py
tests/admin_scripts/management/commands/label_command.py
from django.core.management.base import LabelCommand class Command(LabelCommand): help = "Test Label-based commands" requires_system_checks = [] def handle_label(self, label, **options): print( "EXECUTE:LabelCommand label=%s, options=%s" % (label, sorted(options.items())) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/management/commands/__init__.py
tests/admin_scripts/management/commands/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/management/commands/suppress_base_options_command.py
tests/admin_scripts/management/commands/suppress_base_options_command.py
from django.core.management import BaseCommand class Command(BaseCommand): help = "Test suppress base options command." requires_system_checks = [] suppressed_base_arguments = { "-v", "--traceback", "--settings", "--pythonpath", "--no-color", "--force-color", "--version", "file", } def add_arguments(self, parser): super().add_arguments(parser) self.add_base_argument(parser, "file", nargs="?", help="input file") def handle(self, *labels, **options): print("EXECUTE:SuppressBaseOptionsCommand options=%s" % sorted(options.items()))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/broken_app/models.py
tests/admin_scripts/broken_app/models.py
from django.db import modelz # NOQA
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/broken_app/__init__.py
tests/admin_scripts/broken_app/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_with_import/models.py
tests/admin_scripts/app_with_import/models.py
from django.contrib.auth.models import User from django.db import models # Regression for #13368. This is an example of a model # that imports a class that has an abstract base class. class UserProfile(models.Model): user = models.OneToOneField(User, models.CASCADE, primary_key=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_with_import/__init__.py
tests/admin_scripts/app_with_import/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/simple_app/models.py
tests/admin_scripts/simple_app/models.py
from ..complex_app.models.bar import Bar __all__ = ["Bar"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/simple_app/__init__.py
tests/admin_scripts/simple_app/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/simple_app/management/__init__.py
tests/admin_scripts/simple_app/management/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/simple_app/management/commands/duplicate.py
tests/admin_scripts/simple_app/management/commands/duplicate.py
from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, **options): self.stdout.write("simple_app")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/simple_app/management/commands/__init__.py
tests/admin_scripts/simple_app/management/commands/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_raising_messages/models.py
tests/admin_scripts/app_raising_messages/models.py
from django.core import checks from django.db import models class ModelRaisingMessages(models.Model): @classmethod def check(self, **kwargs): return [ checks.Warning("First warning", hint="Hint", obj="obj"), checks.Warning("Second warning", obj="a"), checks.Error("An error", hint="Error hint"), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_raising_messages/__init__.py
tests/admin_scripts/app_raising_messages/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_raising_warning/models.py
tests/admin_scripts/app_raising_warning/models.py
from django.core import checks from django.db import models class ModelRaisingMessages(models.Model): @classmethod def check(self, **kwargs): return [checks.Warning("A warning")]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_raising_warning/__init__.py
tests/admin_scripts/app_raising_warning/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/another_app_waiting_migration/models.py
tests/admin_scripts/another_app_waiting_migration/models.py
from django.db import models class Foo(models.Model): name = models.CharField(max_length=255) class Meta: app_label = "another_app_waiting_migration"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/another_app_waiting_migration/__init__.py
tests/admin_scripts/another_app_waiting_migration/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/another_app_waiting_migration/migrations/0001_initial.py
tests/admin_scripts/another_app_waiting_migration/migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Foo", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=255)), ], ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/another_app_waiting_migration/migrations/__init__.py
tests/admin_scripts/another_app_waiting_migration/migrations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_waiting_migration/models.py
tests/admin_scripts/app_waiting_migration/models.py
from django.db import models class Bar(models.Model): name = models.CharField(max_length=255) class Meta: app_label = "app_waiting_migration"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_waiting_migration/__init__.py
tests/admin_scripts/app_waiting_migration/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_waiting_migration/migrations/0001_initial.py
tests/admin_scripts/app_waiting_migration/migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Bar", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=255)), ], ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/app_waiting_migration/migrations/__init__.py
tests/admin_scripts/app_waiting_migration/migrations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/__init__.py
tests/admin_scripts/complex_app/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/management/__init__.py
tests/admin_scripts/complex_app/management/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/management/commands/duplicate.py
tests/admin_scripts/complex_app/management/commands/duplicate.py
from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, **options): self.stdout.write("complex_app")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/management/commands/__init__.py
tests/admin_scripts/complex_app/management/commands/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/admin/foo.py
tests/admin_scripts/complex_app/admin/foo.py
from django.contrib import admin from ..models.foo import Foo admin.site.register(Foo)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/admin/__init__.py
tests/admin_scripts/complex_app/admin/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/models/bar.py
tests/admin_scripts/complex_app/models/bar.py
from django.db import models class Bar(models.Model): name = models.CharField(max_length=5) class Meta: app_label = "complex_app"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/models/foo.py
tests/admin_scripts/complex_app/models/foo.py
from django.db import models class Foo(models.Model): name = models.CharField(max_length=5) class Meta: app_label = "complex_app"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_scripts/complex_app/models/__init__.py
tests/admin_scripts/complex_app/models/__init__.py
from .bar import Bar from .foo import Foo __all__ = ["Foo", "Bar"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/modeladmin/test_actions.py
tests/modeladmin/test_actions.py
from django.contrib import admin from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import TestCase from .models import Band class AdminActionsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) content_type = ContentType.objects.get_for_model(Band) Permission.objects.create( name="custom", codename="custom_band", content_type=content_type ) for user_type in ("view", "add", "change", "delete", "custom"): username = "%suser" % user_type user = User.objects.create_user( username=username, password="secret", is_staff=True ) permission = Permission.objects.get( codename="%s_band" % user_type, content_type=content_type ) user.user_permissions.add(permission) setattr(cls, username, user) def test_get_actions_respects_permissions(self): class MockRequest: pass class BandAdmin(admin.ModelAdmin): actions = ["custom_action"] @admin.action def custom_action(modeladmin, request, queryset): pass def has_custom_permission(self, request): return request.user.has_perm("%s.custom_band" % self.opts.app_label) ma = BandAdmin(Band, admin.AdminSite()) mock_request = MockRequest() mock_request.GET = {} cases = [ (None, self.viewuser, ["custom_action"]), ("view", self.superuser, ["delete_selected", "custom_action"]), ("view", self.viewuser, ["custom_action"]), ("add", self.adduser, ["custom_action"]), ("change", self.changeuser, ["custom_action"]), ("delete", self.deleteuser, ["delete_selected", "custom_action"]), ("custom", self.customuser, ["custom_action"]), ] for permission, user, expected in cases: with self.subTest(permission=permission, user=user): if permission is None: if hasattr(BandAdmin.custom_action, "allowed_permissions"): del BandAdmin.custom_action.allowed_permissions else: BandAdmin.custom_action.allowed_permissions = (permission,) mock_request.user = user actions = ma.get_actions(mock_request) self.assertEqual(list(actions.keys()), expected) def test_actions_inheritance(self): class AdminBase(admin.ModelAdmin): actions = ["custom_action"] @admin.action def custom_action(modeladmin, request, queryset): pass class AdminA(AdminBase): pass class AdminB(AdminBase): actions = None ma1 = AdminA(Band, admin.AdminSite()) action_names = [name for _, name, _ in ma1._get_base_actions()] self.assertEqual(action_names, ["delete_selected", "custom_action"]) # `actions = None` removes actions from superclasses. ma2 = AdminB(Band, admin.AdminSite()) action_names = [name for _, name, _ in ma2._get_base_actions()] self.assertEqual(action_names, ["delete_selected"]) def test_global_actions_description(self): @admin.action(description="Site-wide admin action 1.") def global_action_1(modeladmin, request, queryset): pass @admin.action def global_action_2(modeladmin, request, queryset): pass admin_site = admin.AdminSite() admin_site.add_action(global_action_1) admin_site.add_action(global_action_2) class BandAdmin(admin.ModelAdmin): pass ma = BandAdmin(Band, admin_site) self.assertEqual( [description for _, _, description in ma._get_base_actions()], [ "Delete selected %(verbose_name_plural)s", "Site-wide admin action 1.", "Global action 2", ], ) def test_actions_replace_global_action(self): @admin.action(description="Site-wide admin action 1.") def global_action_1(modeladmin, request, queryset): pass @admin.action(description="Site-wide admin action 2.") def global_action_2(modeladmin, request, queryset): pass admin.site.add_action(global_action_1, name="custom_action_1") admin.site.add_action(global_action_2, name="custom_action_2") @admin.action(description="Local admin action 1.") def custom_action_1(modeladmin, request, queryset): pass class BandAdmin(admin.ModelAdmin): actions = [custom_action_1, "custom_action_2"] @admin.action(description="Local admin action 2.") def custom_action_2(self, request, queryset): pass ma = BandAdmin(Band, admin.site) self.assertEqual(ma.check(), []) self.assertEqual( [ desc for _, name, desc in ma._get_base_actions() if name.startswith("custom_action") ], [ "Local admin action 1.", "Local admin action 2.", ], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/modeladmin/test_checks.py
tests/modeladmin/test_checks.py
from django import forms from django.contrib import admin from django.contrib.admin import BooleanFieldListFilter, SimpleListFilter from django.contrib.admin.options import VERTICAL, ModelAdmin, TabularInline from django.contrib.admin.sites import AdminSite from django.core.checks import Error from django.db import models from django.db.models import CASCADE, F, Field, ForeignKey, ManyToManyField, Model from django.db.models.functions import Upper from django.forms.models import BaseModelFormSet from django.test import TestCase, skipUnlessDBFeature from django.test.utils import isolate_apps from .models import Band, Song, User, ValidationTestInlineModel, ValidationTestModel class CheckTestCase(TestCase): def assertIsInvalid( self, model_admin, model, msg, id=None, hint=None, invalid_obj=None, admin_site=None, ): if admin_site is None: admin_site = AdminSite() invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, admin_site) self.assertEqual( admin_obj.check(), [Error(msg, hint=hint, obj=invalid_obj, id=id)] ) def assertIsInvalidRegexp( self, model_admin, model, msg, id=None, hint=None, invalid_obj=None ): """ Same as assertIsInvalid but treats the given msg as a regexp. """ invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, AdminSite()) errors = admin_obj.check() self.assertEqual(len(errors), 1) error = errors[0] self.assertEqual(error.hint, hint) self.assertEqual(error.obj, invalid_obj) self.assertEqual(error.id, id) self.assertRegex(error.msg, msg) def assertIsValid(self, model_admin, model, admin_site=None): if admin_site is None: admin_site = AdminSite() admin_obj = model_admin(model, admin_site) self.assertEqual(admin_obj.check(), []) class RawIdCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): raw_id_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields' must be a list or tuple.", "admin.E001", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ["non_existent_field"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E002", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' must be a foreign key or a " "many-to-many field.", "admin.E003", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) @isolate_apps("modeladmin") def assertGeneratedDateTimeFieldIsValid(self, *, db_persist): class TestModel(Model): date = models.DateTimeField() date_copy = models.GeneratedField( expression=F("date"), output_field=models.DateTimeField(), db_persist=db_persist, ) class TestModelAdmin(ModelAdmin): date_hierarchy = "date_copy" self.assertIsValid(TestModelAdmin, TestModel) @skipUnlessDBFeature("supports_stored_generated_columns") def test_valid_case_stored_generated_field(self): self.assertGeneratedDateTimeFieldIsValid(db_persist=True) @skipUnlessDBFeature("supports_virtual_generated_columns") def test_valid_case_virtual_generated_field(self): self.assertGeneratedDateTimeFieldIsValid(db_persist=False) def test_field_attname(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ["band_id"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' refers to 'band_id', which is " "not a field of 'modeladmin.ValidationTestModel'.", "admin.E002", ) class FieldsetsCheckTests(CheckTestCase): def test_valid_case(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_not_iterable(self): class TestModelAdmin(ModelAdmin): fieldsets = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets' must be a list or tuple.", "admin.E007", ) def test_non_iterable_item(self): class TestModelAdmin(ModelAdmin): fieldsets = ({},) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be a list or tuple.", "admin.E008", ) def test_item_not_a_pair(self): class TestModelAdmin(ModelAdmin): fieldsets = ((),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be of length 2.", "admin.E009", ) def test_second_element_of_item_not_a_dict(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", ()),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must be a dictionary.", "admin.E010", ) def test_missing_fields_key(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {}),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must contain the key 'fields'.", "admin.E011", ) class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_specified_both_fields_and_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) fields = ["name"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "Both 'fieldsets' and 'fields' are specified.", "admin.E005", ) def test_duplicate_fields(self): class TestModelAdmin(ModelAdmin): fieldsets = [(None, {"fields": ["name", "name"]})] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[0][1]'.", "admin.E012", "Remove duplicates of 'name'.", ) def test_duplicate_fields_in_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = [ (None, {"fields": ["name"]}), (None, {"fields": ["name"]}), ] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[1][1]'.", "admin.E012", "Remove duplicates of 'name'.", ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (("Band", {"fields": ("name",)}),) self.assertIsValid(BandAdmin, Band) class FieldsCheckTests(CheckTestCase): def test_duplicate_fields_in_fields(self): class TestModelAdmin(ModelAdmin): fields = ["name", "name"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' contains duplicate field(s).", "admin.E006", "Remove duplicates of 'name'.", ) def test_inline(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fields = 10 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' must be a list or tuple.", "admin.E004", invalid_obj=ValidationTestInline, ) class FormCheckTests(CheckTestCase): def test_invalid_type(self): class FakeForm: pass class TestModelAdmin(ModelAdmin): form = FakeForm class TestModelAdminWithNoForm(ModelAdmin): form = "not a form" for model_admin in (TestModelAdmin, TestModelAdminWithNoForm): with self.subTest(model_admin): self.assertIsInvalid( model_admin, ValidationTestModel, "The value of 'form' must inherit from 'BaseModelForm'.", "admin.E016", ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (("Band", {"fields": ("name",)}),) self.assertIsValid(BandAdmin, Band) def test_valid_case(self): class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm fieldsets = (("Band", {"fields": ("name", "bio", "sign_date", "delete")}),) self.assertIsValid(BandAdmin, Band) class FilterVerticalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_vertical = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical' must be a list or tuple.", "admin.E017", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E019", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' must be a many-to-many field.", "admin.E020", ) @isolate_apps("modeladmin") def test_invalid_reverse_m2m_field_with_related_name(self): class Contact(Model): pass class Customer(Model): contacts = ManyToManyField("Contact", related_name="customers") class TestModelAdmin(ModelAdmin): filter_vertical = ["customers"] self.assertIsInvalid( TestModelAdmin, Contact, "The value of 'filter_vertical[0]' must be a many-to-many field.", "admin.E020", ) @isolate_apps("modeladmin") def test_invalid_m2m_field_with_through(self): class Artist(Model): bands = ManyToManyField("Band", through="BandArtist") class BandArtist(Model): artist = ForeignKey("Artist", on_delete=CASCADE) band = ForeignKey("Band", on_delete=CASCADE) class TestModelAdmin(ModelAdmin): filter_vertical = ["bands"] self.assertIsInvalid( TestModelAdmin, Artist, "The value of 'filter_vertical[0]' cannot include the ManyToManyField " "'bands', because that field manually specifies a relationship model.", "admin.E013", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) class FilterHorizontalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_horizontal = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal' must be a list or tuple.", "admin.E018", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E019", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' must be a many-to-many field.", "admin.E020", ) @isolate_apps("modeladmin") def test_invalid_reverse_m2m_field_with_related_name(self): class Contact(Model): pass class Customer(Model): contacts = ManyToManyField("Contact", related_name="customers") class TestModelAdmin(ModelAdmin): filter_horizontal = ["customers"] self.assertIsInvalid( TestModelAdmin, Contact, "The value of 'filter_horizontal[0]' must be a many-to-many field.", "admin.E020", ) @isolate_apps("modeladmin") def test_invalid_m2m_field_with_through(self): class Artist(Model): bands = ManyToManyField("Band", through="BandArtist") class BandArtist(Model): artist = ForeignKey("Artist", on_delete=CASCADE) band = ForeignKey("Band", on_delete=CASCADE) class TestModelAdmin(ModelAdmin): filter_horizontal = ["bands"] self.assertIsInvalid( TestModelAdmin, Artist, "The value of 'filter_horizontal[0]' cannot include the ManyToManyField " "'bands', because that field manually specifies a relationship model.", "admin.E013", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) class RadioFieldsCheckTests(CheckTestCase): def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): radio_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' must be a dictionary.", "admin.E021", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): radio_fields = {"non_existent_field": VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E022", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): radio_fields = {"name": VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'name', which is not an instance " "of ForeignKey, and does not have a 'choices' definition.", "admin.E023", ) def test_invalid_value(self): class TestModelAdmin(ModelAdmin): radio_fields = {"state": None} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or " "admin.VERTICAL.", "admin.E024", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): radio_fields = {"state": VERTICAL} self.assertIsValid(TestModelAdmin, ValidationTestModel) class PrepopulatedFieldsCheckTests(CheckTestCase): def test_not_list_or_tuple(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": "test"} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields[\"slug\"]' must be a list or tuple.", "admin.E029", ) def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' must be a dictionary.", "admin.E026", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"non_existent_field": ("slug",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E027", ) def test_missing_field_again(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": ("non_existent_field",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields[\"slug\"][0]' refers to " "'non_existent_field', which is not a field of " "'modeladmin.ValidationTestModel'.", "admin.E030", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"users": ("name",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'users', which must not be " "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.", "admin.E028", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": ("name",)} self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_one_to_one_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"best_friend": ("name",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'best_friend', which must " "not be a DateTimeField, a ForeignKey, a OneToOneField, or a " "ManyToManyField.", "admin.E028", ) class ListDisplayTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display' must be a list or tuple.", "admin.E107", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' refers to 'non_existent_field', " "which is not a callable or attribute of 'TestModelAdmin', " "or an attribute, method, or field on 'modeladmin.ValidationTestModel'.", "admin.E108", ) def test_missing_related_field(self): class TestModelAdmin(ModelAdmin): list_display = ("band__non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' refers to 'band__non_existent_field', " "which is not a callable or attribute of 'TestModelAdmin', " "or an attribute, method, or field on 'modeladmin.ValidationTestModel'.", "admin.E108", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): list_display = ("users",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_invalid_reverse_related_field(self): class TestModelAdmin(ModelAdmin): list_display = ["song_set"] self.assertIsInvalid( TestModelAdmin, Band, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_invalid_related_field(self): class TestModelAdmin(ModelAdmin): list_display = ["song"] self.assertIsInvalid( TestModelAdmin, Band, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_invalid_m2m_related_name(self): class TestModelAdmin(ModelAdmin): list_display = ["featured"] self.assertIsInvalid( TestModelAdmin, Band, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_valid_case(self): @admin.display def a_callable(obj): pass class TestModelAdmin(ModelAdmin): @admin.display def a_method(self, obj): pass list_display = ("name", "decade_published_in", "a_method", a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_field_accessible_via_instance(self): class PositionField(Field): """Custom field accessible only via instance.""" def contribute_to_class(self, cls, name): super().contribute_to_class(cls, name) setattr(cls, self.name, self) def __get__(self, instance, owner): if instance is None: raise AttributeError() class TestModel(Model): field = PositionField() class TestModelAdmin(ModelAdmin): list_display = ("field",) self.assertIsValid(TestModelAdmin, TestModel) class ListDisplayLinksCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display_links = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", "admin.E110", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display_links = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, ( "The value of 'list_display_links[0]' refers to " "'non_existent_field', which is not defined in 'list_display'." ), "admin.E111", ) def test_missing_in_list_display(self): class TestModelAdmin(ModelAdmin): list_display_links = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links[0]' refers to 'name', which is not " "defined in 'list_display'.", "admin.E111", ) def test_valid_case(self): @admin.display def a_callable(obj): pass class TestModelAdmin(ModelAdmin): @admin.display def a_method(self, obj): pass list_display = ("name", "decade_published_in", "a_method", a_callable) list_display_links = ("name", "decade_published_in", "a_method", a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_None_is_valid_case(self): class TestModelAdmin(ModelAdmin): list_display_links = None self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_links_check_skipped_if_get_list_display_overridden(self): """ list_display_links check is skipped if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = ["name", "subtitle"] def get_list_display(self, request): pass self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_link_checked_for_list_tuple_if_get_list_display_overridden( self, ): """ list_display_links is checked for list/tuple/None even if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = "non-list/tuple" def get_list_display(self, request): pass self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", "admin.E110", ) class ListFilterTests(CheckTestCase): def test_list_filter_validation(self): class TestModelAdmin(ModelAdmin): list_filter = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter' must be a list or tuple.", "admin.E112", ) def test_not_list_filter_class(self): class TestModelAdmin(ModelAdmin): list_filter = ["RandomClass"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'RandomClass', which " "does not refer to a Field.", "admin.E116", ) def test_callable(self): def random_callable(): pass class TestModelAdmin(ModelAdmin): list_filter = [random_callable] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_callable(self): class TestModelAdmin(ModelAdmin): list_filter = [[42, 42]] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_filter = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'non_existent_field', " "which does not refer to a Field.", "admin.E116", ) def test_not_filter(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (RandomClass,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_filter_again(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (("is_active", RandomClass),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_not_filter_again_again(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return "awesomeness" def get_choices(self, request): return (("bit", "A bit awesome"), ("very", "Very awesome")) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = (("is_active", AwesomeFilter),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_list_filter_is_func(self): def get_filter(): pass class TestModelAdmin(ModelAdmin): list_filter = [get_filter] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_associated_with_field_name(self): class TestModelAdmin(ModelAdmin): list_filter = (BooleanFieldListFilter,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must not inherit from 'FieldListFilter'.", "admin.E114", ) def test_valid_case(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return "awesomeness" def get_choices(self, request): return (("bit", "A bit awesome"), ("very", "Very awesome")) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = ( "is_active", AwesomeFilter, ("is_active", BooleanFieldListFilter), "no", ) self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListPerPageCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_per_page = "hello" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_per_page' must be an integer.", "admin.E118", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_per_page = 100 self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListMaxShowAllCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_max_show_all = "hello" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_max_show_all' must be an integer.", "admin.E119", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_max_show_all = 200 self.assertIsValid(TestModelAdmin, ValidationTestModel) class SearchFieldsCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): search_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'search_fields' must be a list or tuple.", "admin.E126", ) class DateHierarchyCheckTests(CheckTestCase): def test_missing_field(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "non_existent_field" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' refers to 'non_existent_field', " "which does not refer to a Field.", "admin.E127", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "name" self.assertIsInvalid( TestModelAdmin,
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/modeladmin/models.py
tests/modeladmin/models.py
from django.contrib.auth.models import User from django.db import models class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() sign_date = models.DateField() class Meta: ordering = ("name",) def __str__(self): return self.name class Song(models.Model): name = models.CharField(max_length=100) band = models.ForeignKey(Band, models.CASCADE) featuring = models.ManyToManyField(Band, related_name="featured") def __str__(self): return self.name class Concert(models.Model): main_band = models.ForeignKey(Band, models.CASCADE, related_name="main_concerts") opening_band = models.ForeignKey( Band, models.CASCADE, related_name="opening_concerts", blank=True ) day = models.CharField(max_length=3, choices=((1, "Fri"), (2, "Sat"))) transport = models.CharField( max_length=100, choices=((1, "Plane"), (2, "Train"), (3, "Bus")), blank=True ) class ValidationTestModel(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() users = models.ManyToManyField(User) state = models.CharField( max_length=2, choices=(("CO", "Colorado"), ("WA", "Washington")) ) is_active = models.BooleanField(default=False) pub_date = models.DateTimeField() band = models.ForeignKey(Band, models.CASCADE) best_friend = models.OneToOneField(User, models.CASCADE, related_name="best_friend") # This field is intentionally 2 characters long (#16080). no = models.IntegerField(verbose_name="Number", blank=True, null=True) def decade_published_in(self): return self.pub_date.strftime("%Y")[:3] + "0's" class ValidationTestInlineModel(models.Model): parent = models.ForeignKey(ValidationTestModel, models.CASCADE)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/modeladmin/__init__.py
tests/modeladmin/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/modeladmin/tests.py
tests/modeladmin/tests.py
from datetime import date from django import forms from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry from django.contrib.admin.options import ( HORIZONTAL, VERTICAL, ModelAdmin, TabularInline, get_content_type_for_model, ) from django.contrib.admin.sites import AdminSite from django.contrib.admin.widgets import ( AdminDateWidget, AdminRadioSelect, AutocompleteSelect, AutocompleteSelectMultiple, ) from django.contrib.auth.models import User from django.db import models from django.forms.widgets import Select from django.test import RequestFactory, SimpleTestCase, TestCase from django.test.utils import isolate_apps from .models import Band, Concert, Song class MockRequest: pass class MockSuperUser: def has_perm(self, perm, obj=None): return True request = MockRequest() request.user = MockSuperUser() class ModelAdminTests(TestCase): @classmethod def setUpTestData(cls): cls.band = Band.objects.create( name="The Doors", bio="", sign_date=date(1965, 1, 1), ) def setUp(self): self.site = AdminSite() def test_modeladmin_str(self): ma = ModelAdmin(Band, self.site) self.assertEqual(str(ma), "modeladmin.ModelAdmin") def test_default_attributes(self): ma = ModelAdmin(Band, self.site) self.assertEqual(ma.actions, ()) self.assertEqual(ma.inlines, ()) # form/fields/fieldsets interaction ############################## def test_default_fields(self): ma = ModelAdmin(Band, self.site) self.assertEqual( list(ma.get_form(request).base_fields), ["name", "bio", "sign_date"] ) self.assertEqual(list(ma.get_fields(request)), ["name", "bio", "sign_date"]) self.assertEqual( list(ma.get_fields(request, self.band)), ["name", "bio", "sign_date"] ) self.assertIsNone(ma.get_exclude(request, self.band)) def test_default_fieldsets(self): # fieldsets_add and fieldsets_change should return a special data # structure that is used in the templates. They should generate the # "right thing" whether we have specified a custom form, the fields # argument, or nothing at all. # # Here's the default case. There are no custom form_add/form_change # methods, no fields argument, and no fieldsets argument. ma = ModelAdmin(Band, self.site) self.assertEqual( ma.get_fieldsets(request), [(None, {"fields": ["name", "bio", "sign_date"]})], ) self.assertEqual( ma.get_fieldsets(request, self.band), [(None, {"fields": ["name", "bio", "sign_date"]})], ) def test_get_fieldsets(self): # get_fieldsets() is called when figuring out form fields (#18681). class BandAdmin(ModelAdmin): def get_fieldsets(self, request, obj=None): return [(None, {"fields": ["name", "bio"]})] ma = BandAdmin(Band, self.site) form = ma.get_form(None) self.assertEqual(form._meta.fields, ["name", "bio"]) class InlineBandAdmin(TabularInline): model = Concert fk_name = "main_band" can_delete = False def get_fieldsets(self, request, obj=None): return [(None, {"fields": ["day", "transport"]})] ma = InlineBandAdmin(Band, self.site) form = ma.get_formset(None).form self.assertEqual(form._meta.fields, ["day", "transport"]) def test_lookup_allowed_allows_nonexistent_lookup(self): """ A lookup_allowed allows a parameter whose field lookup doesn't exist. (#21129). """ class BandAdmin(ModelAdmin): fields = ["name"] ma = BandAdmin(Band, self.site) self.assertIs( ma.lookup_allowed("name__nonexistent", "test_value", request), True, ) @isolate_apps("modeladmin") def test_lookup_allowed_onetoone(self): class Department(models.Model): code = models.CharField(max_length=4, unique=True) class Employee(models.Model): department = models.ForeignKey(Department, models.CASCADE, to_field="code") class EmployeeProfile(models.Model): employee = models.OneToOneField(Employee, models.CASCADE) class EmployeeInfo(models.Model): employee = models.OneToOneField(Employee, models.CASCADE) description = models.CharField(max_length=100) class EmployeeProfileAdmin(ModelAdmin): list_filter = [ "employee__employeeinfo__description", "employee__department__code", ] ma = EmployeeProfileAdmin(EmployeeProfile, self.site) # Reverse OneToOneField self.assertIs( ma.lookup_allowed( "employee__employeeinfo__description", "test_value", request ), True, ) # OneToOneField and ForeignKey self.assertIs( ma.lookup_allowed("employee__department__code", "test_value", request), True, ) @isolate_apps("modeladmin") def test_lookup_allowed_for_local_fk_fields(self): class Country(models.Model): pass class Place(models.Model): country = models.ForeignKey(Country, models.CASCADE) class PlaceAdmin(ModelAdmin): pass ma = PlaceAdmin(Place, self.site) cases = [ ("country", "1"), ("country__exact", "1"), ("country__id", "1"), ("country__id__exact", "1"), ("country__isnull", True), ("country__isnull", False), ("country__id__isnull", False), ] for lookup, lookup_value in cases: with self.subTest(lookup=lookup): self.assertIs(ma.lookup_allowed(lookup, lookup_value, request), True) @isolate_apps("modeladmin") def test_lookup_allowed_non_autofield_primary_key(self): class Country(models.Model): id = models.CharField(max_length=2, primary_key=True) class Place(models.Model): country = models.ForeignKey(Country, models.CASCADE) class PlaceAdmin(ModelAdmin): list_filter = ["country"] ma = PlaceAdmin(Place, self.site) self.assertIs(ma.lookup_allowed("country__id__exact", "DE", request), True) @isolate_apps("modeladmin") def test_lookup_allowed_foreign_primary(self): class Country(models.Model): name = models.CharField(max_length=256) class Place(models.Model): country = models.ForeignKey(Country, models.CASCADE) class Restaurant(models.Model): place = models.OneToOneField(Place, models.CASCADE, primary_key=True) class Waiter(models.Model): restaurant = models.ForeignKey(Restaurant, models.CASCADE) class WaiterAdmin(ModelAdmin): list_filter = [ "restaurant__place__country", "restaurant__place__country__name", ] ma = WaiterAdmin(Waiter, self.site) self.assertIs( ma.lookup_allowed("restaurant__place__country", "1", request), True, ) self.assertIs( ma.lookup_allowed("restaurant__place__country__id__exact", "1", request), True, ) self.assertIs( ma.lookup_allowed( "restaurant__place__country__name", "test_value", request ), True, ) def test_lookup_allowed_considers_dynamic_list_filter(self): class ConcertAdmin(ModelAdmin): list_filter = ["main_band__sign_date"] def get_list_filter(self, request): if getattr(request, "user", None): return self.list_filter + ["main_band__name"] return self.list_filter model_admin = ConcertAdmin(Concert, self.site) request_band_name_filter = RequestFactory().get( "/", {"main_band__name": "test"} ) self.assertIs( model_admin.lookup_allowed( "main_band__sign_date", "?", request_band_name_filter ), True, ) self.assertIs( model_admin.lookup_allowed( "main_band__name", "?", request_band_name_filter ), False, ) request_with_superuser = request self.assertIs( model_admin.lookup_allowed( "main_band__sign_date", "?", request_with_superuser ), True, ) self.assertIs( model_admin.lookup_allowed("main_band__name", "?", request_with_superuser), True, ) def test_field_arguments(self): # If fields is specified, fieldsets_add and fieldsets_change should # just stick the fields into a formsets structure and return it. class BandAdmin(ModelAdmin): fields = ["name"] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_fields(request)), ["name"]) self.assertEqual(list(ma.get_fields(request, self.band)), ["name"]) self.assertEqual(ma.get_fieldsets(request), [(None, {"fields": ["name"]})]) self.assertEqual( ma.get_fieldsets(request, self.band), [(None, {"fields": ["name"]})] ) def test_field_arguments_restricted_on_form(self): # If fields or fieldsets is specified, it should exclude fields on the # Form class to the fields specified. This may cause errors to be # raised in the db layer if required model fields aren't in fields/ # fieldsets, but that's preferable to ghost errors where a field in the # Form class isn't being displayed because it's not in # fields/fieldsets. # Using `fields`. class BandAdmin(ModelAdmin): fields = ["name"] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name"]) self.assertEqual(list(ma.get_form(request, self.band).base_fields), ["name"]) # Using `fieldsets`. class BandAdmin(ModelAdmin): fieldsets = [(None, {"fields": ["name"]})] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name"]) self.assertEqual(list(ma.get_form(request, self.band).base_fields), ["name"]) # Using `exclude`. class BandAdmin(ModelAdmin): exclude = ["bio"] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name", "sign_date"]) # You can also pass a tuple to `exclude`. class BandAdmin(ModelAdmin): exclude = ("bio",) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name", "sign_date"]) # Using `fields` and `exclude`. class BandAdmin(ModelAdmin): fields = ["name", "bio"] exclude = ["bio"] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name"]) def test_custom_form_meta_exclude_with_readonly(self): """ The custom ModelForm's `Meta.exclude` is respected when used in conjunction with `ModelAdmin.readonly_fields` and when no `ModelAdmin.exclude` is defined (#14496). """ # With ModelAdmin class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ["bio"] class BandAdmin(ModelAdmin): readonly_fields = ["name"] form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["sign_date"]) # With InlineModelAdmin class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ["day"] class ConcertInline(TabularInline): readonly_fields = ["transport"] form = AdminConcertForm fk_name = "main_band" model = Concert class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "opening_band", "id", "DELETE"], ) def test_custom_formfield_override_readonly(self): class AdminBandForm(forms.ModelForm): name = forms.CharField() class Meta: exclude = () model = Band class BandAdmin(ModelAdmin): form = AdminBandForm readonly_fields = ["name"] ma = BandAdmin(Band, self.site) # `name` shouldn't appear in base_fields because it's part of # readonly_fields. self.assertEqual(list(ma.get_form(request).base_fields), ["bio", "sign_date"]) # But it should appear in get_fields()/fieldsets() so it can be # displayed as read-only. self.assertEqual(list(ma.get_fields(request)), ["bio", "sign_date", "name"]) self.assertEqual( list(ma.get_fieldsets(request)), [(None, {"fields": ["bio", "sign_date", "name"]})], ) def test_custom_form_meta_exclude(self): """ The custom ModelForm's `Meta.exclude` is overridden if `ModelAdmin.exclude` or `InlineModelAdmin.exclude` are defined (#14496). """ # With ModelAdmin class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ["bio"] class BandAdmin(ModelAdmin): exclude = ["name"] form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["bio", "sign_date"]) # With InlineModelAdmin class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ["day"] class ConcertInline(TabularInline): exclude = ["transport"] form = AdminConcertForm fk_name = "main_band" model = Concert class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "opening_band", "day", "id", "DELETE"], ) def test_overriding_get_exclude(self): class BandAdmin(ModelAdmin): def get_exclude(self, request, obj=None): return ["name"] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request).base_fields), ["bio", "sign_date"], ) def test_get_exclude_overrides_exclude(self): class BandAdmin(ModelAdmin): exclude = ["bio"] def get_exclude(self, request, obj=None): return ["name"] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request).base_fields), ["bio", "sign_date"], ) def test_get_exclude_takes_obj(self): class BandAdmin(ModelAdmin): def get_exclude(self, request, obj=None): if obj: return ["sign_date"] return ["name"] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request, self.band).base_fields), ["name", "bio"], ) def test_custom_form_validation(self): # If a form is specified, it should use it allowing custom validation # to work properly. This won't break any of the admin widgets or media. class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual( list(ma.get_form(request).base_fields), ["name", "bio", "sign_date", "delete"], ) self.assertEqual( type(ma.get_form(request).base_fields["sign_date"].widget), AdminDateWidget ) def test_form_exclude_kwarg_override(self): """ The `exclude` kwarg passed to `ModelAdmin.get_form()` overrides all other declarations (#8999). """ class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ["name"] class BandAdmin(ModelAdmin): exclude = ["sign_date"] form = AdminBandForm def get_form(self, request, obj=None, **kwargs): kwargs["exclude"] = ["bio"] return super().get_form(request, obj, **kwargs) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name", "sign_date"]) def test_formset_exclude_kwarg_override(self): """ The `exclude` kwarg passed to `InlineModelAdmin.get_formset()` overrides all other declarations (#8999). """ class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ["day"] class ConcertInline(TabularInline): exclude = ["transport"] form = AdminConcertForm fk_name = "main_band" model = Concert def get_formset(self, request, obj=None, **kwargs): kwargs["exclude"] = ["opening_band"] return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "day", "transport", "id", "DELETE"], ) def test_formset_overriding_get_exclude_with_form_fields(self): class AdminConcertForm(forms.ModelForm): class Meta: model = Concert fields = ["main_band", "opening_band", "day", "transport"] class ConcertInline(TabularInline): form = AdminConcertForm fk_name = "main_band" model = Concert def get_exclude(self, request, obj=None): return ["opening_band"] class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "day", "transport", "id", "DELETE"], ) def test_formset_overriding_get_exclude_with_form_exclude(self): class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ["day"] class ConcertInline(TabularInline): form = AdminConcertForm fk_name = "main_band" model = Concert def get_exclude(self, request, obj=None): return ["opening_band"] class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "day", "transport", "id", "DELETE"], ) def test_raw_id_fields_widget_override(self): """ The autocomplete_fields, raw_id_fields, and radio_fields widgets may overridden by specifying a widget in get_formset(). """ class ConcertInline(TabularInline): model = Concert fk_name = "main_band" raw_id_fields = ("opening_band",) def get_formset(self, request, obj=None, **kwargs): kwargs["widgets"] = {"opening_band": Select} return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) band_widget = ( list(ma.get_formsets_with_inlines(request))[0][0]() .forms[0] .fields["opening_band"] .widget ) # Without the override this would be ForeignKeyRawIdWidget. self.assertIsInstance(band_widget, Select) def test_queryset_override(self): # If the queryset of a ModelChoiceField in a custom form is overridden, # RelatedFieldWidgetWrapper doesn't mess that up. band2 = Band.objects.create( name="The Beatles", bio="", sign_date=date(1962, 1, 1) ) ma = ModelAdmin(Concert, self.site) form = ma.get_form(request)() self.assertHTMLEqual( str(form["main_band"]), '<div class="related-widget-wrapper" data-model-ref="band">' '<select data-context="available-source" ' 'name="main_band" id="id_main_band" required>' '<option value="" selected>---------</option>' '<option value="%d">The Beatles</option>' '<option value="%d">The Doors</option>' "</select></div>" % (band2.id, self.band.id), ) class AdminConcertForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["main_band"].queryset = Band.objects.filter( name="The Doors" ) class ConcertAdminWithForm(ModelAdmin): form = AdminConcertForm ma = ConcertAdminWithForm(Concert, self.site) form = ma.get_form(request)() self.assertHTMLEqual( str(form["main_band"]), '<div class="related-widget-wrapper" data-model-ref="band">' '<select data-context="available-source" ' 'name="main_band" id="id_main_band" required>' '<option value="" selected>---------</option>' '<option value="%d">The Doors</option>' "</select></div>" % self.band.id, ) def test_regression_for_ticket_15820(self): """ `obj` is passed from `InlineModelAdmin.get_fieldsets()` to `InlineModelAdmin.get_formset()`. """ class CustomConcertForm(forms.ModelForm): class Meta: model = Concert fields = ["day"] class ConcertInline(TabularInline): model = Concert fk_name = "main_band" def get_formset(self, request, obj=None, **kwargs): if obj: kwargs["form"] = CustomConcertForm return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] Concert.objects.create(main_band=self.band, opening_band=self.band, day=1) ma = BandAdmin(Band, self.site) inline_instances = ma.get_inline_instances(request) fieldsets = list(inline_instances[0].get_fieldsets(request)) self.assertEqual( fieldsets[0][1]["fields"], ["main_band", "opening_band", "day", "transport"] ) fieldsets = list( inline_instances[0].get_fieldsets(request, inline_instances[0].model) ) self.assertEqual(fieldsets[0][1]["fields"], ["day"]) # radio_fields behavior ########################################### def test_default_foreign_key_widget(self): # First, without any radio_fields specified, the widgets for ForeignKey # and fields with choices specified ought to be a basic Select widget. # ForeignKey widgets in the admin are wrapped with # RelatedFieldWidgetWrapper so they need to be handled properly when # type checking. For Select fields, all of the choices lists have a # first entry of dashes. cma = ModelAdmin(Concert, self.site) cmafa = cma.get_form(request) self.assertEqual(type(cmafa.base_fields["main_band"].widget.widget), Select) self.assertEqual( list(cmafa.base_fields["main_band"].widget.choices), [("", "---------"), (self.band.id, "The Doors")], ) self.assertEqual(type(cmafa.base_fields["opening_band"].widget.widget), Select) self.assertEqual( list(cmafa.base_fields["opening_band"].widget.choices), [("", "---------"), (self.band.id, "The Doors")], ) self.assertEqual(type(cmafa.base_fields["day"].widget), Select) self.assertEqual( list(cmafa.base_fields["day"].widget.choices), [("", "---------"), (1, "Fri"), (2, "Sat")], ) self.assertEqual(type(cmafa.base_fields["transport"].widget), Select) self.assertEqual( list(cmafa.base_fields["transport"].widget.choices), [("", "---------"), (1, "Plane"), (2, "Train"), (3, "Bus")], ) def test_foreign_key_as_radio_field(self): # Now specify all the fields as radio_fields. Widgets should now be # RadioSelect, and the choices list should have a first entry of 'None' # if blank=True for the model field. Finally, the widget should have # the 'radiolist' attr, and 'inline' as well if the field is specified # HORIZONTAL. class ConcertAdmin(ModelAdmin): radio_fields = { "main_band": HORIZONTAL, "opening_band": VERTICAL, "day": VERTICAL, "transport": HORIZONTAL, } cma = ConcertAdmin(Concert, self.site) cmafa = cma.get_form(request) self.assertEqual( type(cmafa.base_fields["main_band"].widget.widget), AdminRadioSelect ) self.assertEqual( cmafa.base_fields["main_band"].widget.attrs, {"class": "radiolist inline", "data-context": "available-source"}, ) self.assertEqual( list(cmafa.base_fields["main_band"].widget.choices), [(self.band.id, "The Doors")], ) self.assertEqual( type(cmafa.base_fields["opening_band"].widget.widget), AdminRadioSelect ) self.assertEqual( cmafa.base_fields["opening_band"].widget.attrs, {"class": "radiolist", "data-context": "available-source"}, ) self.assertEqual( list(cmafa.base_fields["opening_band"].widget.choices), [("", "None"), (self.band.id, "The Doors")], ) self.assertEqual(type(cmafa.base_fields["day"].widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields["day"].widget.attrs, {"class": "radiolist"}) self.assertEqual( list(cmafa.base_fields["day"].widget.choices), [(1, "Fri"), (2, "Sat")] ) self.assertEqual(type(cmafa.base_fields["transport"].widget), AdminRadioSelect) self.assertEqual( cmafa.base_fields["transport"].widget.attrs, {"class": "radiolist inline"} ) self.assertEqual( list(cmafa.base_fields["transport"].widget.choices), [("", "None"), (1, "Plane"), (2, "Train"), (3, "Bus")], ) class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ("transport",) class ConcertAdmin(ModelAdmin): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) self.assertEqual( list(ma.get_form(request).base_fields), ["main_band", "opening_band", "day"] ) class AdminConcertForm(forms.ModelForm): extra = forms.CharField() class Meta: model = Concert fields = ["extra", "transport"] class ConcertAdmin(ModelAdmin): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["extra", "transport"]) class ConcertInline(TabularInline): form = AdminConcertForm model = Concert fk_name = "main_band" can_delete = True class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["extra", "transport", "id", "DELETE", "main_band"], ) def test_log_actions(self): ma = ModelAdmin(Band, self.site) mock_request = MockRequest() mock_request.user = User.objects.create(username="bill") content_type = get_content_type_for_model(self.band) tests = ( (ma.log_addition, ADDITION, {"added": {}}), (ma.log_change, CHANGE, {"changed": {"fields": ["name", "bio"]}}), ) for method, flag, message in tests: with self.subTest(name=method.__name__): created = method(mock_request, self.band, message) fetched = LogEntry.objects.filter(action_flag=flag).latest("id") self.assertEqual(created, fetched) self.assertEqual(fetched.action_flag, flag) self.assertEqual(fetched.content_type, content_type) self.assertEqual(fetched.object_id, str(self.band.pk)) self.assertEqual(fetched.user, mock_request.user) self.assertEqual(fetched.change_message, str(message)) self.assertEqual(fetched.object_repr, str(self.band)) def test_log_deletions(self): ma = ModelAdmin(Band, self.site) mock_request = MockRequest() mock_request.user = User.objects.create(username="akash") content_type = get_content_type_for_model(self.band) Band.objects.create( name="The Beatles", bio="A legendary rock band from Liverpool.", sign_date=date(1962, 1, 1), ) Band.objects.create( name="Mohiner Ghoraguli", bio="A progressive rock band from Calcutta.", sign_date=date(1975, 1, 1), ) queryset = Band.objects.all().order_by("-id")[:3] self.assertEqual(len(queryset), 3) with self.assertNumQueries(1): ma.log_deletions(mock_request, queryset) logs = ( LogEntry.objects.filter(action_flag=DELETION) .order_by("id") .values_list( "user_id", "content_type", "object_id", "object_repr", "action_flag", "change_message", ) ) expected_log_values = [ ( mock_request.user.id, content_type.id, str(obj.pk), str(obj), DELETION, "", ) for obj in queryset ] self.assertSequenceEqual(logs, expected_log_values) def test_get_autocomplete_fields(self): class NameAdmin(ModelAdmin): search_fields = ["name"] class SongAdmin(ModelAdmin): autocomplete_fields = ["featuring"] fields = ["featuring", "band"] class OtherSongAdmin(SongAdmin): def get_autocomplete_fields(self, request): return ["band"] self.site.register(Band, NameAdmin) try: # Uses autocomplete_fields if not overridden. model_admin = SongAdmin(Song, self.site) form = model_admin.get_form(request)() self.assertIsInstance( form.fields["featuring"].widget.widget, AutocompleteSelectMultiple ) # Uses overridden get_autocomplete_fields model_admin = OtherSongAdmin(Song, self.site) form = model_admin.get_form(request)() self.assertIsInstance(form.fields["band"].widget.widget, AutocompleteSelect) finally: self.site.unregister(Band) def test_get_deleted_objects(self): mock_request = MockRequest() mock_request.user = User.objects.create_superuser(
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/views.py
tests/forms_tests/views.py
from django import forms from django.http import HttpResponse from django.template import Context, Template from django.views.generic.edit import UpdateView from .models import Article class ArticleForm(forms.ModelForm): content = forms.CharField(strip=False, widget=forms.Textarea) class Meta: model = Article fields = "__all__" class ArticleFormView(UpdateView): model = Article success_url = "/" form_class = ArticleForm def form_view(request): class Form(forms.Form): number = forms.FloatField() template = Template("<html>{{ form }}</html>") context = Context({"form": Form()}) return HttpResponse(template.render(context))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/models.py
tests/forms_tests/models.py
import datetime import itertools import tempfile from django.core.files.storage import FileSystemStorage from django.db import models callable_default_counter = itertools.count() def callable_default(): return next(callable_default_counter) temp_storage = FileSystemStorage(location=tempfile.mkdtemp()) class BoundaryModel(models.Model): positive_integer = models.PositiveIntegerField(null=True, blank=True) class Defaults(models.Model): name = models.CharField(max_length=255, default="class default value") def_date = models.DateField(default=datetime.date(1980, 1, 1)) value = models.IntegerField(default=42) callable_default = models.IntegerField(default=callable_default) class ChoiceModel(models.Model): """For ModelChoiceField and ModelMultipleChoiceField tests.""" CHOICES = [ ("", "No Preference"), ("f", "Foo"), ("b", "Bar"), ] INTEGER_CHOICES = [ (None, "No Preference"), (1, "Foo"), (2, "Bar"), ] STRING_CHOICES_WITH_NONE = [ (None, "No Preference"), ("f", "Foo"), ("b", "Bar"), ] name = models.CharField(max_length=10) choice = models.CharField(max_length=2, blank=True, choices=CHOICES) choice_string_w_none = models.CharField( max_length=2, blank=True, null=True, choices=STRING_CHOICES_WITH_NONE ) choice_integer = models.IntegerField(choices=INTEGER_CHOICES, blank=True, null=True) class ChoiceOptionModel(models.Model): """ Destination for ChoiceFieldModel's ForeignKey. Can't reuse ChoiceModel because error_message tests require that it have no instances. """ name = models.CharField(max_length=10) class Meta: ordering = ("name",) def __str__(self): return "ChoiceOption %d" % self.pk def choice_default(): return ChoiceOptionModel.objects.get_or_create(name="default")[0].pk def choice_default_list(): return [choice_default()] def int_default(): return 1 def int_list_default(): return [1] class ChoiceFieldModel(models.Model): """Model with ForeignKey to another model, for testing ModelForm generation with ModelChoiceField.""" choice = models.ForeignKey( ChoiceOptionModel, models.CASCADE, blank=False, default=choice_default, ) choice_int = models.ForeignKey( ChoiceOptionModel, models.CASCADE, blank=False, related_name="choice_int", default=int_default, ) multi_choice = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name="multi_choice", default=choice_default_list, ) multi_choice_int = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name="multi_choice_int", default=int_list_default, ) class OptionalMultiChoiceModel(models.Model): multi_choice = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name="not_relevant", default=choice_default, ) multi_choice_optional = models.ManyToManyField( ChoiceOptionModel, blank=True, related_name="not_relevant2", ) class FileModel(models.Model): file = models.FileField(storage=temp_storage, upload_to="tests") class Article(models.Model): content = models.TextField()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/__init__.py
tests/forms_tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/urls.py
tests/forms_tests/urls.py
from django.urls import path from .views import ArticleFormView, form_view urlpatterns = [ path("form_view/", form_view, name="form_view"), path("model_form/<int:pk>/", ArticleFormView.as_view(), name="article_form"), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/templatetags/tags.py
tests/forms_tests/templatetags/tags.py
from django.template import Library, Node register = Library() class CountRenderNode(Node): count = 0 def render(self, context): self.count += 1 for v in context.flatten().values(): try: str(v) except AttributeError: pass return str(self.count) @register.tag def count_render(parser, token): return CountRenderNode()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/templatetags/__init__.py
tests/forms_tests/templatetags/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_i18n.py
tests/forms_tests/tests/test_i18n.py
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 from . import jinja2_tests 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">nazwa u\u017cytkownika:</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_1"].legend_tag(), "<legend>field_1:</legend>", ) self.assertHTMLEqual( f["field_2"].label_tag(), '<label for="field_2_id">field_2:</label>' ) self.assertHTMLEqual( f["field_2"].legend_tag(), "<legend>field_2:</legend>", ) 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>\xc5\xf8\xdf:</label>" '<div id="id_somechoice">\n' '<div><label for="id_somechoice_0">' '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" ' "required> En tied\xe4</label></div>\n" '<div><label for="id_somechoice_1">' '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" ' 'required> Mies</label></div>\n<div><label for="id_somechoice_2">' '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" ' "required> Nainen</label></div>\n</div></p>", ) # Translated error messages with translation.override("ru"): f = SomeForm({}) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist" id="id_somechoice_error"><li>' "\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c" "\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n" "<p><label>\xc5\xf8\xdf:</label>" ' <div id="id_somechoice">\n<div><label for="id_somechoice_0">' '<input type="radio" id="id_somechoice_0" value="\xc5" ' 'name="somechoice" aria-invalid="true" required>' "En tied\xe4</label></div>\n" '<div><label for="id_somechoice_1">' '<input type="radio" id="id_somechoice_1" value="\xf8" ' 'name="somechoice" aria-invalid="true" required>' "Mies</label></div>\n<div>" '<label for="id_somechoice_2">' '<input type="radio" id="id_somechoice_2" value="\xdf" ' 'name="somechoice" aria-invalid="true" required>' "Nainen</label></div>\n</div></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() @jinja2_tests class Jinja2FormsI18nTests(FormsI18nTests): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_media.py
tests/forms_tests/tests/test_media.py
from django.forms import CharField, Form, Media, MultiWidget, TextInput from django.forms.widgets import MediaAsset, Script from django.template import Context, Template from django.test import SimpleTestCase, override_settings from django.utils.html import html_safe class CSS(MediaAsset): element_template = '<link href="{path}"{attributes}>' def __init__(self, href, **attributes): super().__init__(href, **attributes) self.attributes["rel"] = "stylesheet" @override_settings(STATIC_URL="http://media.example.com/static/") class MediaAssetTestCase(SimpleTestCase): def test_init(self): attributes = {"media": "all", "is": "magic-css"} asset = MediaAsset("path/to/css", **attributes) self.assertEqual(asset._path, "path/to/css") self.assertEqual(asset.attributes, attributes) self.assertIsNot(asset.attributes, attributes) def test_eq(self): self.assertEqual(MediaAsset("path/to/css"), MediaAsset("path/to/css")) self.assertEqual(MediaAsset("path/to/css"), "path/to/css") self.assertEqual( MediaAsset("path/to/css", media="all"), MediaAsset("path/to/css") ) self.assertNotEqual(MediaAsset("path/to/css"), MediaAsset("path/to/other.css")) self.assertNotEqual(MediaAsset("path/to/css"), "path/to/other.css") self.assertNotEqual(MediaAsset("path/to/css", media="all"), CSS("path/to/css")) def test_hash(self): self.assertEqual(hash(MediaAsset("path/to/css")), hash("path/to/css")) self.assertEqual( hash(MediaAsset("path/to/css")), hash(MediaAsset("path/to/css")) ) def test_str(self): self.assertEqual( str(MediaAsset("path/to/css")), "http://media.example.com/static/path/to/css", ) self.assertEqual( str(MediaAsset("http://media.other.com/path/to/css")), "http://media.other.com/path/to/css", ) def test_repr(self): self.assertEqual(repr(MediaAsset("path/to/css")), "MediaAsset('path/to/css')") self.assertEqual( repr(MediaAsset("http://media.other.com/path/to/css")), "MediaAsset('http://media.other.com/path/to/css')", ) def test_path(self): asset = MediaAsset("path/to/css") self.assertEqual(asset.path, "http://media.example.com/static/path/to/css") asset = MediaAsset("http://media.other.com/path/to/css") self.assertEqual(asset.path, "http://media.other.com/path/to/css") asset = MediaAsset("https://secure.other.com/path/to/css") self.assertEqual(asset.path, "https://secure.other.com/path/to/css") asset = MediaAsset("/absolute/path/to/css") self.assertEqual(asset.path, "/absolute/path/to/css") asset = MediaAsset("//absolute/path/to/css") self.assertEqual(asset.path, "//absolute/path/to/css") @override_settings(STATIC_URL="http://media.example.com/static/") class ScriptTestCase(SimpleTestCase): def test_init_with_src_kwarg(self): self.assertEqual( Script(src="path/to/js").path, "http://media.example.com/static/path/to/js" ) def test_str(self): self.assertHTMLEqual( str(Script("path/to/js")), '<script src="http://media.example.com/static/path/to/js"></script>', ) self.assertHTMLEqual( str(Script("path/to/js", **{"async": True, "deferred": False})), '<script src="http://media.example.com/static/path/to/js" async></script>', ) @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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script 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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script 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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script 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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">', ) self.assertEqual( str(w1.media["js"]), """<script src="/path/to/js1"></script> <script src="http://media.other.com/path/to/js2"></script> <script 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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # media addition hasn't affected the original objects self.assertEqual( str(w1.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script 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" media="all" rel="stylesheet"> <script src="/path/to/js1"></script>""", ) def test_media_deduplication(self): # A deduplication test applied directly to a Media object, to confirm # that the deduplication doesn't only happen at the point of merging # two or more media objects. media = Media( css={"all": ("/path/to/css1", "/path/to/css1")}, js=("/path/to/js1", "/path/to/js1"), ) self.assertEqual( str(media), """<link href="/path/to/css1" media="all" rel="stylesheet"> <script 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" media="all" rel="stylesheet"> <script 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" media="all" rel="stylesheet"> <link href="/other/path" media="all" rel="stylesheet"> <script src="/some/js"></script> <script 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" media="all" ' 'rel="stylesheet">\n' '<link href="/other/path" media="all" rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="/other/js"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script 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" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet"> <link href="/path/to/css2" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script src="http://media.other.com/path/to/js2"></script> <script src="/path/to/js4"></script> <script src="https://secure.other.com/path/to/js3"></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" media="all" rel="stylesheet"> <link href="/other/path" media="all" rel="stylesheet"> <script src="/some/js"></script> <script 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" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script 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" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet"> <link href="/path/to/css2" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script src="http://media.other.com/path/to/js2"></script> <script src="/path/to/js4"></script> <script src="https://secure.other.com/path/to/js3"></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" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet"> <link href="/path/to/css2" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script 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" media="print" rel="stylesheet"> <link href="/file3" media="screen" rel="stylesheet"> <link href="/file1" media="screen, print" rel="stylesheet"> <link href="/file2" media="screen, print" rel="stylesheet"> <script src="/path/to/js1"></script> <script 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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></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" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></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" media="all" ' 'rel="stylesheet">\n' '<link href="/some/form/css" media="all" rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="/some/form/javascript"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # Media works in templates self.assertEqual( Template("{{ form.media.js }}{{ form.media.css }}").render( Context({"form": f3}) ), '<script src="/path/to/js1"></script>\n' '<script src="/some/form/javascript"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>' '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/some/form/css" media="all" rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" 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, 3, 2, 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]), (([1, 2], [1, 2]), [1, 2]), ( [[1, 2], [1, 3], [2, 3], [5, 7], [5, 6], [6, 7, 9], [8, 9]], [1, 5, 8, 2, 6, 3, 7, 9], ), ((), []), (([1, 2],), [1, 2]), ) for lists, expected in test_values: with self.subTest(lists=lists): self.assertEqual(Media.merge(*lists), expected) def test_merge_warning(self): msg = "Detected duplicate Media files in an opposite order: [1, 2], [2, 1]" with self.assertWarnsMessage(RuntimeWarning, msg): self.assertEqual(Media.merge([1, 2], [2, 1], None), [1, 2]) def test_merge_js_three_way(self): """ The relative order of scripts is preserved in a three-way merge. """ widget1 = Media(js=["color-picker.js"]) widget2 = Media(js=["text-editor.js"]) widget3 = Media( js=["text-editor.js", "text-editor-extras.js", "color-picker.js"] ) merged = widget1 + widget2 + widget3 self.assertEqual( merged._js, ["text-editor.js", "text-editor-extras.js", "color-picker.js"] ) def test_merge_js_three_way2(self): # The merge prefers to place 'c' before 'b' and 'g' before 'h' to # preserve the original order. The preference 'c'->'b' is overridden by # widget3's media, but 'g'->'h' survives in the final ordering. widget1 = Media(js=["a", "c", "f", "g", "k"]) widget2 = Media(js=["a", "b", "f", "h", "k"]) widget3 = Media(js=["b", "c", "f", "k"]) merged = widget1 + widget2 + widget3 self.assertEqual(merged._js, ["a", "b", "c", "f", "g", "h", "k"]) def test_merge_css_three_way(self): widget1 = Media(css={"screen": ["c.css"], "all": ["d.css", "e.css"]}) widget2 = Media(css={"screen": ["a.css"]}) widget3 = Media(css={"screen": ["a.css", "b.css", "c.css"], "all": ["e.css"]}) widget4 = Media(css={"all": ["d.css", "e.css"], "screen": ["c.css"]}) merged = widget1 + widget2 # c.css comes before a.css because widget1 + widget2 establishes this # order. self.assertEqual( merged._css, {"screen": ["c.css", "a.css"], "all": ["d.css", "e.css"]} ) merged += widget3 # widget3 contains an explicit ordering of c.css and a.css. self.assertEqual( merged._css, {"screen": ["a.css", "b.css", "c.css"], "all": ["d.css", "e.css"]}, ) # Media ordering does not matter. merged = widget1 + widget4 self.assertEqual(merged._css, {"screen": ["c.css"], "all": ["d.css", "e.css"]}) def test_add_js_deduplication(self): widget1 = Media(js=["a", "b", "c"]) widget2 = Media(js=["a", "b"]) widget3 = Media(js=["a", "c", "b"]) merged = widget1 + widget1 self.assertEqual(merged._js_lists, [["a", "b", "c"]]) self.assertEqual(merged._js, ["a", "b", "c"]) merged = widget1 + widget2 self.assertEqual(merged._js_lists, [["a", "b", "c"], ["a", "b"]]) self.assertEqual(merged._js, ["a", "b", "c"]) # Lists with items in a different order are preserved when added. merged = widget1 + widget3 self.assertEqual(merged._js_lists, [["a", "b", "c"], ["a", "c", "b"]]) msg = ( "Detected duplicate Media files in an opposite order: " "['a', 'b', 'c'], ['a', 'c', 'b']" ) with self.assertWarnsMessage(RuntimeWarning, msg): merged._js def test_add_css_deduplication(self): widget1 = Media(css={"screen": ["a.css"], "all": ["b.css"]}) widget2 = Media(css={"screen": ["c.css"]}) widget3 = Media(css={"screen": ["a.css"], "all": ["b.css", "c.css"]}) widget4 = Media(css={"screen": ["a.css"], "all": ["c.css", "b.css"]}) merged = widget1 + widget1 self.assertEqual(merged._css_lists, [{"screen": ["a.css"], "all": ["b.css"]}]) self.assertEqual(merged._css, {"screen": ["a.css"], "all": ["b.css"]}) merged = widget1 + widget2 self.assertEqual( merged._css_lists, [ {"screen": ["a.css"], "all": ["b.css"]}, {"screen": ["c.css"]}, ], ) self.assertEqual(merged._css, {"screen": ["a.css", "c.css"], "all": ["b.css"]}) merged = widget3 + widget4 # Ordering within lists is preserved. self.assertEqual( merged._css_lists, [ {"screen": ["a.css"], "all": ["b.css", "c.css"]}, {"screen": ["a.css"], "all": ["c.css", "b.css"]}, ], ) msg = ( "Detected duplicate Media files in an opposite order: " "['b.css', 'c.css'], ['c.css', 'b.css']" ) with self.assertWarnsMessage(RuntimeWarning, msg): merged._css def test_add_empty(self): media = Media(css={"screen": ["a.css"]}, js=["a"]) empty_media = Media() merged = media + empty_media self.assertEqual(merged._css_lists, [{"screen": ["a.css"]}]) self.assertEqual(merged._js_lists, [["a"]]) @override_settings( STATIC_URL="http://media.example.com/static/", ) class FormsMediaObjectTestCase(SimpleTestCase): """Media handling when media are objects instead of raw strings.""" def test_construction(self): m = Media( css={ "all": (
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_error_messages.py
tests/forms_tests/tests/test_error_messages.py
from django.core.exceptions import ValidationError 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, 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, "a@b.com") self.assertFormErrors(["LENGTH 11, MAX LENGTH 10"], f.clean, "aye@bee.com") 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( ['"https://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" id="id_last_name_error"><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" id="id_field_error">' "<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" id="id_field_error">' "<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" id="id_field_error">' "<li>“&lt;script&gt;” 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", "invalid_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"]) def test_modelchoicefield_value_placeholder(self): f = ModelChoiceField( queryset=ChoiceModel.objects.all(), error_messages={ "invalid_choice": '"%(value)s" is not one of the available choices.', }, ) self.assertFormErrors( ['"invalid" is not one of the available choices.'], f.clean, "invalid", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_forms.py
tests/forms_tests/tests/test_forms.py
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, BoundField, CharField, CheckboxSelectMultiple, ChoiceField, DateField, DateTimeField, EmailField, Field, FileField, FileInput, FloatField, Form, HiddenInput, ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput, MultiValueField, MultiWidget, NullBooleanField, PasswordInput, RadioSelect, Select, SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeField, ValidationError, ) from django.forms.renderers import DjangoTemplates, get_default_renderer from django.forms.utils import ErrorDict, ErrorList from django.http import QueryDict from django.template import Context, Template from django.test import SimpleTestCase from django.test.utils import override_settings from django.utils.datastructures import MultiValueDict from django.utils.safestring import mark_safe from . import jinja2_tests class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")], widget=RadioSelect) 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 SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) 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.assertIsInstance(p.errors, dict) 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), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) 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), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist" id="id_first_name_error"><li>This field is required.' '</li></ul><input type="text" name="first_name" aria-invalid="true" ' 'required id="id_first_name" aria-describedby="id_first_name_error"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist" id="id_last_name_error"><li>This field is required.' '</li></ul><input type="text" name="last_name" aria-invalid="true" ' 'required id="id_last_name" aria-describedby="id_last_name_error"></div>' '<div><label for="id_birthday">Birthday:</label>' '<ul class="errorlist" id="id_birthday_error"><li>This field is required.' '</li></ul><input type="text" name="birthday" aria-invalid="true" required ' 'id="id_birthday" aria-describedby="id_birthday_error"></div>', ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <ul class="errorlist" id="id_first_name_error"><li>This field is required.</li></ul> <input type="text" name="first_name" id="id_first_name" aria-invalid="true" required aria-describedby="id_first_name_error"> </td></tr><tr><th><label for="id_last_name">Last name:</label></th> <td><ul class="errorlist" id="id_last_name_error"><li>This field is required.</li></ul> <input type="text" name="last_name" id="id_last_name" aria-invalid="true" required aria-describedby="id_last_name_error"> </td></tr><tr><th><label for="id_birthday">Birthday:</label></th> <td><ul class="errorlist" id="id_birthday_error"><li>This field is required.</li></ul> <input type="text" name="birthday" id="id_birthday" aria-invalid="true" required aria-describedby="id_birthday_error"> </td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist" id="id_first_name_error"> <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" aria-invalid="true" required aria-describedby="id_first_name_error"> </li><li><ul class="errorlist" id="id_last_name_error"><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" aria-invalid="true" required aria-describedby="id_last_name_error"> </li><li><ul class="errorlist" id="id_birthday_error"><li>This field is required.</li> </ul><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" aria-invalid="true" required aria-describedby="id_birthday_error"> </li>""", ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist" id="id_first_name_error"><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" aria-invalid="true" required aria-describedby="id_first_name_error"> </p><ul class="errorlist" id="id_last_name_error"><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" aria-invalid="true" required aria-describedby="id_last_name_error"> </p><ul class="errorlist" id="id_birthday_error"><li>This field is required.</li></ul> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" aria-invalid="true" required aria-describedby="id_birthday_error"> </p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist" id="id_first_name_error"><li>This field is required.' '</li></ul><input type="text" name="first_name" aria-invalid="true" ' 'required id="id_first_name" aria-describedby="id_first_name_error"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist" id="id_last_name_error"><li>This field is required.' '</li></ul><input type="text" name="last_name" aria-invalid="true" ' 'required id="id_last_name" aria-describedby="id_last_name_error"></div>' '<div><label for="id_birthday">Birthday:</label>' '<ul class="errorlist" id="id_birthday_error"><li>This field is required.' '</li></ul><input type="text" name="birthday" aria-invalid="true" required ' 'id="id_birthday" aria-describedby="id_birthday_error"></div>', ) 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), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) 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>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) 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>", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<input type="text" name="first_name" value="John" id="id_first_name" ' 'required></div><div><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></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" value="1940-10-9" ' 'id="id_birthday" required></div>', ) 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" id="id_first_name_error">' "<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>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="first_name_id">First name:</label><input type="text" ' 'name="first_name" id="first_name_id" required></div><div><label ' 'for="last_name_id">Last name:</label><input type="text" ' 'name="last_name" id="last_name_id" required></div><div><label ' 'for="birthday_id">Birthday:</label><input type="text" name="birthday" ' 'id="birthday_id" required></div>', ) 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" maxlength="320" required>', ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm({"email": "test@example.com", "get_spam": True}, auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" maxlength="320" value="test@example.com" ' "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": "test@example.com", "get_spam": "True"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) f = SignupForm({"email": "test@example.com", "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": "test@example.com", "get_spam": "False"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" aria-invalid="true" required>', ) f = SignupForm( {"email": "test@example.com", "get_spam": "false"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" aria-invalid="true" required>', ) # A value of '0' should be interpreted as a True value (#16820) f = SignupForm({"email": "test@example.com", "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.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_utils.py
tests/forms_tests/tests/test_utils.py
import copy import json from django.core.exceptions import ValidationError from django.forms.renderers import DjangoTemplates from django.forms.utils import ( ErrorDict, ErrorList, RenderableFieldMixin, RenderableMixin, flatatt, pretty_name, ) 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_list_copy(self): e = 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()) def test_error_list_copy_attributes(self): class CustomRenderer(DjangoTemplates): pass renderer = CustomRenderer() e = ErrorList(error_class="woopsies", renderer=renderer) e_copy = e.copy() self.assertEqual(e.error_class, e_copy.error_class) self.assertEqual(e.renderer, e_copy.renderer) 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) def test_error_dict_copy_attributes(self): class CustomRenderer(DjangoTemplates): pass renderer = CustomRenderer() e = ErrorDict(renderer=renderer) e_copy = copy.copy(e) self.assertEqual(e.renderer, e_copy.renderer) 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__()) def test_error_dict_is_dict(self): self.assertIsInstance(ErrorDict(), dict) def test_error_dict_is_json_serializable(self): init_errors = ErrorDict( [ ( "__all__", ErrorList( [ValidationError("Sorry this form only works on leap days.")] ), ), ("name", ErrorList([ValidationError("This field is required.")])), ] ) min_value_error_list = ErrorList( [ValidationError("Ensure this value is greater than or equal to 0.")] ) e = ErrorDict( init_errors, date=ErrorList( [ ErrorDict( { "day": min_value_error_list, "month": min_value_error_list, "year": min_value_error_list, } ), ] ), ) e["renderer"] = ErrorList( [ ValidationError( "Select a valid choice. That choice is not one of the " "available choices." ), ] ) self.assertJSONEqual( json.dumps(e), { "__all__": ["Sorry this form only works on leap days."], "name": ["This field is required."], "date": [ { "day": ["Ensure this value is greater than or equal to 0."], "month": ["Ensure this value is greater than or equal to 0."], "year": ["Ensure this value is greater than or equal to 0."], }, ], "renderer": [ "Select a valid choice. That choice is not one of the " "available choices." ], }, ) def test_get_context_must_be_implemented(self): mixin = RenderableMixin() msg = "Subclasses of RenderableMixin must provide a get_context() method." with self.assertRaisesMessage(NotImplementedError, msg): mixin.get_context() def test_field_mixin_as_hidden_must_be_implemented(self): mixin = RenderableFieldMixin() msg = "Subclasses of RenderableFieldMixin must provide an as_hidden() method." with self.assertRaisesMessage(NotImplementedError, msg): mixin.as_hidden() def test_field_mixin_as_widget_must_be_implemented(self): mixin = RenderableFieldMixin() msg = "Subclasses of RenderableFieldMixin must provide an as_widget() method." with self.assertRaisesMessage(NotImplementedError, msg): mixin.as_widget() def test_pretty_name(self): self.assertEqual(pretty_name("john_doe"), "John doe") self.assertEqual(pretty_name(None), "") self.assertEqual(pretty_name(""), "")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_renderers.py
tests/forms_tests/tests/test_renderers.py
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
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_widgets.py
tests/forms_tests/tests/test_widgets.py
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 """ from selenium.webdriver.common.by import By article = Article.objects.create(content="\nTst\n") self.selenium.get( self.live_server_url + reverse("article_form", args=[article.pk]) ) with self.wait_page_loaded(): self.selenium.find_element(By.ID, "submit").click() article = Article.objects.get(pk=article.pk) self.assertEqual(article.content, "\r\nTst\r\n")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_formsets.py
tests/forms_tests/tests/test_formsets.py
import datetime from collections import Counter from unittest import mock from django.core.exceptions import ValidationError from django.forms import ( BaseForm, CharField, DateField, FileField, Form, IntegerField, SplitDateTimeField, formsets, ) from django.forms.formsets import ( INITIAL_FORM_COUNT, MAX_NUM_FORM_COUNT, MIN_NUM_FORM_COUNT, TOTAL_FORM_COUNT, BaseFormSet, ManagementForm, all_valid, formset_factory, ) from django.forms.renderers import ( DjangoTemplates, TemplatesSetting, get_default_renderer, ) from django.forms.utils import ErrorList from django.forms.widgets import HiddenInput from django.test import SimpleTestCase from . import jinja2_tests class Choice(Form): choice = CharField() votes = IntegerField() ChoiceFormSet = formset_factory(Choice) class ChoiceFormsetWithNonFormError(ChoiceFormSet): def clean(self): super().clean() raise ValidationError("non-form error") 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"> <div>Choice:<input type="text" name="choices-0-choice"></div> <div>Votes:<input type="number" name="choices-0-votes"></div>""", ) # 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_formset_name(self): ArticleFormSet = formset_factory(ArticleForm) ChoiceFormSet = formset_factory(Choice) self.assertEqual(ArticleFormSet.__name__, "ArticleFormSet") self.assertEqual(ChoiceFormSet.__name__, "ChoiceFormSet") 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_empty_permitted_ignored_empty_form(self): formset = ArticleFormSet(form_kwargs={"empty_permitted": False}) self.assertIs(formset.empty_form.empty_permitted, True) 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. """ formset = self.make_choiceformset( initial=[{"choice": "Calexico", "votes": 100}] ) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<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") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<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") # 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.as_ul() for form in formset.forms), """<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") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<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 at most 1 form."]) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>Please submit at most 1 form.</li></ul>', ) def test_formset_validate_max_flag_custom_error(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "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", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet( data, auto_id=False, prefix="choices", error_messages={ "too_many_forms": "Number of submitted forms should be at most %(num)d." }, ) self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["Number of submitted forms should be at most 1."], ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform">' "<li>Number of submitted forms should be at most 1.</li></ul>", ) 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 at least 3 forms."]) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>' "Please submit at least 3 forms.</li></ul>", ) def test_formset_validate_min_flag_custom_formatted_error(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "0", "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", error_messages={ "too_few_forms": "Number of submitted forms should be at least %(num)d." }, ) self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["Number of submitted forms should be at least 3."], ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform">' "<li>Number of submitted forms should be at least 3.</li></ul>", ) 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 at least 1 form."]) 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") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<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") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<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. """ FavoriteDrinkFormset = formset_factory(form=FavoriteDrinkForm, can_delete=True) formset = FavoriteDrinkFormset( { "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(formset.is_valid()) self.assertEqual(formset._errors, []) self.assertEqual(len(formset.deleted_forms), 1) def test_formset_with_deletion_custom_widget(self): class DeletionAttributeFormSet(BaseFormSet): deletion_widget = HiddenInput class DeletionMethodFormSet(BaseFormSet): def get_deletion_widget(self): return HiddenInput(attrs={"class": "deletion"}) tests = [ (DeletionAttributeFormSet, '<input type="hidden" name="form-0-DELETE">'), ( DeletionMethodFormSet, '<input class="deletion" type="hidden" name="form-0-DELETE">', ), ] for formset_class, delete_html in tests: with self.subTest(formset_class=formset_class.__name__): ArticleFormSet = formset_factory( ArticleForm, formset=formset_class, can_delete=True, ) formset = ArticleFormSet(auto_id=False) self.assertHTMLEqual( "\n".join([form.as_ul() for form in formset.forms]), ( f'<li>Title: <input type="text" name="form-0-title"></li>' f'<li>Pub date: <input type="text" name="form-0-pub_date">' f"{delete_html}</li>" ), ) 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") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<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()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/__init__.py
tests/forms_tests/tests/__init__.py
from unittest import skipIf from django.test.utils import override_settings try: import jinja2 except ImportError: jinja2 = None def jinja2_tests(test_func): test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func) return override_settings( FORM_RENDERER="django.forms.renderers.Jinja2", TEMPLATES={"BACKEND": "django.template.backends.jinja2.Jinja2"}, )(test_func)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/tests.py
tests/forms_tests/tests/tests.py
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, skipUnlessDBFeature from ..models import ( BoundaryModel, ChoiceFieldModel, ChoiceModel, ChoiceOptionModel, Defaults, FileModel, OptionalMultiChoiceModel, ) from . import jinja2_tests 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. """ 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. """ 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> """, ) @skipUnlessDBFeature("supports_json_field") def test_callable_default_hidden_widget_value_not_overridden(self): class FieldWithCallableDefaultsModel(models.Model): int_field = models.IntegerField(default=lambda: 1) json_field = models.JSONField(default=dict) class FieldWithCallableDefaultsModelForm(ModelForm): class Meta: model = FieldWithCallableDefaultsModel fields = "__all__" form = FieldWithCallableDefaultsModelForm( data={ "initial-int_field": "1", "int_field": "1000", "initial-json_field": "{}", "json_field": '{"key": "val"}', } ) form_html = form.as_p() self.assertHTMLEqual( form_html, """ <p> <label for="id_int_field">Int field:</label> <input type="number" name="int_field" value="1000" required id="id_int_field"> <input type="hidden" name="initial-int_field" value="1" id="initial-id_int_field"> </p> <p> <label for="id_json_field">Json field:</label> <textarea cols="40" id="id_json_field" name="json_field" required rows="10"> {&quot;key&quot;: &quot;val&quot;} </textarea> <input id="initial-id_json_field" name="initial-json_field" type="hidden" value="{}"> </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.file.delete() 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): # 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> """, ) @jinja2_tests class Jinja2EmptyLabelTestCase(EmptyLabelTestCase): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_input_formats.py
tests/forms_tests/tests/test_input_formats.py
from datetime import date, datetime, time from django import forms from django.core.exceptions import ValidationError from django.test import SimpleTestCase, override_settings from django.utils import translation class LocalizedTimeTests(SimpleTestCase): @classmethod def setUpClass(cls): # nl/formats.py has customized TIME_INPUT_FORMATS: # ['%H:%M:%S', '%H.%M:%S', '%H.%M', '%H:%M'] cls.enterClassContext(translation.override("nl")) super().setUpClass() 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(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(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(ValidationError): f.clean("1:30:05 PM") with self.assertRaises(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(ValidationError): f.clean("1:30:05 PM") with self.assertRaises(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): @classmethod def setUpClass(cls): cls.enterClassContext(translation.override(None)) super().setUpClass() 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(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(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(ValidationError): f.clean("1:30:05 PM") with self.assertRaises(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(ValidationError): f.clean("1:30:05 PM") with self.assertRaises(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(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(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(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(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") class LocalizedDateTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.enterClassContext(translation.override("de")) super().setUpClass() 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(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(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(ValidationError): f.clean("2010-12-21") with self.assertRaises(ValidationError): f.clean("21/12/2010") with self.assertRaises(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(ValidationError): f.clean("2010-12-21") with self.assertRaises(ValidationError): f.clean("21/12/2010") with self.assertRaises(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): @classmethod def setUpClass(cls): cls.enterClassContext(translation.override(None)) super().setUpClass() 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(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(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(ValidationError): f.clean("21.12.2010") with self.assertRaises(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(ValidationError): f.clean("21.12.2010") with self.assertRaises(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(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(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(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(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") class LocalizedDateTimeTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.enterClassContext(translation.override("de")) super().setUpClass() 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(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(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(ValidationError): f.clean("2010-12-21 13:30:05 13:30:05") with self.assertRaises(ValidationError): f.clean("1:30:05 PM 21/12/2010") with self.assertRaises(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(ValidationError): f.clean("2010/12/21 13:30:05") with self.assertRaises(ValidationError): f.clean("1:30:05 PM 21/12/2010") with self.assertRaises(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(datetime(2010, 12, 21, 13, 30, 5), result) # ISO format is always valid. self.assertEqual( f.clean("2010-12-21 13:30:05"), 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): @classmethod def setUpClass(cls): cls.enterClassContext(translation.override(None)) super().setUpClass() 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(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(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 """
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/tests/test_validators.py
tests/forms_tests/tests/test_validators.py
import re import types from unittest import TestCase from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.core.files.uploadedfile import SimpleUploadedFile 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."], ) class ValidatorCustomMessageTests(TestCase): def test_value_placeholder_with_char_field(self): cases = [ (validators.validate_integer, "-42.5", "invalid"), (validators.validate_email, "a", "invalid"), (validators.validate_email, "a@b\n.com", "invalid"), (validators.validate_email, "a\n@b.com", "invalid"), (validators.validate_slug, "你 好", "invalid"), (validators.validate_unicode_slug, "你 好", "invalid"), (validators.validate_ipv4_address, "256.1.1.1", "invalid"), (validators.validate_ipv6_address, "1:2", "invalid"), (validators.validate_ipv46_address, "256.1.1.1", "invalid"), (validators.validate_comma_separated_integer_list, "a,b,c", "invalid"), (validators.int_list_validator(), "-1,2,3", "invalid"), (validators.MaxLengthValidator(10), 11 * "x", "max_length"), (validators.MinLengthValidator(10), 9 * "x", "min_length"), (validators.URLValidator(), "no_scheme", "invalid"), (validators.URLValidator(), "http://test[.com", "invalid"), (validators.URLValidator(), "http://[::1:2::3]/", "invalid"), ( validators.URLValidator(), "http://" + ".".join(["a" * 35 for _ in range(9)]), "invalid", ), (validators.RegexValidator("[0-9]+"), "xxxxxx", "invalid"), ] for validator, value, code in cases: if isinstance(validator, types.FunctionType): name = validator.__name__ else: name = type(validator).__name__ with self.subTest(name, value=value): class MyForm(forms.Form): field = forms.CharField( validators=[validator], error_messages={code: "%(value)s"}, ) form = MyForm({"field": value}) self.assertIs(form.is_valid(), False) self.assertEqual(form.errors, {"field": [value]}) def test_value_placeholder_with_null_character(self): class MyForm(forms.Form): field = forms.CharField( error_messages={"null_characters_not_allowed": "%(value)s"}, ) form = MyForm({"field": "a\0b"}) self.assertIs(form.is_valid(), False) self.assertEqual(form.errors, {"field": ["a\x00b"]}) def test_value_placeholder_with_integer_field(self): cases = [ (validators.MaxValueValidator(0), 1, "max_value"), (validators.MinValueValidator(0), -1, "min_value"), (validators.URLValidator(), "1", "invalid"), ] for validator, value, code in cases: with self.subTest(type(validator).__name__, value=value): class MyForm(forms.Form): field = forms.IntegerField( validators=[validator], error_messages={code: "%(value)s"}, ) form = MyForm({"field": value}) self.assertIs(form.is_valid(), False) self.assertEqual(form.errors, {"field": [str(value)]}) def test_value_placeholder_with_decimal_field(self): cases = [ ("NaN", "invalid"), ("123", "max_digits"), ("0.12", "max_decimal_places"), ("12", "max_whole_digits"), ] for value, code in cases: with self.subTest(value=value): class MyForm(forms.Form): field = forms.DecimalField( max_digits=2, decimal_places=1, error_messages={code: "%(value)s"}, ) form = MyForm({"field": value}) self.assertIs(form.is_valid(), False) self.assertEqual(form.errors, {"field": [value]}) def test_value_placeholder_with_file_field(self): class MyForm(forms.Form): field = forms.FileField( validators=[validators.validate_image_file_extension], error_messages={"invalid_extension": "%(value)s"}, ) form = MyForm(files={"field": SimpleUploadedFile("myfile.txt", b"abc")}) self.assertIs(form.is_valid(), False) self.assertEqual(form.errors, {"field": ["myfile.txt"]})
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_combofield.py
tests/forms_tests/field_tests/test_combofield.py
from django.core.exceptions import ValidationError from django.forms import CharField, ComboField, EmailField from django.test import SimpleTestCase class ComboFieldTest(SimpleTestCase): def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) self.assertEqual("test@example.com", f.clean("test@example.com")) with self.assertRaisesMessage( ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", ): f.clean("longemailaddress@example.com") 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("test@example.com", f.clean("test@example.com")) with self.assertRaisesMessage( ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", ): f.clean("longemailaddress@example.com") with self.assertRaisesMessage( ValidationError, "'Enter a valid email address.'" ): f.clean("not an email") self.assertEqual("", f.clean("")) self.assertEqual("", f.clean(None))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_splitdatetimefield.py
tests/forms_tests/field_tests/test_splitdatetimefield.py
import datetime from django.core.exceptions import ValidationError from django.forms import Form, SplitDateTimeField 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"] ) ) def test_form_as_table(self): class TestForm(Form): datetime = SplitDateTimeField() f = TestForm() self.assertHTMLEqual( f.as_table(), "<tr><th><label>Datetime:</label></th><td>" '<input type="text" name="datetime_0" required id="id_datetime_0">' '<input type="text" name="datetime_1" required id="id_datetime_1">' "</td></tr>", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_multiplechoicefield.py
tests/forms_tests/field_tests/test_multiplechoicefield.py
from django.core.exceptions import ValidationError from django.forms import MultipleChoiceField 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)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_genericipaddressfield.py
tests/forms_tests/field_tests/test_genericipaddressfield.py
from django.core.exceptions import ValidationError from django.forms import GenericIPAddressField from django.test import SimpleTestCase from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH 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_max_length_custom(self): # Valid IPv4-mapped IPv6 address, len 45. addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" f = GenericIPAddressField(max_length=len(addr)) f.clean(addr) def test_generic_ipaddress_max_length_validation_error(self): # Valid IPv4-mapped IPv6 address, len 45. addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" cases = [ ({}, MAX_IPV6_ADDRESS_LENGTH), # Default value. ({"max_length": len(addr) - 1}, len(addr) - 1), ] for kwargs, max_length in cases: max_length_plus_one = max_length + 1 msg = ( f"Ensure this value has at most {max_length} characters (it has " f"{max_length_plus_one}).'" ) with self.subTest(max_length=max_length): f = GenericIPAddressField(**kwargs) with self.assertRaisesMessage(ValidationError, msg): f.clean("x" * max_length_plus_one) with self.assertRaisesMessage( ValidationError, "This is not a valid IPv6 address." ): f.clean(addr) 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(" " * MAX_IPV6_ADDRESS_LENGTH + " 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")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_durationfield.py
tests/forms_tests/field_tests/test_durationfield.py
import datetime from django.core.exceptions import ValidationError from django.forms import DurationField from django.test import SimpleTestCase from django.utils import translation 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"), ) self.assertEqual( datetime.timedelta(0, 10800), f.clean(datetime.timedelta(0, 10800)), ) msg = "This field is required." with self.assertRaisesMessage(ValidationError, msg): f.clean("") msg = "Enter a valid duration." with self.assertRaisesMessage(ValidationError, msg): f.clean("not_a_time") with self.assertRaisesMessage(ValidationError, msg): DurationField().clean("P3(3D") def test_durationfield_clean_not_required(self): f = DurationField(required=False) self.assertIsNone(f.clean("")) 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_overflow_translation(self): msg = "Le nombre de jours doit être entre {min_days} et {max_days}.".format( min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days, ) with translation.override("fr"): with self.assertRaisesMessage(ValidationError, msg): DurationField().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))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_jsonfield.py
tests/forms_tests/field_tests/test_jsonfield.py
import json import uuid from django.core.serializers.json import DjangoJSONEncoder from django.forms import ( CharField, Form, JSONField, Textarea, TextInput, ValidationError, ) from django.test import SimpleTestCase class JSONFieldTest(SimpleTestCase): def test_valid(self): field = JSONField() value = field.clean('{"a": "b"}') self.assertEqual(value, {"a": "b"}) def test_valid_empty(self): field = JSONField(required=False) self.assertIsNone(field.clean("")) self.assertIsNone(field.clean(None)) def test_invalid(self): field = JSONField() with self.assertRaisesMessage(ValidationError, "Enter a valid JSON."): field.clean("{some badly formed: json}") def test_prepare_value(self): field = JSONField() self.assertEqual(field.prepare_value({"a": "b"}), '{"a": "b"}') self.assertEqual(field.prepare_value(None), "null") self.assertEqual(field.prepare_value("foo"), '"foo"') self.assertEqual(field.prepare_value("你好,世界"), '"你好,世界"') self.assertEqual(field.prepare_value({"a": "😀🐱"}), '{"a": "😀🐱"}') self.assertEqual( field.prepare_value(["你好,世界", "jaźń"]), '["你好,世界", "jaźń"]', ) def test_widget(self): field = JSONField() self.assertIsInstance(field.widget, Textarea) def test_custom_widget_kwarg(self): field = JSONField(widget=TextInput) self.assertIsInstance(field.widget, TextInput) def test_custom_widget_attribute(self): """The widget can be overridden with an attribute.""" class CustomJSONField(JSONField): widget = TextInput field = CustomJSONField() self.assertIsInstance(field.widget, TextInput) def test_converted_value(self): field = JSONField(required=False) tests = [ '["a", "b", "c"]', '{"a": 1, "b": 2}', "1", "1.5", '"foo"', "true", "false", "null", ] for json_string in tests: with self.subTest(json_string=json_string): val = field.clean(json_string) self.assertEqual(field.clean(val), val) def test_has_changed(self): field = JSONField() self.assertIs(field.has_changed({"a": True}, '{"a": 1}'), True) self.assertIs(field.has_changed({"a": 1, "b": 2}, '{"b": 2, "a": 1}'), False) def test_custom_encoder_decoder(self): class CustomDecoder(json.JSONDecoder): def __init__(self, object_hook=None, *args, **kwargs): return super().__init__(object_hook=self.as_uuid, *args, **kwargs) def as_uuid(self, dct): if "uuid" in dct: dct["uuid"] = uuid.UUID(dct["uuid"]) return dct value = {"uuid": uuid.UUID("{c141e152-6550-4172-a784-05448d98204b}")} encoded_value = '{"uuid": "c141e152-6550-4172-a784-05448d98204b"}' field = JSONField(encoder=DjangoJSONEncoder, decoder=CustomDecoder) self.assertEqual(field.prepare_value(value), encoded_value) self.assertEqual(field.clean(encoded_value), value) def test_formfield_disabled(self): class JSONForm(Form): json_field = JSONField(disabled=True) form = JSONForm({"json_field": '["bar"]'}, initial={"json_field": ["foo"]}) self.assertIn("[&quot;foo&quot;]</textarea>", form.as_p()) def test_redisplay_none_input(self): class JSONForm(Form): json_field = JSONField(required=True) tests = [ {}, {"json_field": None}, ] for data in tests: with self.subTest(data=data): form = JSONForm(data) self.assertEqual(form["json_field"].value(), "null") self.assertIn("null</textarea>", form.as_p()) self.assertEqual(form.errors["json_field"], ["This field is required."]) def test_redisplay_wrong_input(self): """ Displaying a bound form (typically due to invalid input). The form should not overquote JSONField inputs. """ class JSONForm(Form): name = CharField(max_length=2) json_field = JSONField() # JSONField input is valid, name is too long. form = JSONForm({"name": "xyz", "json_field": '["foo"]'}) self.assertNotIn("json_field", form.errors) self.assertIn("[&quot;foo&quot;]</textarea>", form.as_p()) # Invalid JSONField. form = JSONForm({"name": "xy", "json_field": '{"foo"}'}) self.assertEqual(form.errors["json_field"], ["Enter a valid JSON."]) self.assertIn("{&quot;foo&quot;}</textarea>", form.as_p())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_nullbooleanfield.py
tests/forms_tests/field_tests/test_nullbooleanfield.py
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( str(f), '<input type="hidden" name="hidden_nullbool1" value="True" ' 'id="id_hidden_nullbool1">' '<input type="hidden" name="hidden_nullbool2" value="False" ' 'id="id_hidden_nullbool2">', ) 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"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_typedmultiplechoicefield.py
tests/forms_tests/field_tests/test_typedmultiplechoicefield.py
import decimal from django.core.exceptions import ValidationError from django.forms import TypedMultipleChoiceField 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"])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_multivaluefield.py
tests/forms_tests/field_tests/test_multivaluefield.py
from datetime import datetime from django.core.exceptions import ValidationError from django.forms import ( CharField, Form, MultipleChoiceField, MultiValueField, MultiWidget, SelectMultiple, SplitDateTimeField, SplitDateTimeWidget, TextInput, ) from django.test import SimpleTestCase beatles = (("J", "John"), ("P", "Paul"), ("G", "George"), ("R", "Ringo")) class PartiallyRequiredField(MultiValueField): def compress(self, data_list): return ",".join(data_list) if data_list else None class PartiallyRequiredForm(Form): f = PartiallyRequiredField( fields=(CharField(required=True), CharField(required=False)), required=True, require_all_fields=False, widget=MultiWidget(widgets=[TextInput(), TextInput()]), ) 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>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>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" ) def test_render_required_attributes(self): form = PartiallyRequiredForm({"f_0": "Hello", "f_1": ""}) self.assertTrue(form.is_valid()) self.assertInHTML( '<input type="text" name="f_0" value="Hello" required id="id_f_0">', form.as_p(), ) self.assertInHTML('<input type="text" name="f_1" id="id_f_1">', form.as_p()) form = PartiallyRequiredForm({"f_0": "", "f_1": ""}) self.assertFalse(form.is_valid())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_booleanfield.py
tests/forms_tests/field_tests/test_booleanfield.py
import pickle from django.core.exceptions import ValidationError from django.forms import BooleanField 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)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_slugfield.py
tests/forms_tests/field_tests/test_slugfield.py
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") def test_empty_value(self): f = SlugField(required=False) self.assertEqual(f.clean(""), "") self.assertEqual(f.clean(None), "") f = SlugField(required=False, empty_value=None) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_base.py
tests/forms_tests/field_tests/test_base.py
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"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_datetimefield.py
tests/forms_tests/field_tests/test_datetimefield.py
from datetime import UTC, date, datetime from django.core.exceptions import ValidationError from django.forms import DateTimeField from django.test import SimpleTestCase from django.utils.timezone import get_fixed_timezone class DateTimeFieldTest(SimpleTestCase): def test_datetimefield_clean(self): tests = [ (date(2006, 10, 25), datetime(2006, 10, 25, 0, 0)), (datetime(2006, 10, 25, 14, 30), datetime(2006, 10, 25, 14, 30)), (datetime(2006, 10, 25, 14, 30, 59), datetime(2006, 10, 25, 14, 30, 59)), ( datetime(2006, 10, 25, 14, 30, 59, 200), datetime(2006, 10, 25, 14, 30, 59, 200), ), ("2006-10-25 14:30:45.000200", datetime(2006, 10, 25, 14, 30, 45, 200)), ("2006-10-25 14:30:45.0002", datetime(2006, 10, 25, 14, 30, 45, 200)), ("2006-10-25 14:30:45", datetime(2006, 10, 25, 14, 30, 45)), ("2006-10-25 14:30:00", datetime(2006, 10, 25, 14, 30)), ("2006-10-25 14:30", datetime(2006, 10, 25, 14, 30)), ("2006-10-25", datetime(2006, 10, 25, 0, 0)), ("10/25/2006 14:30:45.000200", datetime(2006, 10, 25, 14, 30, 45, 200)), ("10/25/2006 14:30:45", datetime(2006, 10, 25, 14, 30, 45)), ("10/25/2006 14:30:00", datetime(2006, 10, 25, 14, 30)), ("10/25/2006 14:30", datetime(2006, 10, 25, 14, 30)), ("10/25/2006", datetime(2006, 10, 25, 0, 0)), ("10/25/06 14:30:45.000200", datetime(2006, 10, 25, 14, 30, 45, 200)), ("10/25/06 14:30:45", datetime(2006, 10, 25, 14, 30, 45)), ("10/25/06 14:30:00", datetime(2006, 10, 25, 14, 30)), ("10/25/06 14:30", datetime(2006, 10, 25, 14, 30)), ("10/25/06", datetime(2006, 10, 25, 0, 0)), # ISO 8601 formats. ( "2014-09-23T22:34:41.614804", datetime(2014, 9, 23, 22, 34, 41, 614804), ), ("2014-09-23T22:34:41", datetime(2014, 9, 23, 22, 34, 41)), ("2014-09-23T22:34", datetime(2014, 9, 23, 22, 34)), ("2014-09-23", datetime(2014, 9, 23, 0, 0)), ("2014-09-23T22:34Z", datetime(2014, 9, 23, 22, 34, tzinfo=UTC)), ( "2014-09-23T22:34+07:00", datetime(2014, 9, 23, 22, 34, tzinfo=get_fixed_timezone(420)), ), # Whitespace stripping. (" 2006-10-25 14:30:45 ", datetime(2006, 10, 25, 14, 30, 45)), (" 2006-10-25 ", datetime(2006, 10, 25, 0, 0)), (" 10/25/2006 14:30:45 ", datetime(2006, 10, 25, 14, 30, 45)), (" 10/25/2006 14:30 ", datetime(2006, 10, 25, 14, 30)), (" 10/25/2006 ", datetime(2006, 10, 25, 0, 0)), (" 10/25/06 14:30:45 ", datetime(2006, 10, 25, 14, 30, 45)), (" 10/25/06 ", datetime(2006, 10, 25, 0, 0)), ( " 2014-09-23T22:34:41.614804 ", datetime(2014, 9, 23, 22, 34, 41, 614804), ), (" 2014-09-23T22:34Z ", datetime(2014, 9, 23, 22, 34, tzinfo=UTC)), ] f = DateTimeField() for value, expected_datetime in tests: with self.subTest(value=value): self.assertEqual(f.clean(value), expected_datetime) def test_datetimefield_clean_invalid(self): f = DateTimeField() msg = "'Enter a valid date/time.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("hello") with self.assertRaisesMessage(ValidationError, msg): f.clean("2006-10-25 4:30 p.m.") with self.assertRaisesMessage(ValidationError, msg): f.clean(" ") with self.assertRaisesMessage(ValidationError, msg): f.clean("2014-09-23T28:23") f = DateTimeField(input_formats=["%Y %m %d %I:%M %p"]) with self.assertRaisesMessage(ValidationError, msg): f.clean("2006.10.25 14:30:45") def test_datetimefield_clean_input_formats(self): tests = [ ( "%Y %m %d %I:%M %p", ( (date(2006, 10, 25), datetime(2006, 10, 25, 0, 0)), (datetime(2006, 10, 25, 14, 30), datetime(2006, 10, 25, 14, 30)), ( datetime(2006, 10, 25, 14, 30, 59), datetime(2006, 10, 25, 14, 30, 59), ), ( datetime(2006, 10, 25, 14, 30, 59, 200), datetime(2006, 10, 25, 14, 30, 59, 200), ), ("2006 10 25 2:30 PM", datetime(2006, 10, 25, 14, 30)), # ISO-like formats are always accepted. ("2006-10-25 14:30:45", datetime(2006, 10, 25, 14, 30, 45)), ), ), ( "%Y.%m.%d %H:%M:%S.%f", ( ( "2006.10.25 14:30:45.0002", datetime(2006, 10, 25, 14, 30, 45, 200), ), ), ), ] for input_format, values in tests: f = DateTimeField(input_formats=[input_format]) for value, expected_datetime in values: with self.subTest(value=value, input_format=input_format): self.assertEqual(f.clean(value), expected_datetime) def test_datetimefield_not_required(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_changed(self): f = DateTimeField(input_formats=["%Y %m %d %I:%M %p"]) d = datetime(2006, 9, 17, 14, 30, 0) self.assertFalse(f.has_changed(d, "2006 09 17 2:30 PM"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_integerfield.py
tests/forms_tests/field_tests/test_integerfield.py
from django.core.exceptions import ValidationError from django.forms import IntegerField, Textarea 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_6(self): f = IntegerField(step_size=3) self.assertWidgetRendersTo( f, '<input name="f" step="3" type="number" id="id_f" required>', ) with self.assertRaisesMessage( ValidationError, "'Ensure this value is a multiple of step size 3.'" ): f.clean("10") self.assertEqual(12, f.clean(12)) self.assertEqual(12, f.clean("12")) self.assertEqual(f.step_size, 3) def test_integerfield_step_size_min_value(self): f = IntegerField(step_size=3, min_value=-1) self.assertWidgetRendersTo( f, '<input name="f" min="-1" step="3" type="number" id="id_f" required>', ) msg = ( "Ensure this value is a multiple of step size 3, starting from -1, e.g. " "-1, 2, 5, and so on." ) with self.assertRaisesMessage(ValidationError, msg): f.clean("9") self.assertEqual(f.clean("2"), 2) self.assertEqual(f.clean("-1"), -1) self.assertEqual(f.step_size, 3) 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)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_filepathfield.py
tests/forms_tests/field_tests/test_filepathfield.py
import os.path from django.core.exceptions import ValidationError from django.forms import FilePathField from django.test import SimpleTestCase PATH = os.path.dirname(os.path.abspath(__file__)) def fix_os_paths(x): if isinstance(x, str): return x.removeprefix(PATH).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_nonexistent_path(self): with self.assertRaisesMessage(FileNotFoundError, "nonexistent"): FilePathField(path="nonexistent") 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"), ], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_choicefield.py
tests/forms_tests/field_tests/test_choicefield.py
from django.core.exceptions import ValidationError from django.db import models from django.forms import ChoiceField, Form 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_mapping(self): def choices(): return {"J": "John", "P": "Paul"} f = ChoiceField(choices=choices) self.assertEqual("J", f.clean("J")) def test_choicefield_callable_grouped_mapping(self): def choices(): return { "Numbers": {"1": "One", "2": "Two"}, "Letters": {"3": "A", "4": "B"}, } f = ChoiceField(choices=choices) for i in ("1", "2", "3", "4"): with self.subTest(i): self.assertEqual(i, f.clean(i)) def test_choicefield_mapping(self): f = ChoiceField(choices={"J": "John", "P": "Paul"}) self.assertEqual("J", f.clean("J")) def test_choicefield_grouped_mapping(self): f = ChoiceField( choices={ "Numbers": (("1", "One"), ("2", "Two")), "Letters": (("3", "A"), ("4", "B")), } ) for i in ("1", "2", "3", "4"): with self.subTest(i): self.assertEqual(i, f.clean(i)) def test_choicefield_grouped_mapping_inner_dict(self): f = ChoiceField( choices={ "Numbers": {"1": "One", "2": "Two"}, "Letters": {"3": "A", "4": "B"}, } ) for i in ("1", "2", "3", "4"): with self.subTest(i): self.assertEqual(i, f.clean(i)) 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(choices, list(form.fields["choicefield"].choices)) self.assertEqual(choices, list(form.fields["choicefield"].widget.choices)) choices = [("P", "Paul")] form = ChoiceFieldForm() self.assertEqual(choices, list(form.fields["choicefield"].choices)) self.assertEqual(choices, list(form.fields["choicefield"].widget.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>', ) def test_choicefield_enumeration(self): class FirstNames(models.TextChoices): JOHN = "J", "John" PAUL = "P", "Paul" f = ChoiceField(choices=FirstNames) self.assertEqual(f.choices, FirstNames.choices) self.assertEqual(f.clean("J"), "J") msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("3")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_charfield.py
tests/forms_tests/field_tests/test_charfield.py
from django.core.exceptions import ValidationError from django.forms import CharField, HiddenInput, PasswordInput, Textarea, TextInput 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")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_regexfield.py
tests/forms_tests/field_tests/test_regexfield.py
import re from django.core.exceptions import ValidationError from django.forms import RegexField 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") def test_get_regex(self): f = RegexField("^[a-z]+$") self.assertEqual(f.regex, re.compile("^[a-z]+$")) def test_regexfield_strip(self): f = RegexField("^[a-z]+$", strip=True) self.assertEqual(f.clean(" a"), "a") self.assertEqual(f.clean("a "), "a") def test_empty_value(self): f = RegexField("", required=False) self.assertEqual(f.clean(""), "") self.assertEqual(f.clean(None), "") f = RegexField("", empty_value=None, required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_typedchoicefield.py
tests/forms_tests/field_tests/test_typedchoicefield.py
import decimal from django.core.exceptions import ValidationError from django.forms import TypedChoiceField 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")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false