How to do it...

In this recipe, we will create a simple administration for the Product model that will have instances of the ProductPhoto model attached to the product as inlines.

In the list_display property, we will include the first_photo() method of the model admin, which will be used to show the first photo from the many-to-one relationship. So, let's begin: 

  1. Let's create an admin.py file that contains the following content:
# myproject/apps/products/admin.py
from django.contrib import admin
from django.template.loader import render_to_string
from django.utils.html import mark_safe
from django.utils.translation import ugettext_lazy as _

from .models import Product, ProductPhoto


class ProductPhotoInline(admin.StackedInline):
model = ProductPhoto
extra = 0
fields = ["photo"]
  1. Then, in the same file, let's add the administration for the product:
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ["first_photo", "title", "has_description",
"price"]
list_display_links = ["first_photo", "title"]
list_editable = ["price"]

fieldsets = ((_("Product"), {"fields": ("title", "slug",
"description", "price")}),)
prepopulated_fields = {"slug": ("title",)}
inlines = [ProductPhotoInline]

def first_photo(self, obj):
project_photos = obj.productphoto_set.all()[:1]
if project_photos.count() > 0:
photo_preview = render_to_string(
"admin/products/includes/photo-preview.html",
{"photo": project_photos[0], "product": obj},
)
return mark_safe(photo_preview)
return ""

first_photo.short_description = _("Preview")

def has_description(self, obj):
return bool(obj.description)

has_description.short_description = _("Has description?")
has_description.admin_order_field = "description"
has_description.boolean = True
  1. Now, let's create the template that will be used to generate the photo-preview, as follows:
{# admin/products/includes/photo-preview.html #}
{% load imagekit %}
{% thumbnail "120x120" photo.photo -- alt=
"{{ product.title }} preview" %}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.86.134