[Answered ]-Render image to a choice/char field in Django admin

1👍

If you really want the image in a select menu, that’s a bit tricky since an <option> cannot have an <img> inside it, and I’d suggest looking at this question to figure which type of solution you want to take for that: How to add images in select list?

Since it sounds as though you don’t necessarily want a drop down and there are only a few images, you could perhaps use a radio group instead.

One way you could do this with Django would be to subclass the RadioSelect widget and override the option_template_name class variable like this:

from django import forms

class SimbolRadioSelect(forms.RadioSelect):
    option_template_name = 'myapp/forms/widgets/simbol_radio_option.html'

Then you’ll need to create the template specified in the option_template_name class variable:

{% load static %}
<label{% if widget.attrs.id %} for="{{ widget.attrs.id }}"{% endif %}>
    <input type="{{ widget.type }}"
           name="{{ widget.name }}"
           value="{{ widget.value|stringformat:'s' }}"
           {% include "django/forms/widgets/attrs.html" %}>
    {% if widget.value %}
        <img src="{% get_media_prefix %}{{ widget.value|stringformat:'s' }}">
    {% else %}
        {{ widget.label }}
    {% endif %}
</label>

I came up with this template mostly by looking at the radio_option.html and other templates in the django source code: https://github.com/django/django/tree/main/django/forms/templates/django/forms/widgets

Then you’ll want to use it in your form (or create one if you don’t have one already):

from django import forms

class SimbolAdminForm(forms.ModelForm):
    class Meta:
        fields = '__all__'
        widgets = {
            'simbol_oznaka': SimbolRadioSelect,
        }

Then you can use the form in your Admin class:

from django.contrib import admin

class SimbolAdmin(admin.ModelAdmin):
    form = SimbolAdminForm

admin.site.register(Simbol, SimbolAdmin)

Then you’ll end up with this in the admin:

Two radio inputs for the first option 'No Image' and the second option an image with some shapes

Leave a comment