在django teplate中从多个字段获取图像
它返回一个错误:找不到:/post detail/6/images/wallper002.jpg。我试图通过{{post_detail.img.all.first.url}显示图像,但我可以在模板中显示图像,它不返回任何值 news.html ''' ''' views.py ''' ''' url.py '''在django teplate中从多个字段获取图像,django,django-views,django-templates,Django,Django Views,Django Templates,它返回一个错误:找不到:/post detail/6/images/wallper002.jpg。我试图通过{{post_detail.img.all.first.url}显示图像,但我可以在模板中显示图像,它不返回任何值 news.html ''' ''' views.py ''' ''' url.py ''' app_name='posts' URL模式=[ 路径(“”,HomePageView.as_view(),name=“”), 路径('post-detail/',PostDetail
app_name='posts'
URL模式=[
路径(“”,HomePageView.as_view(),name=“”),
路径('post-detail/',PostDetailView.as_-view(),name=“post_-detail”)
]+静态(settings.MEDIA\u URL,document\u root=settings.MEDIA\u root)
''您正在使用当前代码访问
Pictures
类的实例。然后需要访问img
属性:
<div class="text-center">
<img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first.img.url }}">
</div>
我还建议您防止在许多领域没有实例的情况
{% if post_detail.img.all.first %}
<div class="text-center">
<img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first.img.url }}">
</div>
{% endif %}
{%if post\u detail.img.all.first%}
{%endif%}
我还建议研究和/或作为更有效获取这些相关细节的方法。它将帮助您防止N+1查询。您可以验证您没有使用运行过多的查询。看起来该特定帖子的
img
字段的集合为空,这就是为什么.first()/。first
返回None
@schillingt,但它有集合“/post detail/6/”
from django.shortcuts import render, redirect
from django.contrib import messages
from django.views import View
from .models import Post, Pictures
from django.views.generic import DetailView
from . import models
from django.shortcuts import get_object_or_404
class HomePageView(View):
def get(self, request):
posts = Post.objects.all()[:4]
context = {'posts': posts}
return render(request, 'index.html', context)
class PostDetailView(DetailView):
context_object_name = "post_detail"
model = models.Post
template_name = 'news.html'
app_name = 'posts'
urlpatterns = [
path('', HomePageView.as_view(), name=""),
path('post-detail/<int:pk>/', PostDetailView.as_view(), name="post_detail")
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<div class="text-center">
<img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first.img.url }}">
</div>
{% if post_detail.img.all.first %}
<div class="text-center">
<img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first.img.url }}">
</div>
{% endif %}