Django Admin

Posted by Daksh on Monday, August 8, 2022

Admin

Need of admin

Django provides a powerful admin interface that you can use to manage content on your site. The admin is a great way to add, change, and delete content on your site. It’s also a great way to customize the admin interface to suit your needs.

The admin is enabled by default. To get started, create a user account for yourself. Then, log in to the admin and start adding content.

The module django.contrib.admin provides the admin site. It’s already installed in your project’s INSTALLED_APPS setting, so you don’t need to do anything to enable it.

This admin site is not meant for end users. It’s for site owners and administrators. It lets you manage content and data administration on your site.

Django automatically create a Unified admin interface for site owners and administrators to Add, Change, and Delete content on their site. This content can include users, permissions, groups, and database entries. The Admin Interface directly links to all the models in the project once registered. You can also check the history of the user and the changes they have made.

Creating an admin user

  1. Visit the admin login page at http://127.0.0.1:8000/admin/

  2. Quit the server with CTRL-C.

  3. Inside your project, create a superuser account. Run the following command:

    python manage.py createsuperuser
    Username (leave blank to use 'daksh'): daksh
    # if a username is already taken
    # Error: That username is already taken.
    Email address: daksh@test.com
    Password:
    Password (again):
    Superuser created successfully.
    
  4. Start the server again with python manage.py runserver.

  5. Visit the admin login page again at http://127.0.0.1:8000/admin/

  6. Log in with the superuser account you just created.

  7. You should see the Django admin dashboard.

Adding Models to the Admin

  1. Open the app_name/admin.py file, and edit it to look like this:

    from django.contrib import admin
    
    from .models import Entity
    
    admin.site.register(Entity)
    
  2. The text you see on the “Entity” page is generated from the __str__() method in the Entity model. If you don’t have a __str__() method, Django will use __repr__().

  3. Click on the “Entities” link to see the list of entities. You can add, edit, and delete entities from this page.

  4. For autogenerated slug fields, use blank=True and unique=True. This will allow you to create multiple entities with the same name, but each will have a unique slug. And moreover, you can create an entity without a slug, and Django will automatically generate one for you without throwing a required field error. You can also add editable=False to the slug field to make it read-only in the admin.

  5. editable=False is useful for autogenerated fields like slug and created_at and updated_at fields. You don’t want the user to edit these fields in the admin. You want them to be automatically generated when the model is saved. Moreover, you don’t want the user to see these fields in the admin. You want them to be hidden from the user.

  6. It is advisable to use editable=True for autogenerated slug from title fields. This will help administrators to resolve slug conflicts. For example, if you have two entities with the same title, you can edit the slug of one of them to make it unique.

  7. You can also remove autogenerated slug and make it prepopulated from title on admin dashboard.

Customizing the Admin

Although the admin is powerful, it’s not perfect. You can customize the admin to suit your needs. Sometimes, adding fields such as blank=True and editable=False is not enough. You may want to change the way the admin looks or works. For example, you may want to prepopulate the slug field with the title of the entity. You can do this by customizing the admin.

  1. Open the app_name/admin.py file, and edit it to look like this:

    from django.contrib import admin
    
    from .models import Entity
    
    # EntityAdmin is a preferred name for the admin class of the Entity model
    class EntityAdmin(admin.ModelAdmin):
        # readonly_fields is a tuple of fields that should be read-only in the admin
        readonly_fields = ('created_at', 'updated_at')
        # prepopulated_fields is a dictionary of fields that should be prepopulated with the value of another field
        # prepopulated_fields should not be used inside readonly_fields
        prepopulated_fields = {'slug': ('title',)}
        # you can also filter the list of entities by the field name
        list_filter = ('field_name1', 'field_name2')
        # you can also use list_display to display the fields in the list of entities
        list_display = ('title', 'field_name1', 'field_name2') # adds 3 columns for each field in the list of entities
        search_fields = ('title', 'field_name1', 'field_name2') # adds a search box to search entities by title and field_name1 and field_name2
    
    
    # Register the Entity model with the EntityAdmin
    admin.site.register(Entity, EntityAdmin)
    

Adding Meta Configuration to Models

To add meta configuration to your model, you can use a nested Meta class inside the model class.

from django.db import models

class Entity(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        # verbose_name_plural is the plural form of the model name
        verbose_name_plural = 'Entities Name'
        # ordering is a tuple of fields that should be used to order the entities
        ordering = ('-created_at',)

    def __str__(self):
        return self.title

Users, Groups, and Permissions

  • If a user’s is_staff property is set to True, it can log in to the admin interface. Users with a staff status can manage the other users. But they can also edit their own permissions, which is not warranted. A staff user can also allocate superuser rights.

  • To customize the User Admin, first, unregister the existing user profile and register a new one. To unregister the existing user profile, add the following code to app_name/admin.py:

    from django.contrib import admin
    from django.contrib.auth.admin import UserAdmin
    from django.contrib.auth.models import User
    
    # unregister the existing user profile
    admin.site.unregister(User)