예제 #1
0
파일: views.py 프로젝트: Soyweiser/kninfra
def secr_add_group(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddGroupForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            nm = fd['name']
            g = Es.Group({
                'types': ['group', 'tag'],
                'names': [nm],
                'use_mailman_list': fd['true_group'],
                'has_unix_group': fd['true_group'],
                'humanNames': [{'name': nm,
                    'human': fd['humanName'],
                    'genitive_prefix': fd['genitive_prefix']}],
                    'description': fd['description'],
                'tags': [_id(fd['parent'])]})
            logging.info("Added group %s" % nm)
            g.save()
            Es.notify_informacie("De groep %s is opgericht." % (
                        unicode(g.humanName)))
            giedo.sync_async(request)
            request.user.push_message("Groep toegevoegd.")
            return HttpResponseRedirect(reverse('group-by-name', args=(nm,)))
    else:
        form = AddGroupForm()
    return render_to_response('leden/secr_add_group.html', {'form': form},
            context_instance=RequestContext(request))
예제 #2
0
def ik_chsmoel(request):
    if not 'smoel' in request.FILES:
        raise ValueError, "Missing `smoel' in FILES"
    if not 'id' in request.POST:
        raise ValueError, "Missing `id' in POST"
    user = Es.by_id(request.POST['id'])
    if not request.user.may_upload_smoel_for(request.user):
        raise PermissionDenied
    original = default_storage.open(path.join(settings.SMOELEN_PHOTOS_PATH,
            str(user.name)) + ".orig", 'wb+')
    for chunk in request.FILES['smoel'].chunks():
        original.write(chunk)
    original.seek(0)
    img = Image.open(original)
    if img._getexif() is not None:
        orientation = int(img._getexif().get(274, '1')) # Orientation
        if orientation == 3:
            img = img.transpose(Image.ROTATE_180)
        elif orientation == 6:
            img = img.transpose(Image.ROTATE_270)
        elif orientation == 8:
            img = img.transpose(Image.ROTATE_90)
    width, height = resize_proportional(img.size[0], img.size[1],
                                        settings.SMOELEN_WIDTH*2,
                                        settings.SMOELEN_HEIGHT*2)
    img = img.resize((width, height), Image.ANTIALIAS)
    img.save(default_storage.open(path.join(settings.SMOELEN_PHOTOS_PATH,
            str(user.name)) + ".jpg", 'w'), "JPEG")
    Es.notify_informacie('set_smoel', request.user, entity=user)
    return redirect_to_referer(request)
예제 #3
0
def relation_begin(request):
    # TODO We should use Django forms, or better: use sweet Ajax
    d = {}
    for t in ('who', 'with', 'how'):
        if t not in request.POST:
            raise ValueError, "Missing attr %s" % t
        if t == 'how' and (not request.POST[t] or
                               request.POST[t] == 'null'):
            d[t] = None
        else:
            d[t] = _id(request.POST[t])
    if not Es.user_may_begin_relation(request.user, d['who'], d['with'],
                                                                d['how']):
        raise PermissionDenied

    # Check whether such a relation already exists
    dt = now()
    ok = False
    try:
        next(Es.query_relations(who=d['who'], _with=d['with'],
            how=d['how'], _from=dt, until=DT_MAX))
    except StopIteration:
        ok = True
    if not ok:
        raise ValueError, "This relation already exists"

    # Add the relation!
    relation_id = Es.add_relation(d['who'], d['with'], d['how'], dt, DT_MAX)

    # Notify informacie
    # TODO (rik) leave out 'als lid'
    Es.notify_informacie('relation_begin', request.user, relation=relation_id)

    giedo.sync_async(request)
    return redirect_to_referer(request)
예제 #4
0
def secr_add_group(request):
    if "secretariaat" not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == "POST":
        form = AddGroupForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            nm = fd["name"]
            g = Es.Group(
                {
                    "types": ["group", "tag"],
                    "names": [nm],
                    "use_mailman_list": fd["true_group"],
                    "has_unix_group": fd["true_group"],
                    "humanNames": [{"name": nm, "human": fd["humanName"], "genitive_prefix": fd["genitive_prefix"]}],
                    "description": fd["description"],
                    "tags": [_id(fd["parent"])],
                }
            )
            logging.info("Added group %s" % nm)
            g.save()
            Es.notify_informacie("addgroup", request.user, entity=g._id)
            giedo.sync_async(request)
            messages.info(request, "Groep toegevoegd.")
            return HttpResponseRedirect(reverse("group-by-name", args=(nm,)))
    else:
        form = AddGroupForm()
    return render_to_response("leden/secr_add_group.html", {"form": form}, context_instance=RequestContext(request))
예제 #5
0
def ik_chsmoel(request):
    if not "smoel" in request.FILES:
        raise ValueError, _("Missende `smoel' in FILES")
    if not "id" in request.POST:
        raise ValueError, _("Missende `id' in POST")
    user = Es.by_id(request.POST["id"])
    if not user.name:
        raise ValueError, _("Entiteit heeft geen naam")
    if not request.user.may_upload_smoel_for(request.user):
        raise PermissionDenied
    original = default_storage.open(path.join(settings.SMOELEN_PHOTOS_PATH, str(user.name)) + ".orig", "wb+")
    for chunk in request.FILES["smoel"].chunks():
        original.write(chunk)
    original.seek(0)
    img = Image.open(original)
    if hasattr(img, "_getexif") and img._getexif() is not None:
        orientation = int(img._getexif().get(274, "1"))  # Orientation
        if orientation == 3:
            img = img.transpose(Image.ROTATE_180)
        elif orientation == 6:
            img = img.transpose(Image.ROTATE_270)
        elif orientation == 8:
            img = img.transpose(Image.ROTATE_90)
    width, height = resize_proportional(
        img.size[0], img.size[1], settings.SMOELEN_WIDTH * 2, settings.SMOELEN_HEIGHT * 2
    )
    img = img.resize((width, height), Image.ANTIALIAS)
    img.save(default_storage.open(path.join(settings.SMOELEN_PHOTOS_PATH, str(user.name)) + ".jpg", "w"), "JPEG")
    Es.notify_informacie("set_smoel", request.user, entity=user)
    return redirect_to_referer(request)
예제 #6
0
파일: views.py 프로젝트: mrngm/kninfra
def untag(request):
    group, tag = _get_group_and_tag(request)
    if not Es.user_may_untag(request.user, group, tag):
        raise PermissionDenied

    group.untag(tag)
    Es.notify_informacie('untag', request.user, entity=group, tag=tag)
    giedo.sync_async(request)
    return redirect_to_referer(request)
예제 #7
0
def relation_end(request, _id):
    rel = Es.relation_by_id(_id)
    if rel is None:
        raise Http404
    if not Es.user_may_end_relation(request.user, rel):
        raise PermissionDenied
    Es.end_relation(_id)

    # Notify informacie
    # TODO (rik) leave out 'als lid'
    Es.notify_informacie('relation_end', request.user, relation=_id)

    giedo.sync_async(request)
    return redirect_to_referer(request)
예제 #8
0
파일: views.py 프로젝트: Soyweiser/kninfra
def relation_end(request, _id):
    rel = Es.relation_by_id(_id)
    if rel is None:
        raise Http404
    if not Es.user_may_end_relation(request.user, rel):
        raise PermissionDenied
    Es.end_relation(_id)
    # Notify informacie
    if request.user == rel['who']:
        Es.notify_informacie("%s heeft zich uitgeschreven als %s %s" % (
                        request.user.full_name,
                        rel['how'].humanName if rel['how'] else 'lid',
                        rel['with'].humanName.genitive))
    else:
        # TODO (rik) leave out 'als lid'
        Es.notify_informacie("%s is geen %s meer %s" % (
                        rel['who'].humanName,
                        rel['how'].humanName if rel['how'] else 'lid',
                        rel['with'].humanName.genitive))
    giedo.sync_async(request)
    return redirect_to_referer(request)
예제 #9
0
파일: views.py 프로젝트: Jille/kninfra
def relation_begin(request):
    # TODO We should use Django forms, or better: use sweet Ajax
    d = {}
    for t in ('who', 'with', 'how'):
        if t not in request.POST:
            raise ValueError, "Missing attr %s" % t
        if t == 'how' and (not request.POST[t] or
                               request.POST[t] == 'null'):
            d[t] = None
        else:
            d[t] = _id(request.POST[t])
    if not Es.user_may_begin_relation(request.user, d['who'], d['with'],
                                                                d['how']):
        raise PermissionDenied

    # Check whether such a relation already exists
    dt = now()
    ok = False
    try:
        next(Es.query_relations(who=d['who'], _with=d['with'],
            how=d['how'], _from=dt, until=DT_MAX))
    except StopIteration:
        ok = True
    if not ok:
        raise ValueError, "This relation already exists"

    # Add the relation!
    relation_id = Es.add_relation(d['who'], d['with'], d['how'], dt, DT_MAX)

    # Notify informacie
    if request.user._id == d['who']:
        Es.notify_informacie('relation_begun', relation=relation_id)
    else:
        # TODO (rik) leave out 'als lid'
        Es.notify_informacie('relation_begin', relation=relation_id)

    giedo.sync_async(request)
    return redirect_to_referer(request)
예제 #10
0
파일: views.py 프로젝트: Blackeel/kninfra
def secr_add_user(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User({
                'types': ['user'],
                'names': [fd['username']],
                'humanNames': [{
                    'human':
                    fd['first_name'] + ' ' + fd['last_name']
                }],
                'person': {
                    'titles': [],
                    'nick': fd['first_name'],
                    'given': None,
                    'family': fd['last_name'],
                    'dateOfBirth': date_to_dt(fd['dateOfBirth'])
                },
                'email':
                fd['email'],
                'address': {
                    'street': fd['addr_street'],
                    'number': fd['addr_number'],
                    'zip': fd['addr_zip'],
                    'city': fd['addr_city']
                },
                'telephone':
                fd['telephone'],
                'studies': [{
                    'institute': _id(fd['study_inst']),
                    'study': _id(fd['study']),
                    'from': DT_MIN,
                    'until': DT_MAX,
                    'number': fd['study_number']
                }],
                'is_active':
                True,
                'password':
                None
            })
            logging.info("Added user %s" % fd['username'])
            u.save()
            # Then, add the relations.
            groups = ['leden']
            if fd['incasso']:
                groups.append('incasso')
            else:
                groups.append('geen-incasso')
            for group in groups:
                Es.add_relation(u,
                                Es.id_by_name(group, use_cache=True),
                                _from=date_to_dt(fd['dateJoined']))
            for l in fd['addToList']:
                Es.add_relation(u,
                                Es.id_by_name(l, use_cache=True),
                                _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.html", u, {
                'user': u,
                'password': pwd
            })
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.html", u, {'u': u})
            Es.notify_informacie('adduser', request.user, entity=u._id)
            return HttpResponseRedirect(
                reverse('user-by-name', args=(fd['username'], )))
    else:
        form = AddUserForm()
    return render(request, 'leden/secr_add_user.html', {'form': form})
예제 #11
0
def _set_metadata(data, request):
    user = request.user if request.user.is_authenticated() else None
    if not fEs.is_admin(user):
        raise PermissionDenied

    if 'title' not in data:
        return {'error': 'missing title attribute'}
    if not isinstance(data['title'], six.string_types):
        return {'error': 'title should be string'}
    title = data['title'].strip()
    if not title:
        title = None

    if 'visibility' not in data:
        return {'error': 'missing visibility attribute'}
    if data['visibility'] not in ['world', 'leden', 'hidden']:
        return {'error': 'visibility not valid'}
    visibility = data['visibility']

    entity = entity_from_request(data)
    if isinstance(entity, six.string_types):
        return {'error': entity}

    result = {'Ok': True}

    if entity._type == 'foto':
        if 'rotation' not in data:
            return {'error': 'missing rotation attribute'}
        if not isinstance(data['rotation'], int):
            return {'error': 'rotation should be a number'}
        rotation = data['rotation']
        if rotation not in [0, 90, 180, 270]:
            return {'error': 'rotation is not valid'}
        entity.set_rotation(rotation, save=False)

        result['largeSize'] = entity.get_cache_size('large')
        result['large2xSize'] = entity.get_cache_size('large2x')

    if entity._type in ['foto', 'video']:
        if 'description' not in data:
            return {'error': 'missing description attribute'}
        if not isinstance(data['description'], six.string_types):
            return {'error': 'description should be a string'}
        description = data['description'].strip()
        if not description:
            description = None
        entity.set_description(description, save=False)

        if 'tags' not in data:
            return {'error': 'missing tags attribute'}
        if not isinstance(data['tags'], list):
            return {'error': 'tags should be a list'}
        if not all(isinstance(n, six.string_types) for n in data['tags']):
            return {'error': 'tags may only contain strings'}
        tags = data['tags']
        entity.set_tags(tags, save=True)

        result['thumbnailSize'] = entity.get_cache_size('thumb')
        result['thumbnail2xSize'] = entity.get_cache_size('thumb2x')

    entity.set_title(title, save=False)

    # save changes in one batch
    entity.save()
    # except for visibility which is much harder to save in the same batch
    if entity.is_root:
        return result

    was_visible = 'leden' in fEs.actual_visibility(entity.effective_visibility)
    entity.update_visibility([visibility])
    is_visible = 'leden' in fEs.actual_visibility(entity.effective_visibility)

    # Send a mail when a new album comes online.
    if not entity.notified_informacie:
        if not was_visible and is_visible and isinstance(
                entity, fEs.FotoAlbum):
            event = entity
            while event.depth > 1:
                event = event.get_parent()
            if entity.depth > 1:
                Es.notify_informacie('add_foto_album',
                                     request.user,
                                     fotoEvent=event,
                                     fotoAlbum=entity)
            else:
                Es.notify_informacie('add_foto_event',
                                     request.user,
                                     fotoEvent=event)
            entity.set_informacie_notified()
        elif was_visible and not is_visible:
            # Do not send a mail when an old album (pre-notifications)
            # is set to invisible and back to visible. Act like a
            # notification has already been sent.
            entity.set_informacie_notified()

    return result
예제 #12
0
파일: views.py 프로젝트: Soyweiser/kninfra
def secr_add_user(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            nm = find_name_for_user(fd['first_name'],
                        fd['last_name'])
            u = Es.User({
                'types': ['user'],
                'names': [nm],
                'humanNames': [{'human': fd['first_name']+' '+
                             fd['last_name']}],
                'person': {
                    'titles': [],
                    'nick': fd['first_name'],
                    'given': None,
                    'family': fd['last_name'],
                    'gender': fd['sex'],
                    'dateOfBirth': date_to_dt(
                        fd['dateOfBirth'])
                },
                'emailAddresses': [
                    {'email': fd['email'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'addresses': [
                    {'street': fd['addr_street'],
                     'number': fd['addr_number'],
                     'zip': fd['addr_zip'],
                     'city': fd['addr_city'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'telephones': [
                    {'number': fd['telephone'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'studies': [
                    {'institute': _id(fd['study_inst']),
                     'study': _id(fd['study']),
                     'from': DT_MIN,
                     'until': DT_MAX,
                     'number': fd['study_number']}],
                'is_active': True,
                'password': None
                })
            logging.info("Added user %s" % nm)
            u.save()
            Es.add_relation(u, Es.id_by_name('leden',
                            use_cache=True),
                    _from=date_to_dt(fd['dateJoined']))
            for l in fd['addToList']:
                Es.add_relation(u, Es.id_by_name(l, use_cache=True),
                    _from=now())
            Es.notify_informacie("%s is ingeschreven als lid." % (
                        u.humanName))
            giedo.sync_async(request)
            request.user.push_message("Gebruiker toegevoegd. "+
                "Let op: hij heeft geen wachtwoord "+
                "en hij moet nog gemaild worden.")
            return HttpResponseRedirect(reverse('user-by-name',
                    args=(nm,)))
    else:
        form = AddUserForm()
    return render_to_response('leden/secr_add_user.html',
            {'form': form},
            context_instance=RequestContext(request))
예제 #13
0
파일: views.py 프로젝트: mrngm/kninfra
def secr_add_user(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User({
                'types': ['user'],
                'names': [fd['username']],
                'humanNames': [{'human': fd['first_name'] + ' ' +
                                fd['last_name']}],
                'person': {
                    'titles': [],
                    'nick': fd['first_name'],
                    'given': None,
                    'family': fd['last_name'],
                    'dateOfBirth': date_to_dt(
                        fd['dateOfBirth'])
                },
                'emailAddresses': [
                    {'email': fd['email'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'addresses': [
                    {'street': fd['addr_street'],
                     'number': fd['addr_number'],
                     'zip': fd['addr_zip'],
                     'city': fd['addr_city'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'telephones': [
                    {'number': fd['telephone'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'studies': [
                    {'institute': _id(fd['study_inst']),
                     'study': _id(fd['study']),
                     'from': DT_MIN,
                     'until': DT_MAX,
                     'number': fd['study_number']}],
                'is_active': True,
                'password': None
            })
            logging.info("Added user %s" % fd['username'])
            u.save()
            # Then, add the relations.
            groups = ['leden']
            if fd['incasso']:
                groups.append('incasso')
            else:
                groups.append('geen-incasso')
            for group in groups:
                Es.add_relation(u, Es.id_by_name(group,
                                                 use_cache=True),
                                _from=date_to_dt(fd['dateJoined']))
            for l in fd['addToList']:
                Es.add_relation(u, Es.id_by_name(l, use_cache=True),
                                _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.txt", u, {
                'user': u,
                'password': pwd})
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.txt", u, {
                'u': u})
            Es.notify_informacie('adduser', request.user, entity=u._id)
            return HttpResponseRedirect(reverse('user-by-name',
                                                args=(fd['username'],)))
    else:
        form = AddUserForm()
    return render_to_response('leden/secr_add_user.html',
                              {'form': form},
                              context_instance=RequestContext(request))
예제 #14
0
def _set_metadata(data, request):
    user = request.user if request.user.is_authenticated() else None
    if not fEs.is_admin(user):
        raise PermissionDenied

    if 'title' not in data:
        return {'error': 'missing title attribute'}
    if not isinstance(data['title'], basestring):
        return {'error': 'title should be string'}
    title = data['title'].strip()
    if not title:
        title = None

    if 'visibility' not in data:
        return {'error': 'missing visibility attribute'}
    if data['visibility'] not in ['world', 'leden', 'hidden']:
        return {'error': 'visibility not valid'}
    visibility = data['visibility']

    entity = entity_from_request(data)
    if isinstance(entity, basestring):
        return {'error': entity}

    result = {'Ok': True}

    if entity._type == 'foto':
        if 'rotation' not in data:
            return {'error': 'missing rotation attribute'}
        if not isinstance(data['rotation'], int):
            return {'error': 'rotation should be a number'}
        rotation = data['rotation']
        if rotation not in [0, 90, 180, 270]:
            return {'error': 'rotation is not valid'}
        entity.set_rotation(rotation, save=False)

        result['largeSize'] = entity.get_cache_size('large')

    if entity._type in ['foto', 'video']:
        if 'description' not in data:
            return {'error': 'missing description attribute'}
        if not isinstance(data['description'], basestring):
            return {'error': 'description should be a string'}
        description = data['description'].strip()
        if not description:
            description = None
        entity.set_description(description, save=False)

        if 'tags' not in data:
            return {'error': 'missing tags attribute'}
        if not isinstance(data['tags'], list):
            return {'error': 'tags should be a list'}
        if not all(isinstance(n, basestring) for n in data['tags']):
            return {'error': 'tags may only contain strings'}
        tags = data['tags']
        entity.set_tags(tags, save=True)

        result['thumbnailSize'] = entity.get_cache_size('thumb')

    entity.set_title(title, save=False)

    # save changes in one batch
    entity.save()
    # except for visibility which is much harder to save in the same batch
    if entity.is_root:
        return result

    was_visible = 'leden' in fEs.actual_visibility(entity.effective_visibility)
    entity.update_visibility([visibility])
    is_visible = 'leden' in fEs.actual_visibility(entity.effective_visibility)

    # Send a mail when a new album comes online.
    if not entity.notified_informacie:
        if not was_visible and is_visible and isinstance(entity, fEs.FotoAlbum):
            event = entity
            while event.depth > 1:
                event = event.get_parent()
            if entity.depth > 1:
                Es.notify_informacie('add_foto_album', request.user, fotoEvent=event, fotoAlbum=entity)
            else:
                Es.notify_informacie('add_foto_event', request.user, fotoEvent=event)
            entity.set_informacie_notified()
        elif was_visible and not is_visible:
            # Do not send a mail when an old album (pre-notifications) is set to
            # invisible and back to visible. Act like a notification has already
            # been sent.
            entity.set_informacie_notified()

    return result
예제 #15
0
def secr_add_user(request):
    if "secretariaat" not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == "POST":
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User(
                {
                    "types": ["user"],
                    "names": [fd["username"]],
                    "humanNames": [{"human": fd["first_name"] + " " + fd["last_name"]}],
                    "person": {
                        "titles": [],
                        "nick": fd["first_name"],
                        "given": None,
                        "family": fd["last_name"],
                        "gender": fd["gender"],
                        "dateOfBirth": date_to_dt(fd["dateOfBirth"]),
                    },
                    "emailAddresses": [{"email": fd["email"], "from": DT_MIN, "until": DT_MAX}],
                    "addresses": [
                        {
                            "street": fd["addr_street"],
                            "number": fd["addr_number"],
                            "zip": fd["addr_zip"],
                            "city": fd["addr_city"],
                            "from": DT_MIN,
                            "until": DT_MAX,
                        }
                    ],
                    "telephones": [{"number": fd["telephone"], "from": DT_MIN, "until": DT_MAX}],
                    "studies": [
                        {
                            "institute": _id(fd["study_inst"]),
                            "study": _id(fd["study"]),
                            "from": DT_MIN,
                            "until": DT_MAX,
                            "number": fd["study_number"],
                        }
                    ],
                    "is_active": True,
                    "password": None,
                }
            )
            logging.info("Added user %s" % fd["username"])
            u.save()
            # Then, add the relations.
            groups = ["leden"]
            groups.append({"m": "mannen", "v": "vrouwen"}.get(fd["gender"]))
            if fd["incasso"]:
                groups.append("incasso")
            else:
                groups.append("geen-incasso")
            for group in groups:
                Es.add_relation(u, Es.id_by_name(group, use_cache=True), _from=date_to_dt(fd["dateJoined"]))
            for l in fd["addToList"]:
                Es.add_relation(u, Es.id_by_name(l, use_cache=True), _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.txt", u, {"user": u, "password": pwd})
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.txt", u, {"u": u})
            Es.notify_informacie("adduser", request.user, entity=u._id)
            return HttpResponseRedirect(reverse("user-by-name", args=(fd["username"],)))
    else:
        form = AddUserForm()
    return render_to_response("leden/secr_add_user.html", {"form": form}, context_instance=RequestContext(request))