diff --git a/django/apps/config.py b/django/apps/config.py index 6d794eee3aa1..bced53d506b7 100644 --- a/django/apps/config.py +++ b/django/apps/config.py @@ -34,6 +34,10 @@ def __init__(self, app_name, app_module): # This value must be unique across a Django project. if not hasattr(self, 'label'): self.label = app_name.rpartition(".")[2] + if not self.label.isidentifier(): + raise ImproperlyConfigured( + "The app label '%s' is not a valid Python identifier." % self.label + ) # Human-readable name for the application e.g. "Admin". if not hasattr(self, 'verbose_name'): diff --git a/tests/apps/tests.py b/tests/apps/tests.py index 0e1f918bccfd..a8a93ce6835f 100644 --- a/tests/apps/tests.py +++ b/tests/apps/tests.py @@ -436,6 +436,14 @@ def test_repr(self): ac = AppConfig('label', Stub(__path__=['a'])) self.assertEqual(repr(ac), '') + def test_invalid_label(self): + class MyAppConfig(AppConfig): + label = 'invalid.label' + + msg = "The app label 'invalid.label' is not a valid Python identifier." + with self.assertRaisesMessage(ImproperlyConfigured, msg): + MyAppConfig('test_app', Stub()) + @override_settings( INSTALLED_APPS=['apps.apps.ModelPKAppsConfig'], DEFAULT_AUTO_FIELD='django.db.models.SmallAutoField',