'Make ModelMultipleChoiceField with FilteredSelectMultiple widget - read only (Python Django)
In my project i use an intermediary model CustomizedUserGroups to keep relations between CustomizedUser and Group models:
# models.py
class CustomizedUser(AbstractUser):
first_name = models.CharField(max_length=255, verbose_name='имя')
last_name = models.CharField(max_length=255, verbose_name='фамилия')
# other fields
groups = models.ManyToManyField(Group, verbose_name='группы', related_name='users', through='CustomizedUserGroups')
Therefore in admin class (CustomizedUserAdmin) for CustomizedUser i can't let fieldsets contain 'groups' (otherwise The value of 'fieldsets[2][1]["fields"]' cannot include the ManyToManyField 'groups', because that field manually specifies a relationship model. will happen). So, i defined fieldsets manually (with no groups) and problem was solved.
# admin.py
class CustomizedUserAdmin(UserAdmin):
fieldsets = ((None, {'fields': ('username',)}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'patronymic', 'role', 'email')}))
It is intended, that value for groups field in model CustomizedUser is assigned automatically depending on other values from registration form fields, therefore when a user adds a new user via admin panel, there is no need to display groups field. But when a user wants to edit other user's data via admin panel, i want the group field to be shown to him in read only mode.
To solve this i created ExtendedUserChangeForm, where i defined a group_list field:
# forms.py
class ExtendedUserChangeForm(UserChangeForm):
group_list = forms.ModelMultipleChoiceField(label='Группы пользователя', queryset=Group.objects.all(),
required=False,
widget=FilteredSelectMultiple('группы пользователя', False, attrs={
'disabled': True
}))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
username = self.initial['username']
user = CustomizedUser.objects.get(username=username)
if user.groups:
self.fields["group_list"].initial = user.groups.all()
I also assigned this form as a form in CustomizedUserAdmin and made fieldsets dynamically include group_list, when ExtendedUserChangeForm is used. It solved the most part of the problem. When i try to edit other user via admin panel i really can see groups_list field which displays actual content of groups field for this user, but read only mode (which i activated via disabled=True in widget attrs) works only for the left half of the widget, and i can still click on its buttons, while i'd like every part of the widget to be unlickable. Please, look at the screenshot to see, what i mean. How can i do this, while continuing to use FilteredSelectMultiple widget?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
