Django Admin Inlines和AbstractUser

时间:2018-04-24 23:16:43

标签: python django

我在尝试在admin.py中使用MtoM时遇到问题。 我一直收到错误消息: <class 'demo.admin.CustomUserAdmin'>: (admin.E013) The value of 'fieldsets[2][1]["fields"]' cannot include the ManyToManyField 'groups', because that field manually specifies a relationship model.

#admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from app.forms import CustomUserCreationForm, CustomUserChangeForm
from app.models import User, GroupUser, RoleAssign

class GroupUserInline(admin.TabularInline):
    model = GroupUser

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = User
    inlines = [ GroupUserInline, ]

admin.site.register(User, CustomUserAdmin)

这些是我的模特:

#models.py
class Group(models.Model):
    name  = models.CharField(max_length=240)
    roles = models.ManyToManyField(Role, through='RoleAssign')

class User(AbstractUser):
    username   = models.CharField(max_length=240, blank=False, null=False, unique=True)
    password   = models.CharField(max_length=256, blank=False, null=False)
    email      = models.EmailField(max_length=256, blank=False, null=False, unique=True)
    S3         = models.TextField()
    groups     = models.ManyToManyField(Group, through='GroupUser')

class GroupUser(models.Model):
    user  = models.ForeignKey(settings.AUTH_USER_MODEL)
    group = models.ForeignKey(Group)

有没有人知道为什么我的内联可能无法正常工作?或者我应该尝试不同的方法吗?

1 个答案:

答案 0 :(得分:0)

尝试在model = User.groups.through

中使用GroupUserInline

查看更多here,我认为这可以为您提供帮助。