Adding Custom Fields and Filters

Tutorial 2 of 5

Introduction

Welcome to our tutorial on adding custom fields and filters in the Django Admin panel. The Django Admin panel is a powerful tool that provides a user interface for managing your models. However, sometimes you may need to customize this interface to better fit your needs. This is where custom fields and filters come in.

By the end of this tutorial, you will learn how to:

  • Add custom fields to your Django Admin forms,
  • Create custom filters for your data.

Prerequisites: Basic understanding of Django, including its admin interface and model system.

Step-by-Step Guide

Adding Custom Fields

To add a custom field to your Django Admin form, you need to override the get_form method in your admin class.

class YourModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # Add your custom fields here
        return form

You can add a new field to the form by simply assigning a new field object to it.

form.new_field = forms.CharField()

Creating Custom Filters

To create a custom filter for your data, you need to create a subclass of admin.SimpleListFilter and add it to the list_filter attribute of your admin class.

class YourFilter(admin.SimpleListFilter):
    # Define your filter here

class YourModelAdmin(admin.ModelAdmin):
    list_filter = (YourFilter,)

Code Examples

Example 1: Adding a Custom Field

Suppose you want to add a custom field called "Reviewer Notes" to the admin form of a model called "Book".

from django import forms
from django.contrib import admin
from .models import Book

class BookAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # Add a new field called 'reviewer_notes'
        form.reviewer_notes = forms.CharField()
        return form

admin.site.register(Book, BookAdmin)

In this code, the get_form method is overridden to add a new field called "Reviewer Notes". The CharField is a simple text input field.

Example 2: Creating a Custom Filter

Suppose you want to add a custom filter that filters books by their publication year.

from django.contrib import admin
from .models import Book

class YearFilter(admin.SimpleListFilter):
    title = 'year'  # A title for the filter
    parameter_name = 'year'  # The query string name for this filter

    def lookups(self, request, model_admin):
        # Returns a list of tuples. The first element in each
        # tuple is the value for the queryset. The second element is the
        # human-readable name for the option.
        return [(year, year) for year in Book.objects.values_list('year', flat=True).distinct()]

    def queryset(self, request, queryset):
        # Returns the filtered queryset based on the value provided in the query string.
        if self.value():
            return queryset.filter(year=self.value())

class BookAdmin(admin.ModelAdmin):
    list_filter = (YearFilter,)

admin.site.register(Book, BookAdmin)

In this code, YearFilter is a custom filter that filters books by their publication year. The lookups method returns a list of tuples, each representing a filter option. The queryset method returns the filtered queryset.

Summary

In this tutorial, you have learned how to add custom fields and filters in the Django admin interface. You can now tailor the admin interface to your needs, improving your workflow and productivity.

Further learning can involve looking into more complex field types and filter options, as well as other ways to customize the Django admin interface.

Practice Exercises

  1. Add a custom field to the admin form of a model in your Django project. The field should be a text input field with a default value.
  2. Create a custom filter for a model in your Django project. The filter should allow you to filter objects by a boolean field.
  3. Add a custom field and a custom filter to the admin form of a model. The field should be a date input field, and the filter should allow you to filter objects by a date range.

Remember, the key to mastering Django is practice. Don't hesitate to experiment with different field types and filter options. Happy coding!