7

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

3 Answers 3

9

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')
0

Although @domino's answer may work for now, the "kinda" recommended approach is to use formset's self._should_delete_form(form) function together with self.can_delete.

There's also the issue of calling super().clean() to perform standard builtin validation. So the final code may look like:

class UserGroupsInlineFormset(forms.models.BaseInlineFormSet):
    def clean(self):
        super().clean()
        if any(self.errors):
            return  # Don't bother validating the formset unless each form is valid on its own
        for form in self.forms:
            if self.can_delete and self._should_delete_form(form):
                if <...form.instance.is_admin...>:
                    raise ValidationError('...')
0

Adding to domino's Answer:

In some other scenarios, Sometimes user wants to delete and add object in the same time, so in this case delete should be fine!

Optimized version of code:

class RequiredImageInlineFormset(forms.models.BaseInlineFormSet):
    """ Makes inline fields required """

    def clean(self):
        # get forms that actually have valid data
        count = 0
        delete_checked = 0
        for form in self.forms:
            try:
                if form.cleaned_data:
                    count += 1
                    if form.cleaned_data['DELETE']:
                        delete_checked += 1
                    if not form.cleaned_data['DELETE']:
                        delete_checked -= 1
            except AttributeError:
                # annoyingly, if a subform is invalid Django explicity raises
                # an AttributeError for cleaned_data
                pass

        # Case no images uploaded
        if count < 1:
            raise forms.ValidationError(
                'At least one image is required.')

        # Case one image added and another deleted
        if delete_checked > 0 and ProductImage.objects.filter(product=self.instance).count() == 1:
            raise forms.ValidationError(
                "At least one image is required.")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.