load-csv-users.py 1.58 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import csv
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError
from django.utils.text import slugify

from ...models import User, Emission


class Command(BaseCommand):
    args = 'filename'

    def handle(self, filename, verbosity, **kwargs):
        self.verbose = (verbosity > 1)
        for line in csv.reader(file(filename)):
16 17
            email, lastname, firstname = [unicode(x.strip(), 'utf-8') for x in line[:3]]
            emission_slugs = [x.strip().lower() for x in line[4:9] if x]
18 19 20 21 22 23
            if not email or not emission_slugs:
                continue
            if firstname and lastname:
                username = slugify(u'%s-%s' % (firstname, lastname))
            elif firstname or lastname:
                username = slugify(firstname or lastname)
24 25
                if len(username) < 8:
                    username = '%s.%s' % (username, slugify(unicode(emission_slugs[0])))
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
            else:
                continue

            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = User.objects.create_user(username, email)
                user.set_password('panik')
            user.first_name = firstname
            user.last_name = lastname
            emissions = []
            for slug in emission_slugs:
                try:
                    emissions.append(Emission.objects.get(slug=slug))
                except Emission.DoesNotExist:
                    print 'E: missing emission:', slug
            user.emissions = emissions
            user.save()