如何将图像文件加载到Django File对象中,然后保存到我的模型

时间:2018-04-26 09:19:07

标签: python django image django-staticfiles

所以我花了超过24小时试图弄清楚如何将图像存储到我的模型中。

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    avatar = models.FileField(null=True, upload_to='www-avatar/')

我的Profile Model有一个属性avatar,代表个人资料图片。

我想要做的是在User完成注册过程后,Profile模型将从我的静态文件夹中分配一个默认图像。

这是我的Settings.py for static

STATIC_ROOT = '/srv/foo/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "bar/resource/"), )

我要加载并存储到模型中的图像位于bar/resource/profile_light.png

到目前为止,我提出的解决方案是

file = File()
url = static("bar/resource/profile_light.png")
file = urllib.request.urlopen(url).read()
r = File(file)
authbox.profile.avatar = File(file)
authbox.profile.save()

无济于事。我是Django的新手,我非常感谢任何形式的帮助。

编辑:我的问题可能很糟糕,但我需要在创建的配置文件上添加默认图像。我在上面提到的保存头像的片段位于注册过程之后。所以基本上我想在每次有人注册时访问图像,并将图像存储为默认头像。

2 个答案:

答案 0 :(得分:0)

首先将models.py中的字段类型更改为:

avatar = models.ImageField(upload_to='www-avatar/', null=True)

其次,在您的设置文件中,您应该定义媒体目录

MEDIA_DIR = os.path.join(BASE_DIR, "www-avatar")

然后,您应该将urls.py文件修改为

urlpatterns = [
    url(r'^admin/', admin.site.urls),
.......

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

最后但并非最不重要的是不要忘记安装枕头库pip install Pillowhttps://pypi.org/project/Pillow/2.2.1/

答案 1 :(得分:0)

在你的模特中:

avatar = models.ImageField(upload_to='www-avatar', default='path/to/my/default/image.jpg')