Add command for importing users

This commit is contained in:
Ramon Wenger 2019-07-03 13:03:33 +02:00
parent 7d46ec9ef0
commit e062a533b1
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,9 @@
Vorname,Nachname,Klassen,Rolle,Email
Ramon,Wenger,1C,Lehrer,ramon.wenger@iterativ.ch
Michael,Scott,"Scranton Branch,Stanford Branch",Lehrer,michael@dundermifflin.com
Jim,Halpert,Scranton Branch,Schüler,jim@dundermifflin.com
Pam,Beasley,Scranton Branch,Schüler,pam@dundermifflin.com
Karen,Filippelli,Stanford Branch,Schüler,karen@dundermifflin.com
Oscar,Martinez,Scranton Branch,Schüler,oscar@dundermifflin.com
Meredith,Palmer,Scranton Branch,Schüler,meredith@dundermifflin.com
Ryan,Howard,Scranton Branch,Schüler,ryan@dundermifflin.com
1 Vorname Nachname Klassen Rolle Email
2 Ramon Wenger 1C Lehrer ramon.wenger@iterativ.ch
3 Michael Scott Scranton Branch,Stanford Branch Lehrer michael@dundermifflin.com
4 Jim Halpert Scranton Branch Schüler jim@dundermifflin.com
5 Pam Beasley Scranton Branch Schüler pam@dundermifflin.com
6 Karen Filippelli Stanford Branch Schüler karen@dundermifflin.com
7 Oscar Martinez Scranton Branch Schüler oscar@dundermifflin.com
8 Meredith Palmer Scranton Branch Schüler meredith@dundermifflin.com
9 Ryan Howard Scranton Branch Schüler ryan@dundermifflin.com

View File

@ -0,0 +1,48 @@
import csv
from django.core.management import BaseCommand
import os
from django.conf import settings
from users.models import User, SchoolClass, Role, UserRole
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('csv_file')
def handle(self, *args, **options):
self.stdout.write('Importing from {}!'.format(options['csv_file']))
dir_path = settings.BASE_DIR
rel_path = options['csv_file']
abs_path = os.path.join(dir_path, rel_path)
try:
with open(abs_path) as f:
reader = csv.DictReader(f)
for row in reader:
email = row['Email'].lower()
school_class_names = [c.strip() for c in row['Klassen'].split(',')]
first_name = row['Vorname']
last_name = row['Nachname']
self.stdout.write("Creating user {} {}, {}".format(first_name, last_name, email))
user, created = User.objects.get_or_create(email=email, username=email)
user.first_name = first_name
user.last_name = last_name
user.save()
if row['Rolle'] == 'Lehrer':
self.stdout.write("Assigning teacher role")
teacher = Role.objects.get(key='teacher')
UserRole.objects.get_or_create(user=user, role=teacher)
self.stdout.write("Adding to class(es) {}".format(', '.join(school_class_names)))
for school_class_name in school_class_names:
school, _ = SchoolClass.objects.get_or_create(name=school_class_name)
user.school_classes.add(school)
self.stdout.write("")
except Exception as e:
self.stdout.write(e)