django - 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.
解决方案
<option>
element 不支持其中的任何子元素。您需要使用一些 javascript 库将选项转换为一组列表 ( <li>
)。这是一个示例https://www.addwebsolution.com/blog/adding-image-select-list-with-cross-browser-compatibility
推荐阅读
- c# - ValidationMessageFor 不显示错误信息
- java - Spring boot + Kotlin + MongoDb: Cannot resolve reference to bean 'mongoTemplate' while setting bean property
- c++ - 将 int 转换为 int* 会发生什么?
- java - 用于 ElasticSearch 多字段搜索的 Java API
- graphql - 如何使用 Prisma 和 GraphQL 创建自解析对象类型数组
- azure-cosmosdb - 使用 azure-documentdb-java 的 Azure Cosmos DB 分页
- android - Xamarin UI Test Click the 3 dots to expand menu and select menu item
- java - Dynamic filtering for objects arraylist java
- amazon-web-services - Aws sdk for .NET custom region endpoint configuration
- c# - 构造多部分 MIME 消息而不将其保存在内存中