Loading lesson path
When you display a Model as a list, Django displays each record as the string representation of the record object, which in our case is "Member object (1)", "Member object(2)" etc.:
Formula
To change this to a more reader - friendly format, we have two choices:Change the string representation function, str() of the Member Model Set the list_display property of the MemberAdmin class
To change the string representation, we have to define the str() function of the Member Model in models.py, like this:
Formula
my_tennis_club/members/models.pyfrom django.db import models
class Member(models.Model):
Formula
firstname = models.CharField(max_length = 255)
lastname = models.CharField(max_length = 255)
phone = models.IntegerField(null = True)
joined_date = models.DateField(null = True)def __str__(self):
return f"{self.firstname} {self.lastname}"str() function is not a Django feature, it is how to change the string representation of objects in Python.
Python object tutorial. Set list_display We can control the fields to display by specifying them in a list_display property in the admin.py file.
class and specify the list_display tuple, like this:
Formula
my_tennis_club/members/admin.pyfrom django.contrib import admin from .models import Member
# Register your models here.
class MemberAdmin(admin.ModelAdmin):
Formula
list_display = ("firstname", "lastname", "joined_date",)admin.site.register(Member, MemberAdmin) Remember to add the MemberAdmin as an argumet in the admin.site.register(Member, MemberAdmin). Now go back to the browser and you should get this result: