Custom Fields

Learn how to add custom fields and custom links.

Adding custom fields

So far you have seen that you can use list_display to display model fields in the list page of the admin. But it is also possible to display a custom field that does not exist in the model.

For instance, if you want to display a new field in a new column to indicate that a question has been published or will be published in the future, you can create a has_been_published function inside the QuestionAdmin class and also add this property to the list_display list:

list_display = ('question_text', 'refAuthor', 'has_been_published', 'pub_date', 'createdDate', 'updatedDate',)
list_display_links = ('question_text', 'refAuthor',)

def has_been_published(self, obj):
	present = datetime.now()
	return obj.pub_date.date() < present.date()

The new has_been_published field has been added in the list_display and its value is being calculated within the function: has_been_published(self, obj). This is how it works: You need to define a function with the name of your new field added and passing the parameters self and obj (which represents the instance of the model).

If you go to your question list page in your admin, you can see the new column has_been_published with a value of True or False.

Get hands-on with 1200+ tech skills courses.