In today's short article, I will discuss adding nonmodel fields to list_display in Django Admin.
Django has a powerful built-in admin panel. But sometimes we need extra customization.
But today I want to talk about especially list_display field. I will show you how to add “nonmodel” and “many to many ” fields to list_display.
Now initially let's create our models. I will create two simple models Category and Product.
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Categories"
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ManyToManyField(Category)
price = models.IntegerField()
discount = models.IntegerField()
def __str__(self):
return self.name
Adding custom fields to list_display
Now let’s look at some useful examples based on our models.
In the admin.py file, we will create custom methods and include its name in list_display.
from django.contrib import admin
from django.utils.html import format_html
from .models import Category, Product
class ProductAdmin(admin.ModelAdmin):
list_display = ["name", "price", "discount_p", "discounted_price", "product_link", "categories"]
def discount_p(self, obj):
return f"{obj.discount} %"
def discounted_price(self, obj):
return f"{obj.price - obj.price * obj.discount / 100} $"
def product_link(self, obj):
return format_html(
'<a href="https://127.0.0.1:8000/product/{0}" >{1}</a> ',
obj.id, obj.name
)
def categories(self, obj):
return list(obj.category.all())
admin.site.register(Category)
admin.site.register(Product, ProductAdmin)
Now let’s explain the above code.
- Formatting existing model field.
def discount_p(self, obj):
return f"{obj.discount} %"
Here we formatted the model’s discount field. Added a dollar sign at the end of the value.
2. Adding custom nonmodel field.
def discounted_price(self, obj):
return f"{obj.price - obj.price * obj.discount / 100} $"
def product_link(self, obj):
return format_html(
'<a href="https://127.0.0.1:8000/product/{0}" >{1}</a> ',
obj.id, obj.name
)
Here we created new custom nonmodel fields.
In the first method, we calculated discounted prices.
With the next method, we created a product link.
3. Adding ManytoMany relationships.
def categories(self, obj):
return list(obj.category.all())
And finally, here, we create a list of the categories.
To sum up, we can create custom list_display items by creating methods and including them in list_display. With this option, Django gives us big opportunities to customize the admin panel.
Thanks for reading. I hope you enjoyed it ❤. If you found the article useful don’t forget to clap and follow me.
This is my #10/52 story in 2023, I’m on a challenge to write 52 stories in 2023.
Keep Learning..!