我创建了一个自定义用户,如何将它们添加到组中?

时间:2019-10-31 16:57:35

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

我在名为Accounts的应用程序的整个过程中创建了一个名为OUser的自定义用户。我在默认的AuthUserGroups中定义了一些现有的组。如何将OUsers添加到组?尝试时,出现错误Invalid column name 'ouser_id'。要允许OUsers添加到我的预定义组中,我需要做什么?我是否需要创建一个自定义组模型来放置我的OUsers?无论如何,我有什么可以告诉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!

1 个答案:

答案 0 :(得分:0)

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

您将需要创建ManyToManyOUsers的不同Group关系形式,并且需要通过单独的表。

下面是将其添加到OUser模型的示例

from django.contrib.auth.models import Group

class OUsers(models.Model):
    ...
    groups = models.ManyToManyField(Group)

Docs在ManyToMany字段上