From c0f36f307e724a9a7a0e3b5b3e495cc058c3c020 Mon Sep 17 00:00:00 2001 From: Fer-Bar Date: Thu, 23 May 2024 19:54:53 -0400 Subject: [PATCH] Added picture profile in admin section, declaring the field as a readonly --- pet/admin.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/pet/admin.py b/pet/admin.py index 0f87689..7e9b6d9 100644 --- a/pet/admin.py +++ b/pet/admin.py @@ -1,4 +1,6 @@ from django.contrib import admin +from django.utils.safestring import mark_safe +from django.utils.translation import gettext_lazy as _ from pet.filters import HasOwnerFilter from pet.models import Breed, Pet @@ -8,9 +10,33 @@ class PetAdmin(admin.ModelAdmin): search_fields = ["name", "owner"] list_display = ("name", "breed", "gender", "age", "owner", "has_owner", "is_neutered") - readonly_fields = ("age", ) + readonly_fields = ("age", "picture_display",) list_filter = (HasOwnerFilter,) + def picture_display(self, obj=None): + return mark_safe( + f'' + ) + + picture_display.short_description = _("Profile Picture") + + def get_fieldsets(self, request, obj=None): + if obj is None or not obj.picture_url: + picture_fields = [ + ("picture",), + ] + else: + picture_fields = [ + ("picture_display", "picture"), + ] + return ( + ( + None, { + "fields": picture_fields + [("name", "breed", "gender", "age"), ] + } + ), + ) + @admin.register(Breed) class BreedAdmin(admin.ModelAdmin): @@ -19,4 +45,5 @@ class BreedAdmin(admin.ModelAdmin): class PetInline(admin.TabularInline): model = Pet + fields = ("name", "breed", "gender") extra = 0