Django Imagefield网址不包含MEDIA_ROOT

时间:2015-02-28 09:53:55

标签: python django image

我有一个带有ImageField的模型,并通过CreateForm创建了一个简单的上传表单。我有一个简单的ListView来显示图像(徽标)。

上传工作正常,迭代徽标可行。 Property logo.url缺少,但它是logo.media。不幸的是,媒体不包含整个路径,缺少MEDIA_ROOT。我在这里做错了什么?

models.py:

class Logo(models.Model):
    media = models.ImageField(upload_to='uploads')

views.py:

class LogoManager(CreateView):
  model = Logo
  template_name = 'polls/upload.html'
  success_url = '/logos/'

class LogoIndex(ListView):
  model = Logo
  template_name = 'polls/logos.html'

upload.html:

{% block title %} Upload Form {% endblock %}
{% block content %}

<form id="my_form" action="" method="post" enctype="multipart/form-data">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save Changes" />
</form>
<br />
<a href="{% url 'polls:index' %}">Back</a>
{% endblock %}

logos.html:

{% block content %}
  {% if object_list %}
    <ul>
      {% for image in object_list %}
        <li><img src="{{ image.media }}" width="320" height="200"/></li>
      {% endfor %}
    </ul>
  {% else %}
    <p>No Logos are available.</p>
  {% endif %}
<br />
{% endblock %}

输出是:

<li><img src="uploads/IMG_5106.JPG" width="320" height="200"/></li>

2 个答案:

答案 0 :(得分:0)

我想你会想要使用{{ image.media.url }}

答案 1 :(得分:0)

好的,这是我的错。我正在编辑应用程序url文件中的url。在root urls.py中添加此节时,它可以正常工作:

if settings.DEBUG:
urlpatterns += patterns('django.views.static',
    (r'%s(?P<path>.*)' % settings.MEDIA_URL, 'serve', {'document_root': settings.MEDIA_ROOT}),
)

使用settings.py:

MEDIA_URL =  '/media/'