Search code examples
pythondjangomodeladmin

How to move model to the other section in Django's site admin


Is it possible to move default Groups model from 'Authentication and Authoriation' section (on the Django admin site) to custom one and how to achieve that?

Let's start from the beginning in the other words.

I have a very simple application 'accounts' in my Django project.

models.py file looks like below:

from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    def __str__(self):
        return self.email

serializers.py file:

from rest_framework import serializers
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group


class UserSerializer(serializers.HyperlinkedModelSerializer):
    groups = serializers.HyperlinkedRelatedField(
        many=True,
        required=False,
        read_only=True,
        view_name="group-detail"
    )

    class Meta:
        model = get_user_model()
        exclude = ('user_permissions',)

Now, on the admin site I have two sections: 'Accounts' and 'Authentication and Authorization'. 'Accounts' section contains my 'Users' table (for User model) and 'Authentication and Authorization' section contains 'Groups' table (for Django's default authorization Group model).

My question is - is it possible and how to move Groups table (model) to the 'Accounts' section?

I've even tried to create a custom 'Group' model based on Django's default auth Group model but have stuck on migration exceptions.


Solution

  • Is it possible to move default Groups model from 'Authentication and Authoriation' section (on the Django admin site) to custom one and how to achieve that?

    Yes, it's possible.

    1) You can move your model to section auth, just add to your class:

    class Meta:
        app_label = 'auth'
    

    2) You can move Group and User models to your app section, for that variant need to:

    Override user model and add it to your app

    from django.contrib.auth.models import AbstractUser
    
    
    class CustomUser(AbstractUser):
        pass
    

    also need add to your project settings AUTH_USER_MODEL = 'your_app.CustomUser'

    Don't forget declare in admin.py from your app:

    class UserAdmin(admin.ModelAdmin):
        pass
    
    
    admin.site.register(CustomUser, UserAdmin)
    

    For group model put this code in admin.py:

    from django.db.models.loading import get_models
    from django.contrib.auth import models
    
    models = get_models(models)
    models[1]._meta.app_label = 'your_app'
    

    3) You can look at django-admin-tools