django admin中的访问请求属性

时间:2018-08-12 23:00:41

标签: python django forms request django-admin

我正在Django中开发应用程序,并将请求添加到用户创建表单的某些干净方法中,当我尝试对管理站点中的User进行一些更新时,出现错误,该请求为None ,显然,该参数并未像我在视图中请求时那样添加到表单中,在很多平台中搜索了此答案,但无法解决我的问题。
首先,我表单的init方法添加了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')


现在使用请求属性“清理组”字段:

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']


最后,我要为用户设置管理员:

class MyAdmin(auth_admin.UserAdmin):
    save_on_top = True
    fieldsets = (
        ('Personal Info', {
            'fields': ('image_tag', 'avatar', 'email', 'password', 'first_name', 'last_name', 'date_joined', 'last_login')
        }),
        ('Relationships', {
            'fields': ('groups', 'user_permissions', 'user_institution')
        }),
        ('User status', {
            'fields': ('is_active', 'is_staff', 'old_password')
        }),
        )
    form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = auth_admin.AdminPasswordChangeForm
    list_filter = ('user_institution', 'groups')
    readonly_fields = ('last_login', 'date_joined', 'image_tag')
    list_display = ('get_full_name', 'email', 'is_staff', 'last_login')
    filter_horizontal = ['groups', 'user_permissions', 'user_institution',]

0 个答案:

没有答案