Django Admin custom foreign key select box

1.1k Views Asked by At

I want to customize Django admin select box and show thumbnail in the select box next to the image title

I have a class called Image and another class called News, that has a foreign key to the Image.

Note: I use Django jet as admin template.

class Image(models.Model):
    alternate = models.CharField(
        verbose_name=_('Alternate'),
        max_length=255,
        null=True,
        blank=True
    )
    title = models.CharField(
        verbose_name=_('Title'),
        max_length=255,
        null=True,
        blank=True
    )
    artist = models.ManyToManyField(
        'Artist',
        verbose_name=_('Artist'),
        blank=True
    )
    image = models.ImageField()

    def __str__(self):
        return "({}) {}".format(self.pk, self.title)

    class Meta:
        verbose_name = _('Image Attachment')
        verbose_name_plural = _('Image Attachments')

    @staticmethod
    def autocomplete_search_fields():
        return 'title',

class News(BaseModel):
    title = models.CharField(
        verbose_name=_('Title'),
        max_length=255,
        null=True,
        blank=True
    )
    summery = RichTextField(
        verbose_name=_('Summery'),
        null=True,
        blank=True,
    )
    main_image = models.ForeignKey(
        Image,
        verbose_name=_('Main Image'),
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='images'
    )

Now I want to show the thumbnail of the image in choices in Django admin when I want to add news.

Now my select box look like this

My issue

1

There are 1 best solutions below

2
On

You will need to create a custom widget that inherits from Select, the most important part it seems will be setting the option_template_name to be a template that you create to show the image. Since you are using something other than the base Django Admin, you may want to look into extending the widgets in that Library.

Something along the lines of:

class SelectWithImage(Select):
    ...
    option_template_name = 'myapp/forms/widgets/select_option_with_image.html'
    ...

Then adjust the admin formfield_overrides for the News model in your admin.py as described here and you should be good to go!

This step will look something like this:

from django.contrib import admin
from django.db import models

# Import our custom widget and our model from where they're defined
from myapp.models import News
from myapp.widgets import SelectWithImage

class NewsAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ForeignKey: {'widget': SelectWithImage},
    }