【发布时间】:2021-04-16 13:27:59
【问题描述】:
我已经覆盖了 UserAdmin 类,并希望将用户配置文件和一些相关对象添加为内联对象。
Userprofile 按预期工作,但对于 ManyToMany 关系,我现在得到一个包含相关对象的表。这对我的应用程序来说并不是很理想,更改相关对象有点麻烦,并且不需要这种方式添加新对象。
我想要一个包含相关对象的简单 MultipleChoiceField。有没有简单的方法来实现这一点?
这是我的用户资料/admin.py:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from django_admin_listfilter_dropdown.filters import RelatedOnlyDropdownFilter
from driverslog.models import Branch
from driverslog.models import Car
from .models import Userprofile
User = get_user_model()
class ProfileInline(admin.TabularInline):
model = Userprofile
can_delete = False
max_num = 0
extra = 0
fk_name = 'user'
class CarInline(admin.TabularInline):
model = Car.users.through
can_delete = True
verbose_name = _('Car')
verbose_name_plural = _('Cars')
extra = 0
class BranchInline(admin.TabularInline):
model = Branch.users.through
can_delete = True
verbose_name = _('Branch')
verbose_name_plural = _('Branches')
extra = 0
class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline, BranchInline, CarInline)
list_display = ('username', 'first_name', 'last_name', 'is_staff', 'is_superuser', 'represents')
list_filter = ('is_active', 'is_staff', 'is_superuser', ('groups', RelatedOnlyDropdownFilter),
('branches', RelatedOnlyDropdownFilter), ('profile__represent', RelatedOnlyDropdownFilter),
('car', RelatedOnlyDropdownFilter))
def represents(self, obj):
return obj.profile.represent.count()
represents.short_description = _('Represents')
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
【问题讨论】:
标签: python django django-admin