【问题标题】:I created a custom User, how do I add them to a group?我创建了一个自定义用户,如何将它们添加到组中?
【发布时间】:2020-02-27 02:11:39
【问题描述】:

我在我的项目中途创建了一个自定义用户,称为 OUser,在一个名为 accounts 的应用程序中。我在默认 AuthUserGroups 中定义了一些现有组。如何将 OUser 添加到组?当我尝试时,我得到一个错误,Invalid column name 'ouser_id'。我需要做什么才能允许将 OUser 添加到我的预定义组中?我是否必须创建自定义组模型来放置我的 OUser?无论如何我可以告诉 Auth_User_groups 它应该寻找 OUsers 吗?

accounts.admin

class OUserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserAdminChangeForm
    add_form = UserAdminCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    fieldsets = (
        ('Personal info', {'fields': ('first_name', 'last_name', 'email',)}),
        ('Permissions', {'fields': ('is_superuser', 'is_active', 'is_staff',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username',)}
        ),
    )
    search_fields = ('username',)
    ordering = ('username',)
    filter_horizontal = ()
    list_filter = ('is_superuser',)



admin.site.register(OUser, OUserAdmin)
'''



There are also other dependencies on things, such as Auth_Group_permission, but I assume that it will be a similar fix to switching Auth_Group to using OUser. 

How would I make groups contain references to Ouser. I have tried just swapping the Foreign key of the user_id in AuthUserGroups to contain a reference to OUser, but that didn't work. Maybe I missed something?

Thanks for the help!

【问题讨论】:

    标签: django-models django-admin django-authentication


    【解决方案1】:

    AuthUserGroups 是一个表,其中包含UserGroup 之间的ManyToMany 关系。它对这些模型有外键约束。您不能拥有与 OUsersUser 都具有外键关系的字段

    您需要创建一个不同的ManyToMany 关系表单OUsersGroup,它通过一个单独的表。

    这是一个将其添加到 OUser 模型的示例

    from django.contrib.auth.models import Group
    
    class OUsers(models.Model):
        ...
        groups = models.ManyToManyField(Group)
    

    Docs 在多对多字段上

    【讨论】:

    • 我应该在哪里添加新模型?它会放在我之前包含我的用户模型的主应用程序中,还是应该放在帐户 models.py 中?
    • ManyToManyField 将为您创建直通表,即使您没有指定。我在答案中添加了一个示例
    猜你喜欢
    • 1970-01-01
    • 2018-08-10
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多