Django在模型中存储用户图像 [英] Django store user image in model

查看:99
本文介绍了Django在模型中存储用户图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在模型中创建一个字段,它应该为注册用户存储图像。
此图像应该重命名并存储在单独的用户目录中,如 media / users / 10 / photo.jpeg

I'm trying to create a field in a model, that should store an image for a registered user. This image should be renamed and stored in a separate user directory like media/users/10/photo.jpeg.

我搜索了很多,但仍然找不到如何干净地正确地做。在我看来,许多网站需要相同的功能,这应该在django文档中,但不是。

I've searched a lot, but still can't find how to do it cleanly and correctly. It seems to me that many sites require the same functionality and this should be in django docs, but it is not.

推荐答案

你想使用 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)

这是我的一个项目的代码。上传的图像将转到 / MEDIA_ROOT / photos /< user_id> / filename

This is code directly from a project of mine. The uploaded image goes to /MEDIA_ROOT/photos/<user_id>/filename

将照片字符串更改为code中的用户def get_image_path

For what you want, just change the 'photos' string to 'users' in def get_image_path

这里是关于它的小部分文档,在 FileField 详细信息

Here is the small bit about it in the docs, under FileField details

这篇关于Django在模型中存储用户图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆