Django admin

  • Django provides a default admin interface
  • It can be used to perform create, read, update and delete (CURD) operations on the model directly.
  • Provides a convenient interface to manage model data and visualize database

3.1 Activating and Using the Admin Interface

  • Add app in INSTALLED_APPS
  • And create Superuser
# Create superuser
python manage.py createsuperuser
# Enter --> email, username, password

# After create
python manage.py runserver
  • Visit localhost/admin
    • Login using username and password

3.2 Register models in admin-panel

  • Only after registration model is visible in admin-panel
  • 3 Ways for Registration
from customer.models import Customer
# Way 1
admin.site.register(Customer)

# Way 2
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
    pass

# Way 3
class CustomerAdmin(admin.ModelAdmin):
    pass
admin.site.register(Customer, CustomerAdmin)

3.3 Basic: Model display

# Attribute becomes link (clickable) on 'add page'
list_display_links = ()

# Limit no of items per page in admin panel
list_per_page = 25

# Add search instead of select --> for ForeignKey
raw_id_fields = ()

# Gets all the fields name
all_fields_name = [f.name for f in Adhar._meta.fields]

Sample

from django.contrib import admin
from customer.models import Customer

@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
    # ---> Display data - in Table Page
    list_display = ('f_name', 'get_is_active', 'mobile_is_verified', 'user')
    search_fields = ('=user__first_name',)
    list_editable = ('mobile_is_verified', )
    actions = ['mark_mobile_verified']
    # list_display_links = ('user', )
    list_filter = ('mobile_is_verified', 'email_is_verified')

    # Handle FK
    def get_is_active(self, obj):
        return obj.user.is_active

    # Apply a function
    def mark_mobile_verified(self, request, queryset):
        queryset.update(mobile_is_verified=True)
    mark_mobile_verified.short_description = 'Mark Ph no as Verified'
    
    
    # ---> Display data - of Each Row
    readonly_fields = ('email_id', 'mobile')
    exclude = ('lead_status', )
    # Grouping of fields - and fields that want to show
    # fields = (('f_name', 'l_name'), 'is_active')

3.4 Advance: Model display

https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fieldsets

  • fieldsets = ()
    • format (name, field_options),
    • name –> the title of the fieldset
    • field_options –> dictionary of information about the fieldset,
    • including a list of fields to be displayed in it.
    • collapse and wide –> are widely used classes
    • description –> About fields
fieldsets = (
    (name, {
        'description': 'info about the fields'
        'classes': ('collapse',),
        'fields': ('field1', 'field2')
    }),
)

Sample

from django.contrib import admin
from customer.models import Customer


@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):    
    # ---> Display data - of Each Row
    # Grouping Using Fieldsets
    fieldsets = (
        (None, {
            'fields': ('user', ('f_name', 'l_name'), 'mobile')
        }),
        ('Advanced options', {
            'classes': ('collapse',),
            'fields': ('create_datetime', 'campaign_ids'),
        }),
    )

3.5 InlineModelAdmin objects

  • Display two or more MODELS at the same admin-panel page
  • The admin interface has the ability to edit models on the same page as a parent model.
  • For different model-types has different ways of doing:
    • two or more foreign keys
    • many-to-many models
    • many-to-many intermediary models
  • Django provides two subclasses of InlineModelAdmin and they are:
    • TabularInline
    • StackedInline

TabularInline

https://docs.djangoproject.com/en/4.1/ref/contrib/admin/#working-with-many-to-many-models

class UserPermissionInline(admin.TabularInline):
    model = User.user_permissions.through

class GroupInline(admin.TabularInline):
    model = User.groups.through

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ('username', 'email', 'is_staff', 'is_superuser')
    exclude = ('user_permissions', 'groups')
    inlines = [
        UserPermissionInline,
        GroupInline
    ]

3.6 Changes in Admin panel (Logo, CSS)

  • admin.site.site_header = ‘Kharchapani Admin panel’
    • Changing the title of Django Admin, By default, this is “Django administration”
{% extends 'admin/base.html' %}
{% load static %}

<!-- TO Edit LOGO/Branding -->
{% block branding %}
  <h1 id="head">
    <img src="{% static 'img/logo.png' %}" alt="BT Real Estate" 
    height="50" width="80" class="brand_img"> Admin Area
  </h1>
{% endblock %}

<!-- To edit CSS -->
{% block extrastyle %}
  <link rel="stylesheet" href="{% static 'css/admin.css' %}">
{% endblock %}

Reference