在模型中的Django模板中显示图像

时间:2019-12-12 08:17:01

标签: python django

我有一个django模型,可以在django模型中存储一些图像,但是当我尝试显示此图像时,它显示的是残破的图像符号,而不是图像。

Models.py

class Uploaded_pod(models.Model):
    document = models.FileField(upload_to='pods/')
    lr_connected = models.ForeignKey(DeliveredDocket, on_delete=models.CASCADE, related_name='delivered_pod')

Views.py

#upload POD
def pod_upload (request, pk):
    lr_object = get_object_or_404(DeliveredDocket, id=pk)
    print(lr_object)
    if request.method == 'POST':
        form = UploadPODform(request.POST, request.FILES)

        if form.is_valid():
            obj = form.save(commit=False)
            obj.lr_connected = lr_object
            obj.save()
            messages.success(request, 'The POD was Uploaded with success!')
            return redirect('employee:delivered_docket_table')

    else:
        form = UploadPODform()
        form.lr_connected = lr_object

    return render(request, 'packsapp/employee/model_form_upload.html', {'form': form})

#show pod
def list(request,pk):
    print("function called with pk ",pk)

    images = Uploaded_pod.objects.filter(lr_connected = pk)
    return render(request, "packsapp/employee/list.html", {'images': images})

HTML

{% extends 'base.html' %}

{% block content %}

{% for i in images %}
    <img src="{{ i.image.url }}" width="500px"/>
{% endfor %}

{% endblock %}

Settings.py

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

我做错了什么?请帮忙!

1 个答案:

答案 0 :(得分:1)

我假设您存储的图像带有文档名称,所以称它为

{% for i in images %}
    <img src="{{ i.document.url }}" width="500px"/>
{% endfor %}

还要在您的设置中添加以下内容

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn")

和主网址中

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