我正在尝试采用另一种方法来解决我在下面描述的使用 django-select2 模块的问题。
Django choicefield using pictures instead of text not displaying
我有一个 django 模型,它看起来像:
我的模型看起来像:
class MyPicture(models.Model):
name = models.CharField(max_length=60,
blank=False,
unique=True)
logo = models.ImageField(upload_to='logos')
def __str__(self):
return self.name
我想创建一个下拉菜单看起来像
来源:http://select2.github.io/select2/
基本上我在左边有一张大图片(对应于我所说的 Logo ),右边有一些文字(对应于名称)。
我的表格看起来像:
from django_select2.forms import Select2MultipleWidget
class MyPictureForm(forms.Form):
pictures = forms.ModelChoiceField(widget=Select2MultipleWidget, queryset=MyPicture.objects.all())
我的观点是这样的:
def mypicture(request):
form = MyPictureForm(request.POST or None)
if form.is_valid():
#TODO
return render(request, 'myproj/picture.html', {'form': form})
最后,我的 hmtl(有问题的地方):
{% load staticfiles %}
<head>
{{ form.media.css }}
<title>In construction</title>
</head>
<form action="{% url 'mypicture' %}" method="post">
{% csrf_token %}
<select id="#e4" name="picture">
{% for x in form.pictures.field.queryset %}
<option value="{{ x.id }}"><img src="{{ MEDIA_URL }}{{ x.logo.url }}" height=150px/></option>
{% endfor %}
</select>
<br>
<br>
<input type="submit" value="Valider" class="btn btn-primary"/>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
function format(x) {
if (!x.id) return x.name; // optgroup
return "<img src=" + x.logo.url + "/>" + x.name;
}
$(document).ready(function () {
$("#e4").select2({
formatResult: format,
formatSelection: format,
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
});
</script>
{{ form.media.js }}
</form>
不幸的是,我无法判断我的错误是在 javascript 中还是在循环中。当我右键单击以获取源代码时,选项已正确设置。所以我一定离答案不远。
对于那些比我有更多 javascript 经验的人来说,这可能是微不足道的。
感谢您的帮助!
最佳:
埃里克
最佳答案
我认为(大多数)浏览器不允许 <option>
中的任何内容-除了纯文本之外的标记。
这就是 Mozilla 对 <option>
允许内容的说法-标签:
Permitted content: Text, possibly with escaped characters (like é).`
来源:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option
但不确定是否可以将某些内容设置为背景。
关于javascript - 将 django-select2 用于带有图片的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52899128/