当我在管理文件中执行以下操作时:
photo = Photo.objects.get(original_image__exact=file_name)
val = photo.admin_thumbnail.url
我收到此错误:
Caught DoesNotExist while rendering: Photo matching query does not exist.
这是我的班级:
class AdminImageWidget(forms.FileInput):
"""
A ImageField Widget for admin that shows a thumbnail.
"""
def __init__(self, attrs={}, *args, **kwargs):
super(AdminImageWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
output = []
file_name = unicode(value)
if file_name:
photo = Photo.objects.get(original_image__exact=file_name)
val = photo.admin_thumbnail.url
output.append(('<a target="_BLANK" href="%s">'
'<img src="%s" /></a> '
% (val, val)))
output.append(super(AdminImageWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
但是,如果我在shell(python manage.py shell)中执行它,它可以完美运行!
好奇啊?答案 0 :(得分:1)
你究竟想做什么?
你应该找到另一种方法来获取图像名称。 Django一直调用此方法'render',即使字段本身无效。 e.g:
还有其他方法可以获取文件名,例如,您可以覆盖save方法并获取对象实例。
答案 1 :(得分:0)
我已经解决了这个问题,但我觉得应该有一个更优雅的解决方案。
class AdminImageWidget(forms.FileInput):
"""
A ImageField Widget for admin that shows a thumbnail.
"""
def __init__(self, attrs={}, *args, **kwargs):
super(AdminImageWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
output = []
file_name = unicode(value)
if file_name:
pattern = re.compile('.png', re.IGNORECASE)
val = '/media/photos_cache/' + pattern.sub('_admin_thumbnail.png', file_name)
output.append(('<a target="_BLANK" href="%s">'
'<img src="%s" /></a> '
% (val, val)))
output.append(super(AdminImageWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
问题是你必须预先缓存缩略图。
奇怪......现在它有效......
class AdminImageWidget(forms.FileInput):
def __init__(self, attrs={}, *args, **kwargs):
super(AdminImageWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
output = []
file_name = unicode(value)
if file_name:
photo = Photo.objects.get(original_image=file_name)
val = photo.admin_thumbnail.url
output.append(('<a target="_BLANK" href="%s">'
'<img src="%s" /></a> '
% (val, val)))
output.append(super(AdminImageWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))