Welcome back to CodeYourCraft! Today, we're diving into Admin Actions, a powerful feature of Django that helps manage your applications efficiently.
By the end of this lesson, you'll be able to create, update, delete, and perform custom actions on your Django models. Let's get started! π
Admin Actions are methods defined in Django's admin.py file for specific models. They allow you to perform various tasks like creating, updating, deleting, and even custom actions on your application data through the Django admin interface.
π‘ Pro Tip: Admin Actions are a must for managing data in real-world projects, as they provide an easy and efficient way to maintain your application's database.
Let's create an action to mark a BlogPost as featured.
SimpleListFilter and actions from django.contrib.admin.from django.contrib import admin
from django.contrib.admin.actions import Action
from django.contrib.admin.filters import SimpleListFilterclass MakeFeatured(Action):
description = "Mark selected blog posts as featured."
def change_list_view(self, request, model_admin, queryset):
queryset.update(is_featured=True)class FeaturedFilter(SimpleListFilter):
title = "Featured"
parameter_name = "is_featured"
def lookups(self, request, model_admin):
return (
("Yes", "Yes"),
("No", "No"),
)
def queryset(self, request, queryset):
if self.value() == "Yes":
return queryset.filter(is_featured=True)
elif self.value() == "No":
return queryset.exclude(is_featured=True)
return querysetclass BlogPostAdmin(admin.ModelAdmin):
list_filter = (FeaturedFilter,)
actions = [MakeFeatured]Now, when you visit the Django admin interface for BlogPosts, you'll see the "Mark as Featured" action and the "Featured" filter.
Which line in the code above updates the is_featured field for the selected blog posts?
For our second example, let's create an action to delete multiple blog posts at once.
class DeleteMultiple(Action):
description = "Delete multiple blog posts at once."
def __call__(self, request, queryset):
for obj in queryset:
obj.delete()
return queryset.count()class BlogPostAdmin(admin.ModelAdmin):
actions = [DeleteMultiple]Now, when you visit the Django admin interface for BlogPosts, you'll see the "Delete multiple" action.
How many blog posts are deleted by the `DeleteMultiple` action?
And there you have it! With these examples, you've learned how to create custom actions for your Django applications. Happy coding! ππ»
π‘ Pro Tip: Remember to customize these actions according to your application's needs for efficient data management.
Stay tuned for more Django tutorials here at CodeYourCraft! π
Types for this lesson:
Action: A Django class representing an admin action that can be performed on a model.SimpleListFilter: A Django class for creating filters for the change list view.ModelAdmin: A Django class that represents an admin configuration for a model.