Django admin use the request attributes

3

I'm developing an application in Django and have used the request data in form to validate some fields.

For example, if the user who is changing form is from the "Administrator" group, changing the user's password does not have 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 request attribute.

Below are the form codes where I used the clean method for certain attributes. Does anyone know how to get the attributes of request in admin?

Init method changed to receive 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 groups field:

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']
    
asked by anonymous 12.08.2018 / 17:22

0 answers