Django Starter 3 — Database Admin Panel

Rubaiyat Rahim
2 min readMay 22, 2024

--

Working with databases and tables using Admin panel.

Other parts of this series: Part 1 | Part 2 | Part 4 | Part 5 | Part 6

Create User and Login as Admin

# Make migrations to introduce in the database
py manage.py makemigrations

# Implement the migrations
py manage.py migrate

# Create a super user
py manage.py createsuperuser

# Run the server
py manage.py runserver

# Go to the page http://127.0.0.1:8000/admin
# and login using the user just created

Create Table/Model

  • Create the model class (Player) in models.py in the app folder (myproject\players\models.py) as follows:
from django.db import models

class Player(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
dateofbirth = models.DateField(null=True)
phonenumber = models.CharField(max_length=50)
  • Include the Player class in the admin interface (myproject\players\admin.py) as follows:
from django.contrib import admin
from .models import Player

# Register your models here.
admin.site.register(Player)
  • Create migration, then migrate, and then run the server.
py manage.py makemigrations
py manage.py migrate
py manage.py runserver
  • The Player model/table is shown now in the admin panel as follows:
Fig: Model shown in admin panel.

Setting the List Fields

  • Set display label for the list of Players to be seen in the admin panel by setting the string representation of the Players in (myproject\players\models.py) as follows:
from django.db import models

# Create your models here.
class Player(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
dateofbirth = models.DateField(null=True)
phonenumber = models.CharField(max_length=50)

def __str__(self):
return f"{self.firstname} {self.lastname}"

The list is now being shown as follows:

Fig: First name and last name being shown in the list of Players.
  • Fields to be displayed in the Players admin panel can be defined by a tuple also. Create a ModelAdmin class and supply the list_display tuple in the model registration call in (myproject\players\admin.py) as follows:
from django.contrib import admin
from .models import Player

# Register your models here.

class PlayerAdmin(admin.ModelAdmin):
list_display = ("firstname", "lastname", "dateofbirth",)

admin.site.register(Player, PlayerAdmin)

The list is now being shown as follows:

Fig: Several fields being shown in the list of Players.

--

--