Opened 6 years ago

Closed 6 years ago

#29270 closed Bug (fixed)

KeyError if using 'password' as readonly_fields in UserAdmin

Reported by: Malte Gerth Owned by: Malte Gerth
Component: contrib.auth Version: 2.0
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

If 'password' is added as readonly_field in UserAdmin, a KeyError is thrown, as the UserChangeForm expects a password field to exists.

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

class UserAdmin(BaseUserAdmin):
    readonly_fields = ['username', 'password']

admin.site.register(User, UserAdmin)
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/')
        # ...

Change History (5)

comment:1 by Malte Gerth, 6 years ago

This should fix the issue for now:

class UserChangeForm(forms.ModelForm):
    # ...
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if 'password' in self.fields.keys():
            self.fields['password'].help_text = self.fields['password'].help_text.format('../password/')
        # ...

comment:2 by Tim Graham, 6 years ago

Triage Stage: UnreviewedAccepted

.keys() isn't needed, otherwise the fix looks reasonable. A test goes in tests/auth_tests/test_forms.py -- can you offer a pull request?

comment:3 by Malte Gerth, 6 years ago

Easy pickings: set
Owner: changed from nobody to Malte Gerth
Status: newassigned

comment:4 by Malte Gerth, 6 years ago

Ok, I tried to make a pull request
https://github.com/django/django/pull/9833

comment:5 by Tim Graham <timograham@…>, 6 years ago

Resolution: fixed
Status: assignedclosed

In 874977d3:

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

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