@@ -0,0 +1,2035 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Aimport os%0Afrom django.core.management.base import BaseCommand%0Afrom django.core.files import File%0Aimport csv%0A%0Afrom users.models import User%0Afrom catalog.models import Course%0Afrom documents import logic%0A%0A%0Aclass Command(BaseCommand):%0A%0A    help = 'Import documents from a csv'%0A%0A    def add_arguments(self, parser):%0A        parser.add_argument(action='store', dest='path', default='', help='Documents path')%0A        parser.add_argument('--user', action='store', dest='username', default='tverhaegen', help='user owning the documents')%0A%0A    def handle(self, *args, **options):%0A        netid = options%5B%22username%22%5D%0A        self.stdout.write('Looking for user %22%7B%7D%22'.format(netid))%0A%0A        user = User.objects.filter(netid=netid).first()%0A        if user is None:%0A            self.stdout.write('Could not find user.')%0A            return%0A%0A        path = options%5B'path'%5D%0A        self.stdout.write('Reading csv from %22%7B%7D%22'.format(path))%0A        if not os.path.exists(path):%0A            self.stdout.write(%22CSV does not exist%22)%0A            return%0A%0A        with open(path) as fd:%0A            reader = csv.DictReader(fd)%0A%0A            for row in reader:%0A                try:%0A                    import_document(row, user)%0A                    self.stdout.write('.', ending='')%0A                    self.stdout.flush()%0A                except:%0A                    print('Fail for %25r' %25 row)%0A%0A%0Adef import_document(row, user):%0A    %22%22%22row has keys %5B'name', 'slug', 'path'%5D%22%22%22%0A    path = row%5B'path'%5D%0A    filename = os.path.split(path)%5B1%5D%0A    _, extension = os.path.splitext(filename)%0A%0A    name = row%5B'name'%5D%0A    name = logic.clean_filename(name)%0A%0A    course = Course.objects.get(slug=row%5B'slug'%5D)%0A%0A    with open(path, 'rb') as fd:%0A        document = logic.add_file_to_course(%0A            file=File(fd),%0A            name=name,%0A            extension=extension,%0A            course=course,%0A            tags=%5B%5D,%0A            user=user%0A        )%0A%0A    document.tag_from_name()%0A    document.add_to_queue()%0A

Add import from csv command