【问题标题】:Using django-select2 for a dropdown list with pictures使用 django-select2 获取带有图片的下拉列表
【发布时间】:2019-03-24 17:52:41
【问题描述】:

我正在尝试采用另一种方法来解决我在下面使用 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/

本质上,我在左边有一张大图(对应于我所说的徽标),在右边有一些文字(对应于名称)。

我的表格如下:

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 经验的人来说,这可能是微不足道的。

感谢您的帮助!!

最佳:

埃里克

【问题讨论】:

    标签: javascript html django jquery-select2


    【解决方案1】:

    我认为(大多数)浏览器不允许在 &lt;option&gt;-tag 中包含纯文本之外的任何内容。

    这是 Mozilla 关于&lt;option&gt;-tags 允许内容的说法:

    允许的内容:文本,可能带有转义字符(如 é).`

    来源:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option

    不确定是否可以将某些内容设置为背景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多