gpt4 book ai didi

python - 将图像保存到用户模型中

转载 作者:行者123 更新时间:2023-12-01 03:52:16 25 4
gpt4 key购买 nike

我正在尝试在我的用户模型中创建一个“头像”字段(尝试使用所有库,但不太喜欢它们)

class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
...
pic = models.ImageField(upload_to="photos", default='pic')

在设置.py

MEDIA_ROOT = '/media/'

另外我什至没有使用表单,而是直接从管理员上传,问题是图像没有保存到文件夹 templates/media/photos 中。

此外,我没有任何关联的 View ,只是尝试将图像保存到文件夹中,以便我可以更好地了解文件系统的工作原理。

编辑:拼写错误

最佳答案

您需要配置设置才能在使用本地环境时正确提供静态媒体。

将此添加到您的 settings.py

DEBUG = True

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

将此添加到您的 ROOT urls.py

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static


if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

关于python - 将图像保存到用户模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38041605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com