From df9dec9b8890edf4cd975cbe36c9d177e8e847a4 Mon Sep 17 00:00:00 2001 From: Dmitry Gamanenko Date: Thu, 21 Dec 2017 05:56:21 -0500 Subject: [PATCH] Fix "admin/auth/user/add "username" missing field. Add test for PR `fix_username_missing_field` Update test case. Remove blank line whitespace. --- common/djangoapps/student/admin.py | 11 ++++++----- .../djangoapps/student/tests/test_admin_views.py | 16 +++++++++++++--- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/common/djangoapps/student/admin.py b/common/djangoapps/student/admin.py index 0222986882..060295b819 100644 --- a/common/djangoapps/student/admin.py +++ b/common/djangoapps/student/admin.py @@ -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) diff --git a/common/djangoapps/student/tests/test_admin_views.py b/common/djangoapps/student/tests/test_admin_views.py index 980ffcc2b0..0ee14a5691 100644 --- a/common/djangoapps/student/tests/test_admin_views.py +++ b/common/djangoapps/student/tests/test_admin_views.py @@ -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))