【问题标题】:Django Wagtail CSV and photo "upload" - management commandDjango Wagtail CSV 和照片“上传” - 管理命令
【发布时间】:2018-04-27 13:32:10
【问题描述】:

我正在开发一个 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'

非常感谢

【问题讨论】:

  • File(open) 看起来不对。应该是File(f)

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


【解决方案1】:

感谢 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 文件的完整路径。

谢谢!

【讨论】:

  • 答案是:django_file = File(f, name=row[0])
猜你喜欢
  • 2015-03-11
  • 2011-10-03
  • 2019-10-16
  • 2017-11-06
  • 2014-07-18
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多