Reputation: 75
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.
Upvotes: 0
Views: 1774
Reputation: 1402
<option>
element doesn't support any child elements inside it. You would need to use some javascript library to convert the options to a set of lists (<li>
). Here's an example https://www.addwebsolution.com/blog/adding-image-select-list-with-cross-browser-compatibility
Upvotes: 1