Django
Admin Customization
Customize the Django admin with list_display and actions.
By EZ4Code Team
admincustomization
Code
from django.contrib import admin
from .models import Article
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ("title", "is_published", "views", "published_at")
list_filter = ("is_published", "published_at")
search_fields = ("title", "body")
prepopulated_fields = {"slug": ("title",)}
list_editable = ("is_published",)
date_hierarchy = "published_at"
ordering = ("-views",)
actions = ["publish_selected"]
@admin.action(description="Publish selected")
def publish_selected(self, request, queryset):
updated = queryset.update(is_published=True)
self.message_user(request, f"{updated} articles published.")Explanation
ModelAdmin customizes how models appear in the Django admin. list_display, list_filter, and search_fields shape the changelist table and filters. Custom actions receive the current request and selected queryset, then update records and report back via message_user.
More Django Snippets
Model Definition
Define a Django model with field types and meta options.
ORM QuerySet
Filter, exclude, annotate and chain QuerySets.
Class-Based Views
Use generic class-based views for common CRUD flows.
URL Routing
Wire URLs to views with path converters and includes.
ModelForms
Build forms from models with validation and widgets.
Template Tags
Use built-in tags and filters in Django templates.