ImageField中的图像不会加载到模板中

时间:2015-07-19 11:46:01

标签: python django django-templates imagefield

我正在创建一个房地产代理网站。每个优惠都有几张照片,其中一张照片在管理面板中作为主照片标记后,应该显示在索引页面上,但遗憾的是它不是。

我认为问题出在Document doc = Jsoup.connect("example http") .data("name","myname") .data("pass","mypass") .data("x","1") .post(); views.py中。 index.htmlSettings.py似乎没问题,因为我可以通过在浏览器中输入图片的确切网址来访问指定的图片(例如... / media / photos / name_of_the_image.jpg) - 然后图像显示在浏览器中。

Models.py:

urls

Views.py:

class Offer(models.Model):

    category = models.ForeignKey(Category)
    city = models.CharField(max_length=128)
    district = models.CharField(max_length=128)
    floor_space = models.IntegerField()
    price = models.IntegerField()

    def __unicode__(self):
        return "Offer nb %s" % (self.id)


class OfferImage(models.Model):

    offer = models.ForeignKey(Offer, related_name='images')
    images = models.ImageField(upload_to='photos/', blank=True, null=True)
    main_image = models.BooleanField(default=False)

Urls.py:

def index(request):
    category_list = Category.objects.all
    latest_offers = Offer.objects.order_by('-pub_date')[:10]

    context_dict = {
        'categories': category_list,
        'latest_offers': latest_offers,
                    }

    return render(request, 'cardom/index.html', context_dict)

的index.html:

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

if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)',
         'serve',
         {'document_root': settings.MEDIA_ROOT}), )

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

问题出在哪里?

1 个答案:

答案 0 :(得分:1)

当你写:

{{ offer.images.url }}

您得到的是一个空白字符串,因为offer.imagesRelatedManager,并且没有网址属性。

您应该使用专用管理器或视图中的其他查询来检索相应的图像:

main_images = offer.images.filter(main=True)
try:
    image = main_images[0]
except:
    image = None # Or whatever you want

您还可以避免这种情况向Offer模型添加额外的属性main_image(但您必须为admin编写相应的逻辑)。