更新时的Django多选字段

时间:2017-09-13 06:44:00

标签: python django forms

我正在使用Django多选字段来显示复选框,我使用相同的表单来创建和更新组权限。虽然更新组权限我想要只属于该组的所有权限,而不是所有django权限。

forms.py

class AssignPermissionForm(forms.ModelForm):
    list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    queryset = Permission.objects.all().exclude(content_type_id__in=list)
    OPTIONS = ()
    for item in queryset:
        OPTIONS = OPTIONS +((item.name, item.name),)
    group_name = forms.CharField(widget=forms.TextInput(attrs={'id': 'group_name','class': 'form-control'}),label='Group Name')
    name = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS, label="Permission")

    class Meta:
        model = Permission
        fields = ['group_name', 'name']

    def clean_codename(self):
        lists = []
        user_id = self.instance.pk
        codename = str(self.cleaned_data['codename']).split('|')[2].lstrip()
        permission = Permission.objects.get(
            name=codename,
        )
        user_perms = Permission.objects.filter(user=user_id)
        for perm in user_perms:
            lists.append(perm.id)

        permission_id = permission.id
        if permission_id in lists:
            raise forms.ValidationError(u'This Permission already exists')
        return codename

views.py

class DeletePermission(LoginRequiredMixin, View):
login_url = '/accounts/login/'
redirect_field_name = 'next'

form_class = AssignPermissionForm
initial = {'group_name': ''}
template_name = 'permission/delete_permission.html'

def get(self, request, *args, **kwargs):
    data = {}
    if 'pk' in kwargs and kwargs['pk'] is not None:
        group = Group.objects.get(id=kwargs['pk'])
        data = {'group_name': group.name,
                'name': group.permissions.all(),
                }
        print "permission is", data['name']
        form = self.form_class(initial=data)
        user_list = []
        user_list.append({'group_name':group.name, "group_id":group.id, "permission":group.permissions.all()})

        return render(request, self.template_name, {'form': form})

0 个答案:

没有答案