Django图像裁剪 - ' str'对象没有属性' _meta'

时间:2015-01-01 08:41:36

标签: django image django-models django-templates django-views

我正在使用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

Template tage error

我研究了这个错误,发现了这个:

How to add attribute '_meta' to an object?

当我用

更改了1个元素的views.py时
'Test.objects.get()' 

不是

'Test.objects.all()'

 test = Test.objects.get(title='test')

测试它完美裁剪。

但是,如果我想在Image模型中裁剪所有并使用'for循环',我会遇到此错误。

为了帮助你更多,这里是第16行的部分:

cropping.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)

请帮忙, 谢谢

1 个答案:

答案 0 :(得分:2)

您将image传递给代码,但包含图片模型的变量为photo。更改使用的变量名称。