我不知道如何使用的東西,這個簡單的第三方應用程序。只寫一個管理命令(其命名爲MYAPP /管理/命令/ csvimport.py):
from django.core.management.base import BaseCommand, CommandError
from fabric.colors import _wrap_with
from optparse import make_option
import os, csv
green_bg = _wrap_with('42')
red_bg = _wrap_with('41')
class Command(BaseCommand):
help = "Command to import a list of stuff"
option_list = BaseCommand.option_list + (
make_option(
"-f",
"--file",
dest = "filename",
help = "specify import file",
metavar = "FILE"
),
)
def handle(self, *args, **options):
# make sure file option is present
if options['filename'] == None :
raise CommandError("Option `--file=...` must be specified.")
# make sure file path resolves
if not os.path.isfile(options['filename']) :
raise CommandError("File does not exist at the specified path.")
# print file
print green_bg("Path: `%s`" % options['filename'])
# open the file
with open(options['filename']) as csv_file:
reader = csv.reader(csv_file)
for row in reader:
try :
object, created = Contacts.objects.get_or_create(
mobile = row[3],
defaults={
"first_name": row[0],
"last_name": row[1],
"company": row[2],
}
)
except:
print red_bg("Contacts `%s` could not be created." % row['mobile'])
運行,這是真正的一件容易的事:
其中csvimport是你的管理命令的文件名。
請顯示您試圖執行此操作並且無法正常工作的代碼。 – jknupp 2013-03-15 18:07:47