Merge pull request #17042 from raccoongang/dgamanenko/fix_username_missing_field

Fix "admin/auth/user/add "username" missing field.
This commit is contained in:
Ahsan Ul Haq
2018-05-31 14:22:36 +05:00
committed by GitHub
2 changed files with 19 additions and 8 deletions

View File

@@ -195,14 +195,15 @@ class UserAdmin(BaseUserAdmin):
""" Admin interface for the User model. """
inlines = (UserProfileInline,)
def get_readonly_fields(self, *args, **kwargs):
def get_readonly_fields(self, request, obj=None):
"""
Allows editing the users while skipping the username check, so we can have Unicode username with no problems.
The username is marked read-only regardless of `ENABLE_UNICODE_USERNAME`, to simplify the bokchoy tests.
The username is marked read-only when editing existing users regardless of `ENABLE_UNICODE_USERNAME`, to simplify the bokchoy tests.
"""
django_readonly = super(UserAdmin, self).get_readonly_fields(*args, **kwargs)
return django_readonly + ('username',)
django_readonly = super(UserAdmin, self).get_readonly_fields(request, obj)
if obj:
return django_readonly + ('username',)
return django_readonly
@admin.register(UserAttribute)

View File

@@ -165,9 +165,18 @@ class AdminUserPageTest(TestCase):
super(AdminUserPageTest, self).setUp()
self.admin = UserAdmin(User, AdminSite())
def test_username_is_readonly(self):
def test_username_is_writable_for_user_creation(self):
"""
Ensures that the username is readonly to skip Django validation in the `auth_user_change` view.
Ensures that the username is not readonly, when admin creates new user.
"""
request = Mock()
self.assertNotIn('username', self.admin.get_readonly_fields(request))
def test_username_is_readonly_for_user(self):
"""
Ensures that the username field is readonly, when admin open user which already exists.
This hook used for skip Django validation in the `auth_user_change` view.
Changing the username is still possible using the database or from the model directly.
@@ -175,4 +184,5 @@ class AdminUserPageTest(TestCase):
stores the username in a different database.
"""
request = Mock()
self.assertIn('username', self.admin.get_readonly_fields(request))
user = Mock()
self.assertIn('username', self.admin.get_readonly_fields(request, user))