在django-admin内联表单上验证删除

时间:2022-10-05 14:12:46

I am trying to perform a validation such that you cannot delete a user if he's an admin. I'd therefore like to check and raise an error if there's a user who's an admin and has been marked for deletion.

我正在尝试执行验证,如果他是管理员,则无法删除用户。因此,如果用户是管理员并且已被标记为删除,我想检查并引发错误。

This is my inline ModelForm

这是我的内联ModelForm

class UserGroupsForm(forms.ModelForm):
    class Meta:
        model = UserGroups

    def clean(self):
        delete_checked = self.fields['DELETE'].widget.value_from_datadict(
            self.data, self.files, self.add_prefix('DELETE'))
        if bool(delete_checked):
            #if user is admin of group x
            raise forms.ValidationError('You cannot delete a user that is the group administrator')

        return self.cleaned_data

The if bool(delete_checked): condition returns true and stuff inside the if block gets executed but for some reason this validation error is never raised. Could someone please explain to me why?

if bool(delete_checked):condition返回true并且if块内的东西被执行但由于某种原因,这个验证错误永远不会引发。有人可以向我解释原因吗?

Better yet if there's another better way to do this please let me know

更好的是,如果还有另一种更好的方法,请告诉我

1 个解决方案

#1


7  

The solution I found was to clean in the InlineFormSet instead of the ModelForm

我发现的解决方案是在InlineFormSet而不是ModelForm中清理

class UserGroupsInlineFormset(forms.models.BaseInlineFormSet):

    def clean(self):
        delete_checked = False

        for form in self.forms:
            try:
                if form.cleaned_data:
                    if form.cleaned_data['DELETE']:
                        delete_checked = True

            except AttributeError:
                pass

        if delete_checked:
            raise forms.ValidationError(u'You cannot delete a user that is the group administrator')

#1


7  

The solution I found was to clean in the InlineFormSet instead of the ModelForm

我发现的解决方案是在InlineFormSet而不是ModelForm中清理

class UserGroupsInlineFormset(forms.models.BaseInlineFormSet):

    def clean(self):
        delete_checked = False

        for form in self.forms:
            try:
                if form.cleaned_data:
                    if form.cleaned_data['DELETE']:
                        delete_checked = True

            except AttributeError:
                pass

        if delete_checked:
            raise forms.ValidationError(u'You cannot delete a user that is the group administrator')