Created
September 28, 2012 21:27
-
-
Save summerisgone/3802163 to your computer and use it in GitHub Desktop.
pydialog usage example, xls import in Django command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# coding=utf-8 | |
from django.core.management.base import BaseCommand | |
from core.file_import import ListenerFileFormat, ListenerImportLogic | |
from core.models import Department, Course | |
from dialog import Dialog | |
import xlrd | |
class Command(BaseCommand): | |
help = "Import data from xls file" | |
args = 'filename' | |
def handle(self, *args, **options): | |
source_filename = args[0] | |
doc = xlrd.open_workbook(source_filename, formatting_info=True) | |
self.dialog = Dialog() | |
course = self.select_department_and_course() | |
# buisness logic is outside | |
logic = ListenerImportLogic(doc, course) | |
# Start progress bar | |
total = doc.sheet.nrows - doc.start_line | |
self.dialog.gauge_start() | |
for index, row in enumerate(doc): | |
logic.process_row(index, row) | |
# Update percentage and text | |
self.dialog.gauge_update(int(float(index)/total*100), | |
text=('Importing: %s' % row[0]).encode('utf-8'), | |
update_text=True) | |
self.dialog.gauge_stop() | |
num_errors = len(logic.errors) | |
# Show import results | |
self.dialog.infobox('Errors %d from total %d: ' % (num_errors, total)) | |
def select_department_and_course(self): | |
retcode, department_id = self.dialog.menu( | |
"select department", | |
choices=[(str(dep.id), dep.name) for dep in Department.objects.all()] | |
) | |
department = Department.objects.get(id=department_id) | |
retcode, course_id = self.dialog.menu( | |
'select course', | |
choices=[(str(course.id), course.name) for course in department.courses.all()] | |
) | |
return Course.objects.get(id=course_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment