python - Django Wagtail CSV 和照片 "upload"- 管理命令

标签 python python-3.x csv wagtail django-2.0

我正在开发一个 django/wagtail 管理命令(我们称之为“file_upload”),它大致执行以下操作:

  • 采用“csv”参数,它是 CSV 文件的完整路径。
  • 使用 csv 解析并打开结果
  • 对于每一行,创建并保存一个自定义 Wagtail Image 模型对象(继承自 AbstractImage,还有一些额外的 CharField,我认为它们不会阻止我执行以下操作我想做)

(当前简化的)CSV 如下所示:

1.jpg,Title 1
2.jpg,Title 2

一点也不复杂,甚至很简单……但是 Wagtail 方面的事情似乎没有大量记录。以下不起作用:

import csv
import argparse
import os, sys

from django.core.files import File
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.conf import settings

from custom_photo.models import CustomPhoto


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--csv', nargs='?', type=argparse.FileType('r'))

    def handle(self, *args, **options):
        path = os.path.dirname(os.path.realpath(options['csv'].name))
        with options['csv'] as csvfile:
            readCSV = csv.reader(csvfile, delimiter=',')
            for row in readCSV:
                # the file full path assumes everything is flat in the same folder
                with open('%s/%s' %(path, row[0]), 'rb') as f:
                    django_file = File(open)
                    print(django_file)
                    photo = CustomPhoto()
                    photo.title=row[1]
                    # three arguments:
                    # 1) relative path inside MEDIA_ROOT
                    # 2) the django File object
                    # 3) Whether or not we want to save the photo object after the image is saved
                    photo.file.save(row[0], django_file, True)
                    print(photo.__dict__)

运行如下:

python manage.py cca_photo_import --csv=C:\path\to\file\list.csv

并抛出以下错误:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "<snip>env\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "<snip>env\lib\site-packages\django\core\management\__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "<snip>env\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "<snip>env\lib\site-packages\django\core\management\base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "<snip>cca\cca_photo\management\commands\cca_photo_import.py", line 43, in handle
    photo.file.save(row[0], django_file, True)
  File "<snip>env\lib\site-packages\django\db\models\fields\files.py", line 87, in save
    self.name = self.storage.save(name, content, max_length=self.field.max_length)
  File "<snip>env\lib\site-packages\django\core\files\storage.py", line 49, in save
    return self._save(name, content)
  File "<snip>env\lib\site-packages\django\core\files\storage.py", line 268, in _save
    for chunk in content.chunks():
  File "<snip>env\lib\site-packages\django\core\files\base.py", line 71, in chunks
    data = self.read(chunk_size)
  File "<snip>env\lib\site-packages\django\core\files\utils.py", line 16, in <lambda>
    read = property(lambda self: self.file.read)
AttributeError: 'builtin_function_or_method' object has no attribute 'read'

非常感谢

最佳答案

感谢 gasman,现在可以正常工作了。呃。

import csv
import argparse
import os, sys

from django.core.files import File
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.conf import settings

from custom_photo.models import CustomPhoto, CustomPhotoPlate, CustomPhotoType


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--csv', nargs='?', type=argparse.FileType('r'))

    def handle(self, *args, **options):
        path = os.path.dirname(os.path.realpath(options['csv'].name))
        with options['csv'] as csvfile:
            readCSV = csv.reader(csvfile, delimiter=',')
            for row in readCSV:
                photo_path = '%s/%s' %(path, row[0])
                with open(photo_path, 'rb') as f:
                    django_file = File(f)
                    photo = CustomPhoto()
                    photo.title=row[1]
                    photo.file = django_file
                    photo.save()
                    print(photo.__dict__)

photo 对象已保存,等等。一切都很好。

但是,该对象的 file 字段现在填充有:

original_images/CFolderSubFolderSubSubFolderSubSubSubFolder1.jpg

其中 CFolderSubFolderSubSubFolderSubSubSubFolder 显然是 C:\Folder\SubFolder\SubSubFolder\SubSubSubFolder

的清理版本

有什么方法可以摆脱这条(无用的)路径吗?这显然是 JPG 文件的完整路径。

谢谢!

关于python - Django Wagtail CSV 和照片 "upload"- 管理命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063542/

相关文章:

python - 在Python中导入创建环境变量?

python - 如何使用 django 发送带有动态内容的 html 电子邮件?

django - 排序时 : '<' not supported between instances of 'NoneType' and 'str'

python - 在单个字典理解中插入列表和切片

excel - 在 Excel 查询编辑器中合并具有不同列数的 CSV 文件文件夹

python - python 2 中 __getattr__(self, __getitem__) 的内部

python - Matplotlib 动画迭代 pandas 数据帧列表

Python包: Can I look for config/yml file from project directory which called it?

java - 在 Java 中导出为 CSV/Excel

python - 读取每个文件后如何写入新行?