Django在RadioSelect或Checkboxes上显示图像 [英] Django display image on RadioSelect or Checkboxes
问题描述
我是django的新手,我正在尝试将数据库中的图片显示在radiobutton或复选框上。我该怎么做?
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?
我有这个型号
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())
但是如何将这个img标签放入标签?
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.
推荐答案
使用 ModelForm
进行一些惯例:
第一个子类 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)
现在:
class CatForm(forms.ModelForm):
items = CustomChoiceField(widget=forms.RadioSelect, queryset=MyItems.objects.all())
class Meta:
model = categories
现在使用此表单而不是 catForm
。如果您之前没有使用过 ModelForm
,请参阅django文档了解详细信息。
now use this form instead of your catForm
. If you haven't used ModelForm
before please see the django documentation for details on this.
这篇关于Django在RadioSelect或Checkboxes上显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!