Django ImageField 默认值

11 投票
1 回答
17070 浏览
提问于 2025-04-17 23:27

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 %}

我遇到了一个错误: 用户档案匹配的查询不存在。

出错的地方是:

source_file = UserProfile.objects.get(user = request.user).photo

问题在于,ImageField的默认属性没有正常工作。因此,我的模型里面没有创建对象。这个属性应该怎么正确使用呢?如果我不使用这个属性,对象就能正常创建,没有错误。我需要传递绝对路径还是相对路径呢? 我正在使用django-imagekit来在显示图片之前调整图片大小: http://django-imagekit.readthedocs.org/en/latest/

1 个回答

15

如果你没有定义默认属性,图片上传能成功吗?在我自己的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模型中某个地方定义了与User模型的外键关系,对吧?

撰写回答