python - 如何在 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 %}
谢谢,任何帮助将不胜感激
解决方案
在这里,我在您的模型中没有看到任何带有名称image
的字段。您已经使用字段名称定义了图像post
。
{% if post.post %}
<img src="{{ post.post.url }}" />
{% endif %}
并且在这里更好地为您的字段和上下文使用有意义的image
变量。您可以使用而不是post
和上下文 来命名您的图像字段而images
不是forms
推荐阅读
- apache-zookeeper - 重启后如何验证zookeeper服务器是否与集群同步
- swift - Swift JSON 编码和解码
- android - Flutter 小部件包裹在自定义小部件中
- javascript - Promise 的包装函数没有返回
- c++ - 无法理解范围解析运算符的使用
- php - PHP如何使用此代码读取文件内容
- java - 包含 1 个元素的数组是否占用与该 1 个元素相同的内存量?
- java - SetHasFixedSizetrue 显示错误 如何解决
- javascript - JavaScript 减去 reactJS 中使用的时间
- .net - 如何解决错误.net framework version were not found?