Opened 2 years ago

Closed 2 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 Changed 2 years ago by Malte Gerth

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 Changed 2 years ago by Tim Graham

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 Changed 2 years ago by Malte Gerth

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

comment:4 Changed 2 years ago by Malte Gerth

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

comment:5 Changed 2 years ago by Tim Graham <timograham@…>

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