import csv import os import sys from django.conf import settings from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from user.models import Organization, User class Command(BaseCommand): help = """ Programatically create entries for model User """ def handle(self, *args, **options): csv_fpath = os.path.join(settings.RESOURCES_DIR, 'users.csv') csv.field_size_limit(sys.maxsize) created_entries = 0 existing_entries = 0 admin_group, created = Group.objects.get_or_create(name='Admin') operater_group, created = Group.objects.get_or_create(name='Operater') with open(csv_fpath) as f: reader = csv.DictReader(f) default_organization = Organization.objects.get_or_create(name='Državna geodetska uprava')[0] for row in reader: username = row['usrname'] first_name = row['ime'] last_name = row['prezime'] email = row['email'] email_confirmed = True if not email: print("User {} {} doesn't have email but it's required. Setting fake email...".format( first_name, last_name )) # set fake email email = '{}.{}@example.com'.format(first_name, last_name) email_confirmed = False obj, created = User.objects.get_or_create( username=username, first_name=first_name, last_name=last_name, email=email, email_confirmed=email_confirmed, organization=default_organization ) if row['rola'] == 'operater': obj.groups.add(operater_group) elif row['rola'] == 'admin': obj.groups.add(admin_group) else: obj.groups.clear() if created: created_entries += 1 print("Kreiran user {} {}".format(obj.first_name, obj.last_name)) else: existing_entries += 1 print("Created: {}".format(created_entries)) print("Existing: {}".format(existing_entries))