models.py:
class UserProfile(models.Model):
photo = models.ImageField(upload_to = get_upload_file_name,
storage = OverwriteStorage(),
default = os.path.join(settings.STATIC_ROOT,'images','generic_profile_photo.jpg'),
height_field = 'photo_height',
width_field = 'photo_width')
photo_height = models.PositiveIntegerField(blank = True, default = 0)
photo_width = models.PositiveIntegerField(blank = True, default = 0)views.py:
def EditProfile(request):
register_generator()
source_file = UserProfile.objects.get(user = request.user).photo
args = {}
args.update(csrf(request))
args.update({'source_file' : source_file})在我的模板的某个地方
{% generateimage 'user_profile:thumbnail' source=source_file %}我收到一个错误: UserProfile匹配查询不存在。
在这一行:
source_file = UserProfile.objects.get(user = request.user).photo问题是ImageField的默认分布不起作用。因此,对象不是在我的模型中创建的。如何正确地使用这种分配?如果省略此属性,则创建对象时不存在任何错误。我需要通过绝对路径还是相对路径?我正在使用django-imagekit来调整图像的大小,然后再删除它:http://django-imagekit.readthedocs.org/en/latest/。
发布于 2014-03-22 19:27:08
如果您没有定义默认属性,那么图像上传工作成功吗?当我在自己的django项目中实现一个ImageField时,我没有使用默认属性。相反,我编写了这个方法来获取到默认图像的路径:
def image_url(self):
"""
Returns the URL of the image associated with this Object.
If an image hasn't been uploaded yet, it returns a stock image
:returns: str -- the image url
"""
if self.image and hasattr(self.image, 'url'):
return self.image.url
else:
return '/static/images/sample.jpg'然后在模板中,用以下方式显示图像:
<img src="{{ MyObject.image_url }}" alt="MyObject's Image">编辑:简单示例
在views.py中
def ExampleView(request):
profile = UserProfile.objects.get(user = request.user)
return render(request, 'ExampleTemplate.html', { 'MyObject' : profile } )然后在模板中,包括代码
<img src="{{ MyObject.image_url }}" alt="MyObject's Image">会显示图像。
此外,对于错误“不存在UserProfile匹配查询”。我想您已经在UserProfile模型中的某个地方定义了与用户模型的外键关系,对吗?
https://stackoverflow.com/questions/22581877
复制相似问题