Make Django's ModelChoiceField display as a dropdown with title and image

904 Views Asked by At

Below is my Django form. I would like to display a thumbnail and title together in a dropdown element, not as a radio button. With this configuration, it makes my form element a radio button.

What am I doing wrong, I cannot figure this out. If I change widget=forms.Select(), it creates a dropdown with only the title, but does not display the thumbnail beside the title.

class CustomChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return mark_safe("<img src='https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150'><p>"+str(obj.category)+"</p>")

countries_list = ImageModel.objects.all()

class SubCatForm(forms.Form):
    category_pic = CustomChoiceField(widget=forms.RadioSelect(), queryset=countries_list, empty_label=None)

    class Meta:
        model = SubCatModel
        fields = ("sub_category_name", "category", "category_pic")
        widgets = {
            'sub_category_name': forms.TextInput(attrs={'class':'span11'})
        }
0

There are 0 best solutions below