How to register a model with Django admin

So you’ve created a new model in Django, migrations are generated and executed, but how do you now see that model in the admin site? Read on to learn how.

To register a model with the admin site, open admin.py and add a reference to the model:

from django.contrib import admin
from .models import <modelname>

admin.site.register(<modelname>)

The model will then appear in the admin panel:

If you click on the model, You’ll see the list of entries, below I have entered some values for interest rates, you’ll notice that the list isn’t very readable:

We can customise how the entries are displayed in the model.py file, we can define the returned string within the model class:

def __str__(self):
    return <string_to_return>

For example:

class rates(models.Model):

  name = models.CharField(max_length=20, blank=True)
  rate = models.FloatField()

  def __str__(self):
    return "{} - {}".format(self.name, self.rate)

The admin view is then updated to reflect the string we defined above:

This can be customised further by defining the columns to display, in admin.py, replace the line where we register the model:

admin.site.register(rates)

With a mode detailed definition:

@admin.register(rates)
class ratesAdmin(admin.ModelAdmin):
  list_display = ('id', 'name', 'rate')

The resulting list in the view is formatted as per the above registration definition: