user2478240
user2478240

Reputation: 369

Django display image on RadioSelect or Checkboxes

I am new to django and I am trying to display pictures from a database onto a radiobutton or checkbox. How do I do that?

I have this model

class MyItems(models.Model):
itemName=models.CharField(max_length=100)
itemDesc=models.CharField(max_length=400)
itemImage=models.ImageField(upload_to='pictures')

class categories(models.Model):
catName=models.CharField(max_length=100)
items=models.ManyToManyField(MyItems)

Users uploads pictures to a page, and they can categories them into categories.

I could do this to make it show my choices

class catForm(forms.Form):
catName=forms.CharField()
items=forms.ChoiceField(widget=forms.RadioSelect,choices=(MyItems.objects.all())

but how do I put something like this img tag into the label?

<img src="itemImage.url" /> 

Went through many tutorials but none of them generates images from the database.

Upvotes: 1

Views: 2478

Answers (1)

sha256
sha256

Reputation: 3099

Use ModelForm with a bit of customaization:

First sub class the ModelChoiceField

from django.utils.safestring import mark_safe


class CustomChoiceField(forms.ModelChoiceField):

    def label_from_instance(self, obj):
        return mark_safe("<img src='%s'/>" % obj.itemImage.url)

Now:

class CatForm(forms.ModelForm):
  items = CustomChoiceField(widget=forms.RadioSelect, queryset=MyItems.objects.all())

  class Meta:
     model = categories

now use this form instead of your catForm. If you haven't used ModelForm before please see the django documentation for details on this.

Upvotes: 2

Related Questions