admin.py

Consider if models.py file is as follows

from django.db import models
from django.contrib.auth.models import User

class Org(models.Model):
    name = models.CharField(max_length=200)
    address = models.TextField()
    orgId = models.CharField(max_length=50, unique=True)

    # add specific plural name to be shown in admin panel for the model
    class Meta:
        verbose_name = 'Organization'
        verbose_name_plural = 'Organizations'

class Tag(models.Model):
    name = models.CharField(max_length=50)


class Opportunity(models.Model):
    status = models.CharField(max_length=50)
    description = models.TextField(null=True, blank=True)
    display_name = models.CharField(max_length=100)
    order_by = models.IntegerField(default=0)
    is_active = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    organization = models.ForeignKey('Org')
    tags = models.ManyToManyField('Tag')

Then admin.py file would be something like this

from django.contrib import admin
from .models import Opportunity

class adminOpportunity(admin.ModelAdmin): 
    list_display = ('get_orgId', 'display_name', 'status', 'order_by', 'is_active')
    list_display_links = ('get_orgId', 'display_name')
    list_editable = ['order_by', 'display_name', 'status'] 
    list_filter = ('is_active','created','modified')
    filter_horizontal = ('tags',) # available for many to meny  fields only
    raw_id_fields = ("organization",)
    search_fields = ('org__orgId', 'status') 

    # Choose fields that are displayed in admin form, all other fields that
    # not included in the list given below should probably have null=True, blank=True
    fields = ('display_name', 'status', 'organization')
    # or show every field in form except the specified below
    exclude = ('order_by',)
    # To display multiple fields on the same line, wrap those fields in their own tuple. 
    # In this example, the url and title fields will display on the same line and the 
    # content field will be displayed below them on its own line
    fields = (('url', 'title'), 'content')

    # to divide adimin form in sections with specific section headers 
    fieldsets = [
        (None,               {'fields': ['display_name', 'status']}),
        ('Related Organization', {'fields': ['organization'], 'classes': ['collapse']}),
    ]

    def get_orgId(self, obj): 
        return obj.org.orgId 
    get_orgId.short_description = 'Organization ID'   
    get_orgId.admin_order_field = 'org__orgId'
    get_orgId.empty_value_display = '???'

    class Meta:
        model = Opportunity

admin.site.register(Opportunity, adminOpportunity)

# add custome name to admin panel
admin.site.site_header = 'My Admin Panel'

Customizing admin site


results matching ""

    No results matching ""