Mih*_*fir 10 python django django-models imagefield django-imagekit
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)
Run Code Online (Sandbox Code Playgroud)
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})
Run Code Online (Sandbox Code Playgroud)
在我的模板中的某个地方:
{% generateimage 'user_profile:thumbnail' source=source_file %}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:UserProfile匹配查询不存在.
在这一行:
source_file = UserProfile.objects.get(user = request.user).photo
Run Code Online (Sandbox Code Playgroud)
问题是ImageField的默认属性不起作用.因此,对象不是在我的模型中创建的.如何正确使用此属性?如果我省略此属性,则创建对象时没有错误.我需要通过绝对路径还是相对路径?我使用django-imagekit在显示之前调整图像大小:http://django-imagekit.readthedocs.org/en/latest/
rya*_*yan 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'
Run Code Online (Sandbox Code Playgroud)
然后在模板中,显示图像:
<img src="{{ MyObject.image_url }}" alt="MyObject's Image">
Run Code Online (Sandbox Code Playgroud)
编辑:简单的例子
在views.py中
def ExampleView(request):
profile = UserProfile.objects.get(user = request.user)
return render(request, 'ExampleTemplate.html', { 'MyObject' : profile } )
Run Code Online (Sandbox Code Playgroud)
然后在模板中包含代码
<img src="{{ MyObject.image_url }}" alt="MyObject's Image">
Run Code Online (Sandbox Code Playgroud)
会显示图像.
另外,对于错误'UserProfile匹配查询不存在'.我假设您已在UserProfile模型中的某处定义了与User模型的外键关系,对吗?
| 归档时间: |
|
| 查看次数: |
14394 次 |
| 最近记录: |