Opened 9 years ago

Last modified 9 years ago

#26381 closed Bug

UserCreationForm cannot be reused with a custom USERNAME_FIELD value — at Initial Version

Reported by: Berker Peksag Owned by: nobody
Component: contrib.auth Version: dev
Severity: Normal Keywords:
Cc: berker.peksag@… Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I noticed this while working on #25617. If you have a custom user model with USERNAME_FIELD = 'email', you can't just subclass UserCreationForm.

Here is a test case:

diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py
index 6172c44..1d4cd48 100644
--- a/tests/auth_tests/test_forms.py
+++ b/tests/auth_tests/test_forms.py
@@ -20,7 +20,7 @@ from django.utils.encoding import force_text
 from django.utils.text import capfirst
 from django.utils.translation import ugettext as _
 
-from .models.custom_user import ExtensionUser
+from .models.custom_user import CustomUser, ExtensionUser
 from .settings import AUTH_TEMPLATES
 
 
@@ -139,6 +139,22 @@ class UserCreationFormTest(TestDataMixin, TestCase):
         form = CustomUserCreationForm(data)
         self.assertTrue(form.is_valid())
 
+    @override_settings(AUTH_MODEL='auth_tests.models.custom_user.CustomUser')
+    def test_custom_form_with_different_username_field(self):
+        class CustomUserCreationForm(UserCreationForm):
+            class Meta(UserCreationForm.Meta):
+                model = CustomUser
+                fields = ('email', 'date_of_birth')
+
+        data = {
+            'email': 'test@client222.com',
+            'password1': 'testclient',
+            'password2': 'testclient',
+            'date_of_birth': '1988-02-24',
+        }
+        form = CustomUserCreationForm(data)
+        self.assertTrue(form.is_valid())
+
     def test_password_whitespace_not_stripped(self):
         data = {
             'username': 'testuser',

And here is the traceback:

Traceback (most recent call last):
  File "/home/berker/projects/django/django/test/utils.py", line 208, in inner
    return func(*args, **kwargs)
  File "/home/berker/projects/django/tests/auth_tests/test_forms.py", line 155, in test_custom_form_with_different_username_field
    form = CustomUserCreationForm(data)
  File "/home/berker/projects/django/django/contrib/auth/forms.py", line 85, in __init__
    self.fields['username'].widget.attrs.update({'autofocus': ''})
KeyError: u'username'

I will open a oull request to fix this shortly.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top