首页 > 解决方案 > Django select option - displaying image in template

问题描述

I'm trying to create a select button that shows images with their title for a user to choose one from.

template

<select id="fabric-select" name="select-id">
    {% for item in fabric %}
        <option value="{{item.id}}">{{item.fabric_cover.url}}</option>
        <option value="{{item.id}}"><img src="{{item.fabric_cover.url}}" alt="fabric picture">{{item.name}}</option> 
        <option value="{{item.id}}" data-image="{{item.fabric_cover.url}}"></option>
    {% endfor %}
  </select>

Tried different options but none of them show the image itself. First option just shows me the static link of the image. Second option shows the name but nothing else and the third option shows an empty field.

From my view:

class ProductListView(ListView):
    queryset = Product.objects.all()
    def get_context_data(self, *args, **kwargs):
        context = super(ProductListView, self).get_context_data(*args, **kwargs)
        cart_obj, new_obj = Cart.objects.new_or_get(self.request)
        context['cart'] = cart_obj

        fabric_obj = Fabric.objects.all()
        context['fabric'] = fabric_obj

        return context

Model

class Fabric(models.Model):
    name         = models.CharField(max_length=120)
    fabric_cover = models.ImageField(upload_to='fabric_images', blank=False)

Unsure if it's simply not possible to grab the picture directly an put it in the option, if I'm using the wrong code for my template to output it or if I'm missing something to make this work.

标签: djangodjango-modelsdjango-formsdjango-templates

解决方案


<option>element 不支持其中的任何子元素。您需要使用一些 javascript 库将选项转换为一组列表 ( <li>)。这是一个示例https://www.addwebsolution.com/blog/adding-image-select-list-with-cross-browser-compatibility


推荐阅读