__author__ = 'tyrel' from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from tracking.models import Track import xmltodict import os class Command(BaseCommand): help = 'Import a gpx file' def add_arguments(self, parser): parser.add_argument('username', help="Username to import to.") parser.add_argument('filepath', help="File or directory to import a gpx file.") def handle(self, *args, **options): self.username = options['username'] filepath = options['filepath'] try: self.user = User.objects.get(username=self.username) except User.DoesNotExist: raise CommandError("User {0} does not exist".format(self.username)) if os.path.isfile(filepath): self.import_file(filepath) else: raise CommandError("{0} is neither an existing file, nor a path.".format(filepath)) def import_file(self, filename): with open(filename) as fd: gpx = dict(xmltodict.parse(fd.read()))['gpx'] user = self.user Track.objects.get_or_create_from_gpx(gpx, user)