我有一个在我的管理员用户模型视图中禁止用户的功能。但我不确定如何将该被禁用户添加到Banned_User
模型。
#Banning function
def ban_users(self, request, queryset):
queryset.update(is_active = False)
banned_user = Banned_User.objects.create(profile=profile)
banned_user.save()
self.message_user(request, "User banned")
def remove_ban(self, request, queryset):
print(queryset)
queryset.update(is_active = True)
self.message_user(request, "Users ban has been lifted")
#Profile Admin view
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')
def total_reports(self, obj):
return Report.objects.filter(user_reported=obj).count()
admin.site.register(Profile, ProfileAdmin)
#User Admin View
class MyUserAdmin(UserAdmin):
list_display = ('profileview','username', 'first_name', 'last_name' , 'email')
readonly_fields = ('first_name' , ('last_name') , ('email') , ('username'))
actions = ['ban', 'unban']
ban = ban_users
unban = remove_ban
def profileview(self, instance):
return instance.profile.user
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
(个人资料模型向用户提供OneToOneField)
我的禁止用户模型如下:
class Banned_User(models.Model):
def __str__(self):
return self.user.get_username
profile = models.ForeignKey(
'Profile',
on_delete=models.PROTECT,
blank=False,
null=False,
related_name='banned_profile'
)
report_reason = models.ForeignKey(
'report',
on_delete=models.PROTECT,
blank=False,
null=False,
related_name='reason_banned',
)
date_banned = models.DateField(null=True, blank=False,)
当前错误有:名称'个人资料'未定义,但我不确定我添加到表格中的代码是否正确。
答案 0 :(得分:1)
def ban_users(modeladmin, request, queryset):
queryset.update(is_active = False)
banned_user = Banned_User.objects.create(profile=request.user.profile)
banned_user.save()
self.message_user(request, "User banned")
def remove_ban(modeladmin, request, queryset):
print(queryset)
queryset.update(is_active = True)
self.message_user(request, "Users ban has been lifted")
确保将上部函数写入此admin.py
文件或将其导入
class MyUserAdmin(UserAdmin):
list_display = ('profileview','username', 'first_name', 'last_name' , 'email')
readonly_fields = ('first_name' , ('last_name') , ('email') , ('username'))
actions = [ban, unban]
def profileview(self, instance):
return instance.profile.user
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
检查函数inputs
中的更改以及ModelAdmin