尝试在Django ADMIN中从外部用户模型调用is_active方法

时间:2018-05-03 02:19:32

标签: python django django-admin

这里我有一个禁止和取消禁用用户的功能。目前我可以在我的自定义用户模型中使用DjangoAdmin。 但我想要做的是禁止用户使用我的DjangoAdmin中的 Profile 模型。

然而,我一直在/ admin / api / profile /
收到 错误的FieldDoesNotExist 个人资料没有名为“is_active”的字段 ,因为is_active是用户模型的一个功能。我不知道如何在管理员的配置文件模型视图中禁止用户或如何将is_active连接到Profile模型。

#Banning Function
 def ban_users(self, request, queryset):
     queryset.update(is_active = False)
     self.message_user(request, "User is banned and Email has been sent")

 def remove_ban(self, request, queryset):
     queryset.update(is_active = True)
     self.message_user(request, "Users ban has been lifted")

 #Admin functions will be created here,as well as registration  of their specific models

 class ReportAdmin(admin.ModelAdmin):
     list_display = ('user_reported', 'report_reason', 'sent_by', 'session')
 admin.site.register(Report, ReportAdmin)

 class ProfileAdmin(admin.ModelAdmin):
     list_display = ('user', 'birth_date', 'sessions_played', 'total_reports')
     readonly_fields = (('sessions_played'),('birth_date'),('user'),('pref_server'),('teamwork_commends'),('skill_commends'),('sportsmanship_commends'),('communication_commends'),('discord_name'))#,'total_reports')
     actions = ['ban', 'unban']
     ban = ban_users
     unban = remove_ban

 def total_reports(self, obj):
     return Report.objects.filter(user_reported=obj).count()

 admin.site.register(Profile, ProfileAdmin)

 class MyUserAdmin(UserAdmin):
     list_display = ('username', 'first_name', 'last_name' , 'email')
     readonly_fields = ('first_name' , ('last_name') , ('email') , ('username'))
     actions = ['ban', 'unban']
     ban = ban_users
     unban = remove_ban
 admin.site.unregister(User)
 admin.site.register(User, MyUserAdmin)

2 个答案:

答案 0 :(得分:1)

动作函数假定查询集将始终包含User个对象,但由于您对ProfileAdmin使用相同的动作函数,因此它们还需要处理Profile个对象。

def ban_users(self, request, queryset):
    for obj in queryset:
        if hasattr(obj, 'user'):
            # This object is a Profile, so lookup the user
            obj = obj.user
        obj.is_active = False
        obj.save()
    self.message_user(request, "User is banned and Email has been sent")

请注意queryset.update()函数cannot be used to update columns on related models,因此您无法执行queryset.update(user__is_active = False)

答案 1 :(得分:0)

通过查看您的密码,请看看我的想法 未经测试的理论

由于is_activeUser的字段,因此我们可以queryset检查QuerysetUser还是Profile

知道个人资料有一个传统的OneToOneField用户,正如我在许多项目中看到的那样

def ban_users(self, request, queryset):
    # select an instance from queryset
    instance = queryset.first()
    if instance.__class__.__name__ == 'Profile'
        queryset.update(user__is_active = False)
    else:
        queryset.update(is_active = False)
    self.message_user(request, "User is banned and Email has been sent")