bgneal@237: """ bgneal@237: import_old_links.py - For importing links from SG101 1.0 as csv files. bgneal@237: """ bgneal@237: import csv bgneal@237: import datetime bgneal@237: bgneal@237: from django.core.management.base import LabelCommand, CommandError bgneal@237: from django.contrib.auth.models import User bgneal@237: bgneal@237: from weblinks.models import Link, Category bgneal@237: bgneal@237: bgneal@237: class Command(LabelCommand): bgneal@237: args = '' bgneal@237: help = 'Imports weblinks from the old database in CSV format' bgneal@237: bgneal@237: def handle_label(self, filename, **options): bgneal@237: """ bgneal@237: Process each line in the CSV file given by filename by bgneal@237: creating a new weblink object and saving it to the database. bgneal@237: bgneal@237: """ bgneal@237: self.cats = {} bgneal@237: try: bgneal@237: self.user = User.objects.get(pk=1) bgneal@237: except User.DoesNotExist: bgneal@237: raise CommandError("Need a default user with pk=1") bgneal@237: bgneal@237: try: bgneal@237: with open(filename, "rb") as f: bgneal@237: self.reader = csv.DictReader(f) bgneal@237: try: bgneal@237: for row in self.reader: bgneal@237: self.process_row(row) bgneal@237: except csv.Error, e: bgneal@237: raise CommandError("CSV error: %s %s %s" % ( bgneal@237: filename, self.reader.line_num, e)) bgneal@237: bgneal@237: except IOError: bgneal@237: raise CommandError("Could not open file: %s" % filename) bgneal@237: bgneal@237: def get_category(self, row): bgneal@237: """ bgneal@237: Return the Category object for the row. bgneal@237: bgneal@237: """ bgneal@237: cat_id = row['cid'] bgneal@237: if cat_id not in self.cats: bgneal@237: try: bgneal@237: cat = Category.objects.get(pk=cat_id) bgneal@237: except Category.DoesNotExist: bgneal@237: raise CommandError("Category does not exist: %s on line %s" % ( bgneal@237: cat_id, self.reader.line_num)) bgneal@237: else: bgneal@237: self.cats[cat_id] = cat bgneal@237: return self.cats[cat_id] bgneal@237: bgneal@237: def process_row(self, row): bgneal@237: """ bgneal@237: Process one row from the CSV file: create an object for the row bgneal@237: and save it in the database. bgneal@237: bgneal@237: """ bgneal@237: link = Link(category=self.get_category(row), bgneal@237: title=row['title'], bgneal@237: url=row['url'], bgneal@237: description=row['description'], bgneal@237: user=self.user, bgneal@237: date_added=datetime.datetime.strptime(row['date'], "%Y-%m-%d %H:%M:%S"), bgneal@237: hits=int(row['hits']), bgneal@237: is_public=True) bgneal@237: link.save()