dra*_*oon 27 django django-models
我正在尝试在模型中创建一个字段,该字段应该为注册用户存储图像.此图像应重命名并存储在单独的用户目录中media/users/10/photo.jpeg
.
我搜索了很多,但仍然无法找到如何干净,正确地做到这一点.在我看来,许多网站需要相同的功能,这应该在django文档中,但事实并非如此.
j_s*_*syk 52
您想在上面使用"upload_to"选项 ImageField
#models.py
import os
def get_image_path(instance, filename):
return os.path.join('photos', str(instance.id), filename)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
profile_image = ImageField(upload_to=get_image_path, blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)
这是直接来自我的项目的代码.上传的图像转到/MEDIA_ROOT/photos/<user_id>/filename
根据您的需要,只需将"照片"字符串更改为"用户" def get_image_path
在FileField详细信息下,文档中有一点关于它