[Django]-Django permissions in checkbox form

4👍

This is how I do but i use a MultipleSelect, I guess you can apply some of this to checkboxes.

class EditUserForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    super(EditUserForm, self).__init__(*args, **kwargs)

    def get_label(obj):
        permission_name = str(obj).split('|')[2].strip()
        model_name = permission_name.split(' ')[2].strip()
        return '%s | %s' % (model_name.title(), permission_name)

    User = get_user_model()
    content_type = ContentType.objects.get_for_model(User)
    self.fields['user_permissions'].queryset = Permission.objects.filter(content_type=content_type)
    self.fields['user_permissions'].widget.attrs.update({'class': 'permission-select'})
    self.fields['user_permissions'].help_text = None
    self.fields['user_permissions'].label = "Label"
    self.fields['user_permissions'].label_from_instance = get_label

def save(self, commit=True):
    user_instance = super(EditUserForm, self).save(commit)
    user_instance.save()
    user_instance.user_permissions.set(self.cleaned_data.get('user_permissions'))
    return user_instance

class Meta:
    model = get_user_model()
    fields = ['email', 'first_name', 'last_name', 'user_permissions']

    widgets = {
        'email': forms.EmailInput(attrs={'class': 'form-control', 'style': 'width: 300px;'}),
        'first_name': forms.TextInput(attrs={'class': 'form-control', 'style': 'width: 300px;'}),
        'last_name': forms.TextInput(attrs={'class': 'form-control', 'style': 'width: 300px;'}),
        'user_permissions': forms.SelectMultiple(attrs={'style': 'width: 350px; height: 200px;'})
    }

Hope this helps, good luck!

Leave a comment