首页 > 解决方案 > 如何在 Django 框架中正确显示图像到 html 模板?

问题描述

我已经尝试了一天尝试将保存到媒体文件夹的图像显示在我的模板文件中,但无济于事。图像已上传到 media/images 文件夹,但我不知道如何显示它们。我无法弄清楚我做错了什么,因为我看到很多人使用这些方法并得到了结果。我在想也许我的 post 函数没有将正确的数据返回到模板?我对 Django 和 html 非常陌生,所以请原谅我的错误。

这是我目前的设置:

设置.py

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

模型.py

from django.db import models

class Post(models.Model):
    post = models.ImageField(upload_to="images")

表格.py

from django import forms
from imageDetection.models import Post

class HomeForm(forms.ModelForm):
    class Meta: 

        model = Post 
        fields = ('post',)

视图.py

class HomeView(TemplateView):
    template_name = 'imageDetection/test.html'

    @staticmethod
    def detect(request):
        return render(request, 'imageDetection/detection.html')

    def get(self, request): 
        form = forms.HomeForm()
        return render(request, self.template_name, {'form': form})

    def post (self, request):
        context = {}
        if request.method == "POST":
            form = forms.HomeForm(request.POST, request.FILES)
            if form.is_valid():
                image_form = models.Post()
                image_form.post = form.cleaned_data['post']
                image_form.save()
                context['form'] = image_form
                return render (request, 'imageDetection/detection.html', context)
            else: 
                form = forms.HomeForm()
                context['form'] = form
        return render(request, self.template_name, context)

网址.py

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('imageDetection.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

模板/Detection.html

{% for post in form %}
    {% if post.image %}
        <img src="{{ MEDIA_URL }}{{ post.image.url }}" />
    {% endif %}
{% endfor %}

谢谢,任何帮助将不胜感激

标签: pythonhtmldjangoimagefieldfilefield

解决方案


在这里,我在您的模型中没有看到任何带有名称image的字段。您已经使用字段名称定义了图像post

 {% if post.post %}
        <img src="{{ post.post.url }}" />
 {% endif %}

并且在这里更好地为您的字段和上下文使用有意义的image变量。您可以使用而不是post和上下文 来命名您的图像字段而images不是forms


推荐阅读