我正在尝试使用 pillow 库中的 ImageField。我对此有疑问。
当我尝试显示我的图像时,出现错误:
/home 处的 TemplateSyntaxError 第 62 行的 block 标记无效:“articulo.nombre_imagen.url”,应为“空”或“endfor”。您是否忘记注册或加载此标签?
这是我的第 62 行:
<a href="article/id/{{articulo.id}}"><img class="card-img-top" img src="{% articulo.nombre_imagen.url %}" alt=""></a>
因为你可以使用我正确使用的语法,所以我应该...
这是来 self 的 models.py:
def upload_location(instance, filename):
return "static/img/" %(instance.id, filename)
class Articulo(models.Model):
nombre_imagen=models.ImageField(upload_to=upload_location,
null=True, blank=True,
width_field="width_field",
height_field="height_field")
width_field=models.IntegerField(default=0)
height_field=models.IntegerField(default=0)
有人可以帮忙吗?谢谢!
请您参考如下方法:
尝试使用 {{ }} 代替 {% %}:
<a href="article/id/{{ articulo.id }}"><img class="card-img-top" src="{{ articulo.nombre_imagen.url }}" alt=""></a>
更新。
在模板中:
<a href="article/id/{{ articulo.id }}"><img class="card-img-top" src="{% url 'preload_image' pk=articulo.pk %}" alt=""></a>
在 View 中:
def preload_image(request, pk)
from .models import Articulo
from django.http import HttpResponse
from PIL import Image
articulo = get_object_or_404(Articulo, pk=pk)
img = Image.open(articulo.nombre_imagen.path)
response = HttpResponse(content_type='image/%s' % img.format)
img.save(response, img.format)
response['Content-Disposition'] = 'filename="image.%s"' % img.format
return response
同时将该方法 preload_image 插入到 urls.py 中;以及 from .models 使用你的 from APPNAME.models 的地方。
