我在DJango的视图中看不到ImageField的照片[解决]

时间:2017-05-07 20:56:51

标签: python django

我的Django项目失败了,因为我在图片中加载的图片不会在视图中显示。

https://www.dropbox.com/sh/fvx6sfmxgm08xo6/AABVR-AQGeF52pCxlzVaLuDaa?dl=0

螃蟹的照片加载了"静态",但第二张照片是它的图像区域照片。

enter image description here

型号:

class foto(models.Model):
    nombre=models.CharField(max_length=50)
    imagen=models.ImageField(upload_to='fotos/')
    def __str__(self):
        return self.nombre

查看:

def general(request):
    lista=foto.objects.all()
    context={'material':lista}
    return render(request,'indice.html',context)

设置:

STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'
STATICFILES_DIRS = (
'/media/fotos/',
    )

HTML:

{% load staticfiles %}
<html>
    <head>
        <title>Album de fotos</title>
    </head>
    <body>
        <img src="{% static 'cangrejo.jpg' %}" />
        {% if material %}
            {% for a in material %}
                <li>{{a.nombre}}: {{a.imagen}}</li>
                <img src="{{a.imagen}}" />
            {% endfor %}
        {% else %}
            <p>No hay fotos</p>
        {% endif %}
    </body>
</html>

管理员的网址:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'',include('colecion.urls')),
]

查看网址:

from django.conf.urls import url, include
from colecion import views

urlpatterns =[
    url(r'^$',views.general),
]

编辑:我已经解决了问题!

settings.py

STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'ciencia/static')

models.py

foto=models.ImageField()

HTML

<img src="{% static alfa.foto %}" />

2 个答案:

答案 0 :(得分:0)

来自文档:

MEDIA_URL - &#34;将保存用户上传文件的目录的绝对文件系统路径。&#34;

MEDIA_ROOT - &#34;处理从MEDIA_ROOT提供的媒体的URL,用于管理存储的文件。如果设置为非空值,则必须以斜杠结尾。您需要配置这些文件以在开发和生产环境中提供。&#34;

您当前的配置MEDIA_URL看起来不正确。它应该是一个URL,您将它设置为文件系统路径。尝试像

这样的东西
MEDIA_URL = '/media/'

答案 1 :(得分:0)

将此添加到urls.py

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

{{a.imagen}}更改为{{a.imagen.url}}

相关问题