【问题标题】:Django does's recognize variable in img src(template)Django 确实可以识别 img src(template) 中的变量
【发布时间】:2016-07-30 21:54:33
【问题描述】:

我正在尝试使用循环在模板中列出我的类别,而 django 不将变量识别为变量(我认为是这样)。是的,我需要的所有静态文件都在他们的文件夹中。 这是我的看法:

def home(request):
    if request.user.is_authenticated():
        return render_to_response('useractions/home.html', {
            'ann' : Announcement.objects.all().order_by('-creation_date')[:3],
            'categories' : ['Garden', 'Moving','Cleaning', 'Babysitting', 'Cooking', 'Others']
       })
    else:
        return render(request, 'basicpages/index.html')

还有我的 for in 模板:

{% for kind in categories %}
                <li id="cat1" style="background-image: url({% static "images/categories/{{ kind }}-background.jpg" %});">
                    <a href=''>
                        <span class="cbp-ig-icon"><img src="{% static "images/categories/{{ kind }}-icon.png" %}"></span>
                        <h3 class="cbp-ig-title">{{ kind }}</h3>
                        <span class="cbp-ig-category"> Dă click aici pentru mai multe</span>
        </a>
                </li>
{% endfor %}

在 shell 中我看到这样的东西:

[09/Apr/2016 16:16:54] "GET /static/images/categories/%7B%7B%20kind%20%7D%7D-icon.png HTTP/1.1" 404 1837
[09/Apr/2016 16:16:55] "GET /static/images/categories/%7B%7B%20kind%20%7D%7D-background.jpg HTTP/1.1" 404 1855

【问题讨论】:

  • 尝试使用"/images/category/{{ kind }}-background.jpg"
  • 我得到同样的错误。

标签: python django python-2.7 django-templates django-views


【解决方案1】:

试试看:

<img src="{% static 'images/categories/'%}{{ kind }}-icon.png">

【讨论】:

  • 不,我只知道这个:“/static/images/categories/HTTP/1.1" 404 1760"
  • 如果存在例如“127.0.0.1/static/images/categories/Garden-icon.png”,则编辑后的版本应该可以工作。
  • 嗯/static/images/categories/Garden-icon.png 不是url,是位置,是照片,而且照片确实存在
  • 当然。当服务器运行时,它仍然应该可以通过浏览器直接访问。这是为了测试您的静态变量是否设置正确。
  • 是的,网址返回给我图片。
猜你喜欢
  • 2021-09-30
  • 2010-10-20
  • 1970-01-01
  • 2011-04-02
  • 1970-01-01
  • 2019-02-25
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
相关资源
最近更新 更多