Django:MEDIA\u ROOT错误:\u getfullpathname:路径应为字符串、字节或os.PathLike,而不是元组

2024-06-17 11:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django框架的新手。我正在尝试将图像上载到customer表,出现以下错误:

_getfullpathname: path should be string, bytes or os.PathLike

我正在使用此代码上载:

MEDIA_ROOT = [BASE_DIR, 'static/images']

我把密码改成

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')

但是它说NameError: name 'os' not defined。错误的原因是什么?如何解决

设置.py

STATIC_URL = '/static/'
MEDIA = '/images/'
STATICFILES_DIRS = [BASE_DIR, 'static']
MEDIA_ROOT = [BASE_DIR, 'static/images']

型号.py

class Customer(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=11, null=True)
    email = models.EmailField(max_length=200, null=True)
    profile_pic = models.ImageField(null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

Tags: pathnametruebaseosmodels错误dir
2条回答

试试这个

在settings.py中

import os

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

STATIC_URL = '/static/'

MEDIA = '/images/'

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

MEDIA_ROOT = BASE_DIR + 'static/images'

请参阅此https://docs.djangoproject.com/en/3.1/howto/static-files/

我也有同样的问题,这可能有效 将其更改为:

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

对于未定义的错误os,您只需导入它

import os
from pathlib import Path

相关问题 更多 >