渲染时捕获DoesNotExist:照片匹配查询不存在
当我在管理文件中执行以下操作时:
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),它会完美运行!
很奇怪吧?
When I do the following inside an admin file:
photo = Photo.objects.get(original_image__exact=file_name)
val = photo.admin_thumbnail.url
I get this error:
Caught DoesNotExist while rendering: Photo matching query does not exist.
Here is my class:
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))
However, if I do it in the shell (python manage.py shell), it works perfectly!
weird huh?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你到底想做什么?
您应该找到另一种方法来获取图像名称。 Django 始终调用此方法“render”,即使字段本身无效。例如:
还有其他方法可以获取文件名,例如,您可以覆盖 save 方法并获取对象实例。
What exactly are you trying to do?
You should find another way to grab the image name. This method 'render' is called all the time by Django, even when the field itself is invalid. e.g.:
There are other ways to get the filename, you could override the save method and get the object instance for example.
我已经解决了这个问题,但我觉得应该有一个更优雅的解决方案。
问题是您必须预先缓存缩略图。
编辑:
奇怪...现在可以了...
I've solved the problem but I feel like there should be a more elegant solution.
The problem is you'll have to pre-cache the thumbnails.
EDIT:
Strange... Now it works...