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

Django Wagtail CSV and photo "upload" - management command

我正在研究 django/wagtail 管理命令(我们称之为 "file_upload"),它大致执行以下操作:

(当前已简化)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 文件的完整路径。

谢谢!