Search code examples
django-modelsdjango-admindjango-authentication

I created a custom User, how do I add them to a group?


I created a Custom User midway through my project, Called OUser, in an app called accounts. I have some existing groups defined in the default AuthUserGroups. How do I add OUsers to a group? When I try, I get an error, Invalid column name 'ouser_id'. What do I need to do to allow OUsers to be added to my predefined groups? Do I have to create a custom group model to put my OUsers? Is there anyway that I can over tell Auth_User_groups that it should be looking to 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!

Solution

  • AuthUserGroups is a table which holds the ManyToMany relationships between User and Group. It has foreign key constraints to these models. You can't have a field which has a foreign key relationship to both OUsers and User

    You would need to create a different ManyToMany relationship form OUsers to Group that goes through a separate table.

    Here is an example on to add it to the OUser model

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

    Docs on ManyToMany fields