带有OptGroup选项的Python / Django MultipleChoiceField

时间:2019-06-11 11:19:28

标签: python django django-forms optgroup

在弄清楚如何使用def get_queryset(self): qs = Building.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter(name=query) return qs选择选项在Django表单中配置optgroup标签时,我遇到了一些麻烦。

基本上,我已经创建了一个使用Ajax允许我的项目允许或取消许可的接口,并且我使用了一种形式在2个MutlipleChoiceField选择框中预填充了已授予和未授予的权限。

该项目目前大约有190个权限,因此选择框目前看起来不堪重负,我想要的是使用MutlipleChoiceField html标记对这些选项进行分组。我了解如果我静态键入表单的选项,它是如何工作的,但是目前使用我的当前代码,我看不到一种通过optgroup进行分组以添加正确的app_label的方法。有人可以帮我吗?

这是我的代码:

optgroup

1 个答案:

答案 0 :(得分:0)

我最终以这种方式完成了此问题,现在一切正常,optgroups有效:。

from django import forms
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q


class GroupForm(forms.ModelForm):
    class Meta:
        model = Group
        fields = ['permissions']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if 'instance' in kwargs:
            instance = kwargs['instance']

            all_permissions = Permission.objects.exclude(
                Q(content_type=ContentType.objects.get(app_label='contenttypes', model='contenttype')) |
                Q(content_type=ContentType.objects.get(app_label='sessions', model='session')) |
                Q(codename='add_group') |
                Q(codename='delete_group') |
                Q(codename='add_permission') |
                Q(codename='delete_permission') |
                Q(codename='change_permission')
            ).order_by('id', 'content_type__app_label')

            granted_builder = dict()
            not_granted_builder = dict()

            for permission in all_permissions:
                if permission in instance.permissions.all().order_by('id', 'content_type__app_label'):
                    if not granted_builder.get(permission.content_type.app_label):
                        granted_builder[permission.content_type.app_label] = [[permission.id, permission.name]]
                    else:
                        # we have a list, so append the permission to it
                        granted_builder[permission.content_type.app_label].append([permission.id, permission.name])
                else:
                    if not not_granted_builder.get(permission.content_type.app_label):
                        not_granted_builder[permission.content_type.app_label] = [[permission.id, permission.name]]
                    else:
                        # we have a list, so append the permission to it
                        not_granted_builder[permission.content_type.app_label].append([permission.id, permission.name])

            # loop through granted permissions
            final_granted_permissions = list()
            for app_label, list_of_options in granted_builder.items():
                # [optgroup, [options]]
                final_granted_permissions.append([app_label.title(), list_of_options])

            # loop through not granted permissions
            final_not_granted_permissions = list()
            for app_label, list_of_options in not_granted_builder.items():
                # [optgroup, [options]]
                final_not_granted_permissions.append([app_label.title(), list_of_options])

            self.fields['group_name'] = forms.CharField(
                required=False,
                widget=forms.HiddenInput(attrs={'value': instance.name}))

            self.fields['permissions'] = forms.MultipleChoiceField(
                label='Granted Permissions',
                required=False,
                choices=final_granted_permissions)

            self.fields['not_granted_permissions'] = forms.MultipleChoiceField(
                label='Not Granted Permissions',
                required=False,
                choices=final_not_granted_permissions)