Django admin using the request attributes

Asked

Viewed 136 times

2

I am developing an application in Django and I used the request data on form to validate some fields.

For example, if the user is changing the form for the "Administrator" group, when changing the user password he does not need to enter the old password.

However, when I save a user change in admin, it gives an error precisely because it is not receiving the attribute request.

Below follow the codes of form where I used the clean method for certain attributes. Someone knows how to receive the attributes from request in admin?

Modified init method to receive a request:

def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    super(UserChangeForm, self).__init__(*args, **kwargs)
    f = self.fields.get('user_permissions', None)
    if f is not None:
        f.queryset = f.queryset.select_related('content_type')

Clean method for the field groups:

def clean_groups(self):
    if self.request.user.groups.all() or self.request.user.is_staff:
        if self.request.user.groups.filter(name="Administrador") or self.request.user.is_staff:
            return self.cleaned_data['groups']
        else:
            if list(self.cleaned_data['groups']) == list(self.request.user.groups.all()):
                return self.cleaned_data['groups']
            else:
                raise forms.ValidationError(
                    self.error_messages['non_administrator'],
                    code='non_administrator',
                    )
    elif not self.request.user.groups.all() and self.cleaned_data['groups']:
        raise forms.ValidationError(
            self.error_messages['non_administrator'],
            code='non_administrator',
            )
    elif not self.request.user.groups.all() and not self.cleaned_data['groups']:
        return self.cleaned_data['groups']
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.