如何修复'TypeError:join()'在Django模板中显示数据库图像时

时间:2019-10-11 06:33:00

标签: python django

我正在尝试使用image.url属性显示通过管理页面上传到数据库的一些图像。页面加载时,image.url是正确的,但是终端显示内部服务器错误,回溯结尾为 “ TypeError:join()参数必须为str或字节,而不是'list'”

我找不到在何处专门调用join方法,因为回溯似乎只在谈论内部文件。

我认为它可能与覆盖保存功能有关,但是注释掉该功能会产生相同的结果。

settings.py STATIC以及MEDIA和MEDIA_URL都已设置。

模板:

 <img class='project-details-image' src="{{ project.image.url }}

型号:

image=models.ImageField(upload_to='project-covers/', default='/Default.png', null=True)

settings.py:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/my_portfolio/my_portfolio/static/')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'my_portfolio/static'),
]
MEDIA_ROOT = [
    os.path.join(BASE_DIR, 'my_portfolio/img'),
]
MEDIA_URL = '/img/'

跟踪:

File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/user/django-portfolio/lib/python3.5/site-packages/django/views/static.py", line 36, in serve
    fullpath = Path(safe_join(document_root, path))
  File "/home/user/django-portfolio/lib/python3.5/site-packages/django/utils/_os.py", line 32, in safe_join
    final_path = abspath(join(base, *paths))
  File "/usr/lib/python3.5/posixpath.py", line 89, in join
    genericpath._check_arg_types('join', a, *p)
  File "/usr/lib/python3.5/genericpath.py", line 143, in _check_arg_types
    (funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'list'

Id希望能够使用模板标记功能来显示数据库中的相关图像。目前,我仅尝试显示默认图像,但是实际图像要低一个文件夹。

1 个答案:

答案 0 :(得分:2)

MEDIA_ROOT应该是string而不是list

更改:

MEDIA_ROOT = [
    os.path.join(BASE_DIR, 'my_portfolio/img'),
]

收件人:

MEDIA_ROOT = os.path.join(BASE_DIR, 'my_portfolio/img')