Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating delete on django-admin inline forms

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

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?

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

like image 972
domino Avatar asked Nov 29 '10 13:11

domino


Video Answer


1 Answers

The solution I found was to clean in the InlineFormSet instead of the 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')
like image 98
domino Avatar answered Sep 19 '22 12:09

domino