Django – Show model objects in Django Admin and apply format filter

We can easily scaffold the persisted objects list, add and delete pages on Django Admin by registering your model in your app admin.py file. For example, an app named eureka with model Person.

eureka/models.py

from django.db import models

class Person(models.Model):
  name     = models.CharField(max_length=256)
  homepage = models.URLField(max_length=256)

  def __unicode__(self):
    return self.name

 

eureka/admin.py

from django.contrib import admin
from eureka.models import Person

admin.site.register(Person)

 

Start the server and you can login to the Django Admin to add new Person.
django-admin-show-objects-and-apply-filter-1

By default the listing table will only show the field which u defined in def __unicode__(self) in models.py. In order to show more useful information, we need to override the default admin.ModelAdmin page. Alter the admin.py as follow.

eureka/admin.py

from django.contrib import admin
from eureka.models import Person

class PersonAdmin(admin.ModelAdmin):
  list_display = ('name', 'homepage')

admin.site.register(Person, PersonAdmin)

 

Reload the page and there should be name and home page columns.
django-admin-show-objects-and-apply-filter-2
 

Instead of showing the homepage url in plain text, i would like to make it into a anchor link. Update the admin.py again as follow.

from django.contrib import admin
from eureka.models import Person

class PersonAdmin(admin.ModelAdmin):  
  list_display = ('name', 'view_homepage_link')

  def view_homepage_link(self, obj):
    return '<a href="%s" target="_blank">%s</a>' % (obj.homepage, obj.homepage,)
  view_homepage_link.allow_tags = True
  view_homepage_link.short_description = 'Homepage' # Optional

admin.site.register(Person, PersonAdmin)

 

Check it out again.
django-admin-show-objects-and-apply-filter-3
 

Done =)

Reference:

Advertisement

One thought on “Django – Show model objects in Django Admin and apply format filter”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.