【发布时间】:2015-02-28 00:45:53
【问题描述】:
我正在使用 django-image-cropping:https://github.com/jonasundderwolf/django-image-cropping
我想要实现的是手册的简单裁剪。我使用的是 1.7.1 Django 版本。
models.py
class Image(models.Model):
file = models.ImageField('File', upload_to='dependencies/images/photos/')
gallery = models.ForeignKey('Gallery', related_name='images', blank=True, null=True)
cropping = ImageRatioField('file', '370x267', size_warning=True)
views.py
def photos(request):
photos = Image.objects.all()
return render_to_response('photos.html', {'photos':photos}, context_instance=RequestContext(request))
模板
{% load cropping %}
{% for photo in photos %}
<img src="{% cropped_thumbnail image "cropping" %}" border="0">
{% endfor %}
错误
AttributeError at /photos/
'str' object has no attribute '_meta'
Exception Location:
/venv/lib/python2.7/site-packages/image_cropping/templatetags/cropping.py in cropped_thumbnail, line 16
Python Executable:
/venv/bin/python
我研究了这个错误并发现了这个:
How to add attribute '_meta' to an object?
当我将 views.py 更改为 1 个元素时
'Test.objects.get()'
不是
'Test.objects.all()'
test = Test.objects.get(title='test')
为了测试它完美裁剪。
但如果我想在 Image 模型中裁剪所有内容并使用“for 循环”,则会出现此错误。
第 16 行的部分为您提供更多帮助:
裁剪.py
@register.simple_tag(takes_context=True)
def cropped_thumbnail(context, instance, ratiofieldname, **kwargs):
'''
Syntax:
{% cropped_thumbnail instancename "ratiofieldname"
[scale=0.1|width=100|height=200|max_size="100x200"] [upscale=True] %}
'''
ratiofield = instance._meta.get_field(ratiofieldname)
image = getattr(instance, ratiofield.image_field) # get imagefield
if ratiofield.image_fk_field: # image is ForeignKey
# get the imagefield
image = getattr(image, ratiofield.image_fk_field)
请帮忙, 谢谢
【问题讨论】:
标签: django image django-models django-templates django-views