Customizing Django Admin: List Display and Search Fields

beginner
13 min

Customizing Django Admin: List Display and Search Fields

Welcome back, coders! Today, we're diving into the wonderful world of Django Admin, specifically focusing on customizing the list display and search fields. By the end of this lesson, you'll be able to make your Django Admin more organized and user-friendly. Let's get started!

What is Django Admin? 🎯

Django Admin is a powerful web-based interface that allows you to manage your database easily. It comes built-in with Django and provides a simple, yet powerful way to interact with your data.

List Display and Search Fields: Why Customize? πŸ“

By default, Django Admin displays a list of objects for each model. However, sometimes you might want to display additional information or make it easier for users to search for specific objects. That's where customizing list display and search fields comes in handy.

List Display 🎯

To customize the fields displayed in the list view, you need to define a list_display attribute in your model's Meta class.

Here's a simple example:

python
from django.contrib.admin import modeladmin, list_display from myapp.models import MyModel class MyModelAdmin(modeladmin.ModelAdmin): list_display = ('field1', 'field2',) admin.site.register(MyModel, MyModelAdmin)

In this example, field1 and field2 are the fields you want to display in the list view.

Search Fields 🎯

To make it easier for users to search for specific objects, you can define a search_fields attribute in your model's Meta class.

Here's an example:

python
from django.contrib.admin.options import modeladmin, ModelAdmin from django.contrib.admin.utils import fieldset_contained_in_request from myapp.models import MyModel class MyModelAdmin(ModelAdmin): list_display = ('field1', 'field2',) search_fields = ('field1', 'field2',) admin.site.register(MyModel, MyModelAdmin)

In this example, users can now search for objects by field1 and field2.

Practical Example πŸ’‘

Let's say we have a Product model with fields name, price, description, and stock. To display name, price, and stock in the list view, and to allow searching by name and price, our ProductAdmin would look like this:

python
from django.contrib import admin from .models import Product class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') search_fields = ('name', 'price',) admin.site.register(Product, ProductAdmin)

Quiz 🎯

Quick Quiz
Question 1 of 1

What attribute is used to define the fields displayed in the list view?

That's it for today! In the next lesson, we'll explore more advanced customization options for Django Admin. Until then, happy coding! πŸŒŸπŸ’»πŸŽ‰