Parcourir la source

Fixed #29270 -- Fixed UserChangeForm crash if password field is excluded.

Malte Gerth il y a 7 ans
Parent
commit
874977d388
2 fichiers modifiés avec 17 ajouts et 4 suppressions
  1. 6 4
      django/contrib/auth/forms.py
  2. 11 0
      tests/auth_tests/test_forms.py

+ 6 - 4
django/contrib/auth/forms.py

@@ -137,10 +137,12 @@ class UserChangeForm(forms.ModelForm):
 
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
-        self.fields['password'].help_text = self.fields['password'].help_text.format('../password/')
-        f = self.fields.get('user_permissions')
-        if f is not None:
-            f.queryset = f.queryset.select_related('content_type')
+        password = self.fields.get('password')
+        if password:
+            password.help_text = password.help_text.format('../password/')
+        user_permissions = self.fields.get('user_permissions')
+        if user_permissions:
+            user_permissions.queryset = user_permissions.queryset.select_related('content_type')
 
     def clean_password(self):
         # Regardless of what the user provides, return the initial value.

+ 11 - 0
tests/auth_tests/test_forms.py

@@ -797,6 +797,17 @@ class UserChangeFormTest(ReloadFormsMixin, TestDataMixin, TestCase):
             form = UserChangeForm(data, instance=user)
             self.assertTrue(form.is_valid())
 
+    def test_password_excluded(self):
+        class UserChangeFormWithoutPassword(UserChangeForm):
+            password = None
+
+            class Meta:
+                model = User
+                exclude = ['password']
+
+        form = UserChangeFormWithoutPassword()
+        self.assertNotIn('password', form.fields)
+
 
 @override_settings(TEMPLATES=AUTH_TEMPLATES)
 class PasswordResetFormTest(TestDataMixin, TestCase):