【问题标题】:MEDIA_ROOT error : _getfullpathname: path should be string, bytes or os.PathLike, not tupleMEDIA_ROOT 错误:_getfullpathname:路径应该是字符串、字节或 os.PathLike,而不是元组
【发布时间】:2019-01-18 15:42:07
【问题描述】:

我是 Django 框架的新手。 当我在设置中使用MEDIA_ROOT = os.path.join(BASE_DIR, 'media'), 命令时,在http://127.0.0.1:8000/admin/products/product/add/(管理员模式)中尝试上传图片时遇到以下错误:

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

当我尝试时,我发现删除 MEDIA_ROOT=... 也会消除错误,并且图像将正确放置在媒体文件夹的路径上。 我认为使用 MEDIA_ROOT 的原因是为了了解媒体文件到 Django 的路径,但是:

1)为什么我用的时候会报错

2) 为什么我删除这个命令,一切顺利? 谢谢

setting.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media'),
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static'),

错误截图是 getfullpathname: path should be string, bytes or os.PathLike, not tuple

项目/urls.py

from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
#url will be here
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我的 models.py 中只有一个图像域:

from django.db import models

# Create your models here.


class Product(models.Model) :
    name = models.CharField(max_length=100 , verbose_name="نام جنس",null=True,blank=True)
    category = models.ForeignKey('Category',on_delete=models.CASCADE , verbose_name="دسته بندی" , null=True ,blank=True)
    price = models.IntegerField(verbose_name="قیمت" ,null=True,blank=True)
    property=models.ForeignKey('Property',on_delete=models.CASCADE , verbose_name="ویژگی" , null=True,blank=True)
    description = models.TextField(verbose_name="توضیحات",null=True,blank=True)
    image=models.ImageField(upload_to="media/productimage/")


class Property(models.Model):
    color = models.CharField(max_length=40 , verbose_name="رنگ",null=True,blank=True)
    made = models.CharField(max_length=40 , verbose_name="ساخت کشور" , null=True,blank=True) #made in country


class Category(models.Model):
    name = models.CharField(max_length=100 , verbose_name="دسته بندی" , null=True,blank=True)

【问题讨论】:

    标签: django


    【解决方案1】:

    settings.py 中的MEDIA_ROOTSTATIC_ROOT 变量的值都有一个尾随逗号。尾随逗号将这些变量的值从字符串转换为元组。

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media'),  # This is a tuple
    STATIC_ROOT = os.path.join(BASE_DIR, 'static'),  # So is this
    

    删除结尾的逗号应该可以解决问题。

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  # This is now a string
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')  # So is this
    

    【讨论】:

      【解决方案2】:
      """ Managing media
      """
      MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
      MEDIA_URL = "/media/"
      

      另外,如果您在加入操作系统路径时遇到错误,请在同一 settings.py 文件中导入 os

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-14
        • 1970-01-01
        • 2020-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-04
        • 2020-03-25
        相关资源
        最近更新 更多