如何显示图像? Django的

时间:2017-03-27 19:55:45

标签: django

我尝试在标签中插入“静态”,但不会返回图像。而是它返回一个白色的盒子。用户可以上传自己的照片。存储它的目录是Aviation -> Uploads -> Aircraft。我到底哪里错了?

list.html

<div class="box"><img src="{{ aircraft.image }}" />

设置。吡啶

STATIC_URL = '/static/'
STATICFILES_DIRS = [ map_path('static'),]

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

View.py

def list_aircraft(request):
  aircraft = Aircraft.objects.all()
  favorited_aircraft_ids = None

  if request.user.is_authenticated():
    favorited_aircraft_ids = list(FavoritedAircraft.objects.filter(user__id=request.user.id).values_list('id', flat=True))
    print (favorited_aircraft_ids)

  return render(request, 'aircraft/aircraft_list.html', {
    'aircraft': aircraft,
    'favorited_aircraft_ids': favorited_aircraft_ids,
  })

Model.py

class Aircraft(AircraftModelBase):
    manufacturer = SortableForeignKey(Manufacturer)
    aircraft_type = SortableForeignKey(AircraftType)
    body = SortableForeignKey(Body)
    engines = models.PositiveSmallIntegerField(default=1)
    image = models.ImageField(upload_to="uploads/aircraft", blank=True, null=True)
    cost = models.DecimalField(max_digits=8, decimal_places=3)
    maximum_range = models.PositiveSmallIntegerField()
    passengers = models.PositiveSmallIntegerField()
    maximum_altitude = models.PositiveIntegerField()
    cruising_speed = models.PositiveIntegerField()
    fuel_capacity = models.DecimalField(max_digits=6, decimal_places=2)
    description = models.TextField()
    wing_span = models.PositiveSmallIntegerField(default=1)
    length = models.PositiveSmallIntegerField(default=1)

1 个答案:

答案 0 :(得分:1)

飞机是一个查询集(可能是很多飞机对象)

aircraft = Aircraft.objects.all()

您必须在此查询集上迭代(在模板中)才能访问真实对象,例如:

{% for a in aircraft %}
    <img src="{{ a.image.url }}" />
{% empty %}
    The aircarft queryset is empty
{% endfor %}

我认为你的飞机模型有一个ImageField,因此,要获得图像网址,你必须使用&#34; aircraft.image.url&#34;如果调用ImageField&#34;图像&#34;。 &#34;空&#34;如果您的查询集为空,模板标记将显示。如果消息&#34; aircarft查询集为空&#34;如果没有显示,那么您应该查看浏览器开发人员工具,了解媒体文件的网络分发中的任何问题