Dori's Python Life in Words Journal

Admin panel


# blog/admin.py

from django.contrib import admin

from blog.models import Post


@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ["title", "slug", "author", "publish", "status"]
    list_filter = ["status", "created", "publish", "author"]
    search_fields = ["title", "body"]
    prepopulated_fields = {"slug": ("title",)}
    raw_id_fields = ["author"]
    date_hierarchy = "publish"
    ordering = ["status", "publish"]
    show_facets = admin.ShowFacets.ALWAYS

Note:

It is even possible to search for ForeignKey relations with the search_fields.

This is the syntax:

search_fields = ["foreign_key__related_fieldname"]

In our case I could use the FormeignKey relation of user to search for it, like:

search_fields = ["user__email"]

So, I would be able to search for a user instance by email address.

Legend:

    • list_display: By default, your admin panel will display the __str__() representation of each object, and by using the list_display obtion, you can specify which attributes of the model are displayed in the admin panel. Note that a ForeignKey field will display the __str__() representation of the related object, ManyToManyFields are not supported and if you want to display a BooleanField, Django will display a pretty 'yes' or 'no' or 'unknown' icon.
    • list_filter: When the list_filter option is set, you activate a filter option on the right-hand side of the admin panel. In my case, I used the list option to simply filter the filenames.
    • search_fields: Adding search_fields adds a search bar at the top of the page to the admin panel. The fields used in the list of search_fields should be all kinds of text fields, such as CharField or TextField.

Designed by BootstrapMade and modified by DoriDoro