Пример #1
0
def editstatus(request, chapterurl):
    c = get_object_or_404(Chapter, myrobogals_url__exact=chapterurl)
    memberstatustypes = MemberStatusType.objects.all()
    if request.user.is_superuser or is_executive_or_higher(request.user, c):
        users = []
        if request.method == 'POST':
            ulform = EditStatusForm(request.POST, user=request.user)
            if ulform.is_valid():
                data = ulform.cleaned_data
                status = data['status']
                users = data['users']  # l:queryset
                users_already = ""
                users_changed = ""

                for user in users:
                    u = User.objects.get(username__exact=user.username)
                    old_status = u.memberstatus_set.get(status_date_end__isnull=True)
                    if old_status.statusType == MemberStatusType.objects.get(pk=int(status)):
                        if (users_already):
                            users_already = users_already + ", " + u.username
                        else:
                            users_already = u.username
                    else:
                        if user.membertype().description != 'Inactive':
                            old_status.status_date_end = date.today()
                            old_status.save()
                        new_status = MemberStatus()
                        new_status.user = u
                        new_status.statusType = MemberStatusType.objects.get(pk=int(status))
                        new_status.status_date_start = date.today()
                        new_status.save()
                        if (users_changed):
                            users_changed = users_changed + ", " + u.username
                        else:
                            users_changed = u.username

                if (users_already):
                    messages.success(request, message=unicode(
                        _("%(usernames)s are already marked as %(type)s") % {'usernames': users_already,
                                                                             'type': MemberStatusType.objects.get(
                                                                                 pk=int(status)).description}))

                if (users_changed):
                    messages.success(request, message=unicode(
                        _("%(usernames)s has/have been marked as %(type)s") % {'usernames': users_changed,
                                                                               'type': new_status.statusType.description}))

                return HttpResponseRedirect('/chapters/' + chapterurl + '/edit/users/')
            else:
                return render_to_response('edit_user_status.html',
                                          {'ulform': ulform, 'chapter': c, 'memberstatustypes': memberstatustypes},
                                          context_instance=RequestContext(request))
        else:
            ulform = EditStatusForm(None, user=request.user)
            return render_to_response('edit_user_status.html',
                                      {'ulform': ulform, 'chapter': c, 'memberstatustypes': memberstatustypes},
                                      context_instance=RequestContext(request))
Пример #2
0
def editstatus(request, chapterurl):
    c = get_object_or_404(Chapter, myrobogals_url__exact=chapterurl)
    memberstatustypes = MemberStatusType.objects.all()
    if request.user.is_superuser or is_executive_or_higher(request.user, c):
        users = []
        if request.method == 'POST':
            ulform = EditStatusForm(request.POST, user=request.user)
            if ulform.is_valid():
                data = ulform.cleaned_data
                status = data['status']
                users = data['users']  # l:queryset
                users_already = ""
                users_changed = ""

                for user in users:
                    u = User.objects.get(username__exact=user.username)
                    old_status = u.memberstatus_set.get(status_date_end__isnull=True)
                    if old_status.statusType == MemberStatusType.objects.get(pk=int(status)):
                        if (users_already):
                            users_already = users_already + ", " + u.username
                        else:
                            users_already = u.username
                    else:
                        if user.membertype().description != 'Inactive':
                            old_status.status_date_end = date.today()
                            old_status.save()
                        new_status = MemberStatus()
                        new_status.user = u
                        new_status.statusType = MemberStatusType.objects.get(pk=int(status))
                        new_status.status_date_start = date.today()
                        new_status.save()
                        if (users_changed):
                            users_changed = users_changed + ", " + u.username
                        else:
                            users_changed = u.username

                if (users_already):
                    messages.success(request, message=unicode(
                        _("%(usernames)s are already marked as %(type)s") % {'usernames': users_already,
                                                                             'type': MemberStatusType.objects.get(
                                                                                 pk=int(status)).description}))

                if (users_changed):
                    messages.success(request, message=unicode(
                        _("%(usernames)s has/have been marked as %(type)s") % {'usernames': users_changed,
                                                                               'type': new_status.statusType.description}))

                return HttpResponseRedirect('/chapters/' + chapterurl + '/edit/users/')
            else:
                return render_to_response('edit_user_status.html',
                                          {'ulform': ulform, 'chapter': c, 'memberstatustypes': memberstatustypes},
                                          context_instance=RequestContext(request))
        else:
            ulform = EditStatusForm(None, user=request.user)
            return render_to_response('edit_user_status.html',
                                      {'ulform': ulform, 'chapter': c, 'memberstatustypes': memberstatustypes},
                                      context_instance=RequestContext(request))
Пример #3
0
def newuser(request, chapter, invite=None):
    pwerr = ''
    usererr = ''
    carderr = ''
    inverr = ''
    err = []

    signup_form = FormPartOne(request.POST or None,
                              chapter=chapter,
                              user_id='')

    coc_form_text = openconductfile()

    if coc_form_text is not None:
        coc_form = CodeOfConductForm(request.POST or None)

    if request.method == 'POST':
        # Checks coc_form is assigned before calling is valid
        if coc_form_text is not None:
            valid_forms = signup_form.is_valid() and coc_form.is_valid()
        else:
            valid_forms = signup_form.is_valid()

        if valid_forms:
            data = signup_form.cleaned_data

            new_username = data['username']

            # Checking validity of length
            username_len = len(new_username)
            if username_len < 3:
                usererr = _('Your username must be 3 or more characters')
            elif username_len > 30:
                usererr = _('Your username must be less than 30 characters')

            # Regex check for words, letters, numbers and underscores only in username
            matches = re.compile(r'^\w+$').findall(new_username)
            if matches == []:
                usererr = _(
                    'Your username must contain only letters, numbers and underscores'
                )

            # See if it already exists in database
            else:
                try:
                    User.objects.get(username=new_username)
                except User.DoesNotExist:
                    if request.POST['password1'] == request.POST['password2']:
                        if len(request.POST['password1']) < 5:
                            pwerr = _(
                                'Your password must be at least 5 characters long'
                            )
                        else:
                            # XXX: Don't worry about this line, otherwise, hard code an email in by overriding the
                            # signup form class, remember to remove the double indent if you remove this check!
                            # if (invite is not None) and not invite.email == data['email']:
                            #     inverr = _('Please use the email address that your invite was sent to.')
                            # else:
                            # Creates, saves and returns a User object
                            u = User.objects.create_user(
                                new_username, '', request.POST['password1'])
                            u.chapter = chapter
                            mt = MemberStatus(user_id=u.pk, statusType_id=1)
                            mt.save()
                            u.is_active = True
                            if invite is not None:
                                u.is_staff = invite.staff_access
                                u.is_superuser = invite.superuser_access
                            else:
                                u.is_staff = False
                                u.is_superuser = False
                            u.code_of_conduct = True if coc_form_text is not None else False

                            u.first_name = data['first_name']
                            u.last_name = data['last_name']
                            u.email = data['email']
                            u.alt_email = data['alt_email']
                            u.mobile = data['mobile']
                            u.mobile_verified = False
                            u.gender = data['gender']

                            if 'student_number' in data:
                                u.student_number = data['student_number']

                            if 'union_member' in data:
                                u.union_member = data['union_member']

                            if 'tshirt' in data:
                                u.tshirt = data['tshirt']

                            # If chapter has enabled police check (required check is performed in clean() method
                            if 'police_check_number' in data and 'police_check_expiration' in data:
                                u.police_check_number = data[
                                    'police_check_number']
                                u.police_check_expiration = data[
                                    'police_check_expiration']
                                notify_chapter(chapter, u)

                            u.save()

                            # XXX: Just after saving the user model, you'd want to update your invite model with
                            # its new attributes and save those also
                            if invite:
                                invite.state = 1
                                invite.user = u
                                invite.save()

                            if chapter.welcome_email_enable:
                                welcome_email(request, chapter, u)

                            return HttpResponseRedirect(
                                "/welcome/" + chapter.myrobogals_url + "/")

                    else:
                        pwerr = _(
                            'The password and repeated password did not match. Please try again'
                        )
                else:
                    usererr = _('That username is already taken')

            # Compile all the errors into a list
            err = [usererr, pwerr, carderr, inverr]

    # XXX: Made the appropriate changes here and to the template to reflect arg. changes, make sure to check the case
    # where invite doesn't exist, you will need a different context dictionary without invite.TOKEN
    if coc_form_text is not None:
        return render_to_response('sign_up.html', {
            'signup_form': signup_form,
            'conduct_form': coc_form,
            'chapter': chapter,
            'err': err,
            'token': invite.TOKEN
        },
                                  context_instance=RequestContext(request))
    else:
        return render_to_response('sign_up.html', {
            'signup_form': signup_form,
            'chapter': chapter,
            'err': err,
            'token': invite.TOKEN
        },
                                  context_instance=RequestContext(request))
Пример #4
0
def edituser(request, username, chapter=None):
    pwerr = ''
    usererr = ''
    carderr = ''
    new_username = ''
    valid_card = False

    if username == '':
        join = True
        u = User()
        if request.user.is_superuser or (request.user.is_staff
                                         and request.user.chapter == chapter):
            adduser = True
        else:
            adduser = False
    else:
        join = False
        adduser = False
        if not request.user.is_authenticated():
            return HttpResponseRedirect("/login/?next=/profile/edit/")

        # Get reference to user
        u = get_object_or_404(User, username__exact=username)

        # Get user's chapter
        chapter = u.chapter

    # Either a superuser, self user or exec of chapter
    if join or request.user.is_superuser or request.user.id == u.id or (
            request.user.is_staff and request.user.chapter == u.chapter):
        # Form submission POST request
        if request.method == 'POST':
            # Obtaining the data from the post request
            formpart1 = FormPartOne(request.POST,
                                    chapter=chapter,
                                    user_id=u.id)
            formpart2 = FormPartTwo(request.POST, chapter=chapter)
            formpart3 = FormPartThree(request.POST, chapter=chapter)
            formpart4 = FormPartFour(request.POST, chapter=chapter)
            formpart5 = FormPartFive(request.POST, chapter=chapter)

            # Checking if the form is valid
            if formpart1.is_valid() and formpart2.is_valid(
            ) and formpart3.is_valid() and formpart4.is_valid(
            ) and formpart5.is_valid():
                if ('internal_notes' in request.POST) or (
                        'trained' in request.POST) or ('security_check'
                                                       in request.POST):
                    attempt_modify_exec_fields = True
                else:
                    attempt_modify_exec_fields = False

                # Clean data from form1
                data = formpart1.cleaned_data

                # Issue new username if a new user or old user changes his username
                if join or (data['username'] != ''
                            and data['username'] != u.username):
                    new_username = data['username']

                # If new username, verify the length of the username
                if new_username:
                    username_len = len(new_username)
                    if username_len < 3:
                        usererr = _(
                            'Your username must be 3 or more characters')
                    elif username_len > 30:
                        usererr = _(
                            'Your username must be less than 30 characters')

                    # Regex check for words, letters, numbers and underscores only in username
                    matches = re.compile(r'^\w+$').findall(new_username)
                    if matches == []:
                        usererr = _(
                            'Your username must contain only letters, numbers and underscores'
                        )

                    # See if it already exists in database
                    else:
                        try:
                            usercheck = User.objects.get(username=new_username)
                        except User.DoesNotExist:
                            if join:
                                if request.POST['password1'] == request.POST[
                                        'password2']:
                                    if len(request.POST['password1']) < 5:
                                        pwerr = _(
                                            'Your password must be at least 5 characters long'
                                        )
                                    else:
                                        # Creates, saves and returns a User object
                                        u = User.objects.create_user(
                                            new_username, '',
                                            request.POST['password1'])
                                        u.chapter = chapter
                                        mt = MemberStatus(user_id=u.pk,
                                                          statusType_id=1)
                                        mt.save()
                                        u.is_active = True
                                        u.is_staff = False
                                        u.is_superuser = False

                                        if 'police_check_number' in data and 'police_check_expiration' in data:
                                            u.police_check_number = data[
                                                'police_check_number']
                                            u.police_check_expiration = data[
                                                'police_check_expiration']
                                            notify_chapter(chapter, u)

                                        u.save()
                                else:
                                    pwerr = _(
                                        'The password and repeated password did not match. Please try again'
                                    )
                        else:
                            usererr = _('That username is already taken')

                # Chapter executive accessing the profile and trying to change a password
                if request.user.is_staff and request.user != u:
                    if len(request.POST['password1']) > 0:
                        if request.POST['password1'] == request.POST[
                                'password2']:
                            # Sets the password if it's the same, doesn't save the user object
                            u.set_password(request.POST['password1'])
                        else:
                            pwerr = _(
                                'The password and repeated password did not match. Please try again'
                            )

                # No password or username errors were encountered
                if pwerr == '' and usererr == '':
                    # Form 1 data
                    data = formpart1.cleaned_data
                    u.first_name = data['first_name']
                    u.last_name = data['last_name']

                    if new_username:
                        u.username = new_username

                    username = data['username']
                    u.email = data['email']
                    u.alt_email = data['alt_email']

                    if u.mobile != data['mobile']:
                        u.mobile = data['mobile']
                        u.mobile_verified = False

                    u.gender = data['gender']

                    if 'student_number' in data:
                        u.student_number = data['student_number']
                    if 'union_member' in data:
                        u.union_member = data['union_member']
                    if 'tshirt' in data:
                        u.tshirt = data['tshirt']
                    if 'police_check_number' in data and 'police_check_expiration' in data:
                        # Send email only if the user has changed/added a police check number instead of removing
                        if data['police_check_number'] != u.police_check_number and data[
                                'police_check_expiration'] != u.police_check_expiration:
                            u.police_check_number = data['police_check_number']
                            u.police_check_expiration = data[
                                'police_check_expiration']

                            # Notify chapter of police number changes
                            notify_chapter(chapter, u)

                    # Form 2 data
                    data = formpart2.cleaned_data
                    u.privacy = data['privacy']
                    u.dob_public = data['dob_public']
                    u.email_public = data['email_public']

                    # Form 3 data
                    data = formpart3.cleaned_data
                    u.dob = data['dob']
                    u.course = data['course']
                    u.uni_start = data['uni_start']
                    u.uni_end = data['uni_end']
                    u.university = data['university']
                    u.course_type = data['course_type']
                    u.student_type = data['student_type']
                    u.job_title = data['job_title']
                    u.company = data['company']
                    u.bio = data['bio']
                    # u.job_title = data['job_title']
                    # u.company = data['company']

                    # Form 4 data
                    data = formpart4.cleaned_data
                    u.email_reminder_optin = data['email_reminder_optin']
                    u.email_message_optin = data['email_message_optin']
                    u.mobile_reminder_optin = data['mobile_reminder_optin']
                    u.mobile_marketing_optin = data['mobile_marketing_optin']
                    u.email_newsletter_optin = data['email_newsletter_optin']
                    u.email_careers_newsletter_AU_optin = data[
                        'email_careers_newsletter_AU_optin']

                    # Check whether they have permissions to edit exec only fields
                    if attempt_modify_exec_fields and (
                            request.user.is_superuser
                            or request.user.is_staff):
                        data = formpart5.cleaned_data
                        u.internal_notes = data['internal_notes']
                        u.trained = data['trained']
                        u.security_check = data['security_check']

                    # Save user to database
                    u.save()

                    if 'return' in request.POST:
                        # Renders successful message on page
                        messages.success(
                            request,
                            message=unicode(
                                _("%(username)s has been added to the chapter")
                                % {'username': u.username}))

                        # Returns rendered page
                        return HttpResponseRedirect(request.POST['return'])

                    # If it's a new user signup
                    elif join:
                        if chapter.welcome_email_enable:
                            welcome_email(request, chapter, u)

                        # Notifies chapter of a new member the user joined on their own
                        if not adduser and chapter.notify_enable and chapter.notify_list:
                            # Sends an email to every exec on the notify list
                            message_subject = 'New user ' + u.get_full_name(
                            ) + ' joined ' + chapter.name
                            message_body = 'New user ' + u.get_full_name(
                            ) + ' joined ' + chapter.name + '<br/>username: '******'<br/>full name: ' + u.get_full_name(
                            ) + '<br/>email: ' + u.email
                            email_message(email_subject=message_subject,
                                          email_body=message_body,
                                          chapter=chapter)

                        # Renders welcome page
                        return HttpResponseRedirect("/welcome/" +
                                                    chapter.myrobogals_url +
                                                    "/")
                    else:
                        # Renders successfully updated profile message
                        messages.success(
                            request,
                            message=unicode(
                                _("Profile and settings updated!")))

                        # Returns rendered page
                        return HttpResponseRedirect("/profile/" + username +
                                                    "/")

        # Not POST response
        else:
            # If the user is new and joining a chapter
            if join:
                formpart1 = FormPartOne(None, chapter=chapter, user_id=0)
                formpart2 = FormPartTwo(None, chapter=chapter)
                formpart3 = FormPartThree(None, chapter=chapter)
                formpart4 = FormPartFour(None, chapter=chapter)
                formpart5 = FormPartFive(None, chapter=chapter)

            # Returning the forms with prefilled information about the user fetched from the database if editing user information
            else:
                if u.tshirt:
                    tshirt_id = u.tshirt.pk
                else:
                    tshirt_id = None

                # Data for FormPart1
                formpart1 = FormPartOne(
                    {
                        'first_name': u.first_name,
                        'last_name': u.last_name,
                        'username': u.username,
                        'email': u.email,
                        'alt_email': u.alt_email,
                        'mobile': u.mobile,
                        'gender': u.gender,
                        'student_number': u.student_number,
                        'union_member': u.union_member,
                        'police_check_number': u.police_check_number,
                        'police_check_expiration': u.police_check_expiration,
                        'tshirt': tshirt_id
                    },
                    chapter=chapter,
                    user_id=u.pk)

                # Data for FormPart2
                formpart2 = FormPartTwo(
                    {
                        'privacy': u.privacy,
                        'dob_public': u.dob_public,
                        'email_public': u.email_public
                    },
                    chapter=chapter)
                if u.university:
                    uni = u.university.pk
                else:
                    uni = None
                formpart3 = FormPartThree(
                    {
                        'dob': u.dob,
                        'course': u.course,
                        'uni_start': u.uni_start,
                        'uni_end': u.uni_end,
                        'university': uni,
                        'job_title': u.job_title,
                        'company': u.company,
                        'course_type': u.course_type,
                        'student_type': u.student_type,
                        'bio': u.bio
                    },
                    chapter=chapter)
                formpart4 = FormPartFour(
                    {
                        'email_reminder_optin':
                        u.email_reminder_optin,
                        'email_message_optin':
                        u.email_message_optin,
                        'mobile_reminder_optin':
                        u.mobile_reminder_optin,
                        'mobile_marketing_optin':
                        u.mobile_marketing_optin,
                        'email_newsletter_optin':
                        u.email_newsletter_optin,
                        'email_careers_newsletter_AU_optin':
                        u.email_careers_newsletter_AU_optin
                    },
                    chapter=chapter)
                formpart5 = FormPartFive(
                    {
                        'internal_notes': u.internal_notes,
                        'trained': u.trained,
                        'security_check': u.security_check
                    },
                    chapter=chapter)

        if 'return' in request.GET:
            return_url = request.GET['return']
        elif 'return' in request.POST:
            return_url = request.POST['return']
        else:
            return_url = ''

        chpass = (join or (request.user.is_staff and request.user != u))
        exec_fields = request.user.is_superuser or (
            request.user.is_staff and request.user.chapter == chapter)

        return render_to_response('profile_edit.html', {
            'join': join,
            'adduser': adduser,
            'chpass': chpass,
            'exec_fields': exec_fields,
            'formpart1': formpart1,
            'formpart2': formpart2,
            'formpart3': formpart3,
            'formpart4': formpart4,
            'formpart5': formpart5,
            'u': u,
            'chapter': chapter,
            'usererr': usererr,
            'pwerr': pwerr,
            'carderr': carderr,
            'new_username': new_username,
            'return': return_url
        },
                                  context_instance=RequestContext(request))
    else:
        raise Http404  # don't have permission to change
Пример #5
0
def newuser(request, chapter):
    pwerr = ''
    usererr = ''
    carderr = ''
    err = []

    signup_form = FormPartOne(request.POST or None, chapter=chapter, user_id='')

    coc_form_text = openconductfile()

    if coc_form_text is not None:
        coc_form = CodeOfConductForm(request.POST or None)

    if request.method == 'POST':
        # Checks coc_form is assigned before calling is valid
        if coc_form_text is not None:
            valid_forms = signup_form.is_valid() and coc_form.is_valid()
        else:
            valid_forms = signup_form.is_valid()

        if valid_forms:
            data = signup_form.cleaned_data

            new_username = data['username']

            # Checking validity of length
            username_len = len(new_username)
            if username_len < 3:
                usererr = _('Your username must be 3 or more characters')
            elif username_len > 30:
                usererr = _('Your username must be less than 30 characters')

            # Regex check for words, letters, numbers and underscores only in username
            matches = re.compile(r'^\w+$').findall(new_username)
            if matches == []:
                usererr = _('Your username must contain only letters, numbers and underscores')

            # See if it already exists in database
            else:
                try:
                    User.objects.get(username=new_username)
                except User.DoesNotExist:
                    if request.POST['password1'] == request.POST['password2']:
                        if len(request.POST['password1']) < 5:
                            pwerr = _('Your password must be at least 5 characters long')
                        else:
                            # Creates, saves and returns a User object
                            u = User.objects.create_user(new_username, '', request.POST['password1'])
                            u.chapter = chapter
                            mt = MemberStatus(user_id=u.pk, statusType_id=1)
                            mt.save()
                            u.is_active = True
                            u.is_staff = False
                            u.is_superuser = False
                            u.code_of_conduct = True if coc_form_text is not None else False

                            u.first_name = data['first_name']
                            u.last_name = data['last_name']
                            u.email = data['email']
                            u.alt_email = data['alt_email']
                            u.mobile = data['mobile']
                            u.mobile_verified = False
                            u.gender = data['gender']

                            if 'student_number' in data:
                                u.student_number = data['student_number']

                            if 'union_member' in data:
                                u.union_member = data['union_member']

                            if 'tshirt' in data:
                                u.tshirt = data['tshirt']

                            # If chapter has enabled police check (required check is performed in clean() method
                            if 'police_check_number' in data and 'police_check_expiration' in data:
                                u.police_check_number = data['police_check_number']
                                u.police_check_expiration = data['police_check_expiration']
                                notify_chapter(chapter, u)

                            u.save()

                            if chapter.welcome_email_enable:
                                welcome_email(request, chapter, u)

                            return HttpResponseRedirect("/welcome/" + chapter.myrobogals_url + "/")
                    else:
                        pwerr = _('The password and repeated password did not match. Please try again')
                else:
                    usererr = _('That username is already taken')

            # Compile all the errors into a list
            err = [usererr, pwerr, carderr]

    if coc_form_text is not None:
        return render_to_response('sign_up.html', {'signup_form': signup_form, 'conduct_form': coc_form, 'chapter': chapter, 'err': err}, context_instance=RequestContext(request))
    else:
        return render_to_response('sign_up.html', {'signup_form': signup_form, 'chapter': chapter, 'err': err}, context_instance=RequestContext(request))
Пример #6
0
def edituser(request, username, chapter=None):
    pwerr = ''
    usererr = ''
    carderr = ''
    new_username = ''
    valid_card = False

    if username == '':
        join = True
        u = User()
        if request.user.is_superuser or is_executive_or_higher(request.user, chapter):
            adduser = True
        else:
            adduser = False
    else:
        join = False
        adduser = False
        if not request.user.is_authenticated():
            return HttpResponseRedirect("/login/?next=/profile/edit/")

        # Get reference to user
        u = get_object_or_404(User, username__exact=username)

        # Get user's chapter
        chapter = u.chapter

    # Either a superuser, self user or exec of chapter
    if join or request.user.is_superuser or request.user.id == u.id or is_executive_or_higher(request.user, chapter):
        # Form submission POST request
        if request.method == 'POST':
            # Obtaining the data from the post request
            formpart1 = FormPartOne(request.POST, chapter=chapter, user_id=u.id)
            formpart2 = FormPartTwo(request.POST, chapter=chapter)
            formpart3 = FormPartThree(request.POST, chapter=chapter)
            formpart4 = FormPartFour(request.POST, chapter=chapter)
            formpart5 = FormPartFive(request.POST, chapter=chapter)

            # Checking if the form is valid
            if formpart1.is_valid() and formpart2.is_valid() and formpart3.is_valid() and formpart4.is_valid() and formpart5.is_valid():
                if ('internal_notes' in request.POST) or ('trained' in request.POST) or ('security_check' in request.POST):
                    attempt_modify_exec_fields = True
                else:
                    attempt_modify_exec_fields = False

                # Clean data from form1
                data = formpart1.cleaned_data

                # Issue new username if a new user or old user changes his username
                if join or (data['username'] != '' and data['username'] != u.username):
                    new_username = data['username']

                # If new username, verify the length of the username
                if new_username:
                    username_len = len(new_username)
                    if username_len < 3:
                        usererr = _('Your username must be 3 or more characters')
                    elif username_len > 30:
                        usererr = _('Your username must be less than 30 characters')

                    # Regex check for words, letters, numbers and underscores only in username
                    matches = re.compile(r'^\w+$').findall(new_username)
                    if matches == []:
                        usererr = _('Your username must contain only letters, numbers and underscores')

                    # See if it already exists in database
                    else:
                        try:
                            usercheck = User.objects.get(username=new_username)
                        except User.DoesNotExist:
                            if join:
                                if request.POST['password1'] == request.POST['password2']:
                                    if len(request.POST['password1']) < 5:
                                        pwerr = _('Your password must be at least 5 characters long')
                                    else:
                                        # Creates, saves and returns a User object
                                        u = User.objects.create_user(new_username, '', request.POST['password1'])
                                        u.chapter = chapter
                                        mt = MemberStatus(user_id=u.pk, statusType_id=1)
                                        mt.save()
                                        u.is_active = True
                                        u.is_staff = False
                                        u.is_superuser = False

                                        if 'police_check_number' in data and 'police_check_expiration' in data:
                                            u.police_check_number = data['police_check_number']
                                            u.police_check_expiration = data['police_check_expiration']
                                            notify_chapter(chapter, u)

                                        u.save()
                                else:
                                    pwerr = _('The password and repeated password did not match. Please try again')
                        else:
                            usererr = _('That username is already taken')

                # Chapter executive accessing the profile and trying to change a password
                if is_executive_or_higher(request.user, chapter) and request.user != u:
                    if len(request.POST['password1']) > 0:
                        if request.POST['password1'] == request.POST['password2']:
                            # Sets the password if it's the same, doesn't save the user object
                            u.set_password(request.POST['password1'])
                        else:
                            pwerr = _('The password and repeated password did not match. Please try again')

                # No password or username errors were encountered
                if pwerr == '' and usererr == '':
                    # Form 1 data
                    data = formpart1.cleaned_data
                    u.first_name = data['first_name']
                    u.last_name = data['last_name']

                    if new_username:
                        u.username = new_username

                    username = data['username']
                    u.email = data['email']
                    u.alt_email = data['alt_email']

                    if u.mobile != data['mobile']:
                        u.mobile = data['mobile']
                        u.mobile_verified = False

                    u.gender = data['gender']

                    if 'student_number' in data:
                        u.student_number = data['student_number']
                    if 'union_member' in data:
                        u.union_member = data['union_member']
                    if 'tshirt' in data:
                        u.tshirt = data['tshirt']
                    if 'police_check_number' in data and 'police_check_expiration' in data:
                        # Send email only if the user has changed/added a police check number instead of removing
                        if data['police_check_number'] != u.police_check_number and data['police_check_expiration'] != u.police_check_expiration:
                            u.police_check_number = data['police_check_number']
                            u.police_check_expiration = data['police_check_expiration']

                            # Notify chapter of police number changes
                            notify_chapter(chapter, u)

                    # Form 2 data
                    data = formpart2.cleaned_data
                    u.privacy = data['privacy']
                    u.dob_public = data['dob_public']
                    u.email_public = data['email_public']

                    # Form 3 data
                    data = formpart3.cleaned_data
                    u.dob = data['dob']
                    u.course = data['course']
                    u.uni_start = data['uni_start']
                    u.uni_end = data['uni_end']
                    u.university = data['university']
                    u.course_type = data['course_type']
                    u.student_type = data['student_type']
                    u.job_title = data['job_title']
                    u.company = data['company']
                    u.bio = data['bio']
                    # u.job_title = data['job_title']
                    # u.company = data['company']

                    # Form 4 data
                    data = formpart4.cleaned_data
                    u.email_reminder_optin = data['email_reminder_optin']
                    u.email_chapter_optin = data['email_chapter_optin']
                    u.mobile_reminder_optin = data['mobile_reminder_optin']
                    u.mobile_marketing_optin = data['mobile_marketing_optin']
                    u.email_newsletter_optin = data['email_newsletter_optin']
                    u.email_careers_newsletter_AU_optin = data['email_careers_newsletter_AU_optin']

                    # Check whether they have permissions to edit exec only fields
                    if attempt_modify_exec_fields and (request.user.is_superuser or is_executive_or_higher(request.user, chapter)):
                        data = formpart5.cleaned_data
                        u.internal_notes = data['internal_notes']
                        u.trained = data['trained']
                        u.security_check = data['security_check']

                    # Save user to database
                    u.save()

                    if 'return' in request.POST:
                        # Renders successful message on page
                        messages.success(request, message=unicode(
                            _("%(username)s has been added to the chapter") % {'username': u.username}))

                        # Returns rendered page
                        return HttpResponseRedirect(request.POST['return'])

                    # If it's a new user signup
                    elif join:
                        if chapter.welcome_email_enable:
                            welcome_email(request, chapter, u)

                        # Notifies chapter of a new member the user joined on their own
                        if not adduser and chapter.notify_enable and chapter.notify_list:
                            # Sends an email to every exec on the notify list
                            message_subject = 'New user ' + u.get_full_name() + ' joined ' + chapter.name
                            message_body = 'New user ' + u.get_full_name() + ' joined ' + chapter.name + '<br/>username: '******'<br/>full name: ' + u.get_full_name() + '<br/>email: ' + u.email
                            email_message(email_subject=message_subject, email_body=message_body, chapter=chapter)

                        # Renders welcome page
                        return HttpResponseRedirect("/welcome/" + chapter.myrobogals_url + "/")
                    else:
                        # Renders successfully updated profile message
                        messages.success(request, message=unicode(_("Profile and settings updated!")))

                        # Returns rendered page
                        return HttpResponseRedirect("/profile/" + username + "/")

        # Not POST response
        else:
            # If the user is new and joining a chapter
            if join:
                formpart1 = FormPartOne(None, chapter=chapter, user_id=0)
                formpart2 = FormPartTwo(None, chapter=chapter)
                formpart3 = FormPartThree(None, chapter=chapter)
                formpart4 = FormPartFour(None, chapter=chapter)
                formpart5 = FormPartFive(None, chapter=chapter)

            # Returning the forms with prefilled information about the user fetched from the database if editing user information
            else:
                if u.tshirt:
                    tshirt_id = u.tshirt.pk
                else:
                    tshirt_id = None

                # Data for FormPart1
                formpart1 = FormPartOne({
                    'first_name': u.first_name,
                    'last_name': u.last_name,
                    'username': u.username,
                    'email': u.email,
                    'alt_email': u.alt_email,
                    'mobile': u.mobile,
                    'gender': u.gender,
                    'student_number': u.student_number,
                    'union_member': u.union_member,
                    'police_check_number': u.police_check_number,
                    'police_check_expiration': u.police_check_expiration,
                    'tshirt': tshirt_id}, chapter=chapter, user_id=u.pk)

                # Data for FormPart2
                formpart2 = FormPartTwo({
                    'privacy': u.privacy,
                    'dob_public': u.dob_public,
                    'email_public': u.email_public}, chapter=chapter)
                if u.university:
                    uni = u.university.pk
                else:
                    uni = None
                formpart3 = FormPartThree({
                    'dob': u.dob,
                    'course': u.course,
                    'uni_start': u.uni_start,
                    'uni_end': u.uni_end,
                    'university': uni,
                    'job_title': u.job_title,
                    'company': u.company,
                    'course_type': u.course_type,
                    'student_type': u.student_type,
                    'bio': u.bio}, chapter=chapter)
                formpart4 = FormPartFour({
                    'email_reminder_optin': u.email_reminder_optin,
                    'email_chapter_optin': u.email_chapter_optin,
                    'mobile_reminder_optin': u.mobile_reminder_optin,
                    'mobile_marketing_optin': u.mobile_marketing_optin,
                    'email_newsletter_optin': u.email_newsletter_optin,
                    'email_careers_newsletter_AU_optin': u.email_careers_newsletter_AU_optin}, chapter=chapter)
                formpart5 = FormPartFive({
                    'internal_notes': u.internal_notes,
                    'trained': u.trained,
                    'security_check': u.security_check}, chapter=chapter)

        if 'return' in request.GET:
            return_url = request.GET['return']
        elif 'return' in request.POST:
            return_url = request.POST['return']
        else:
            return_url = ''

        chpass = (join or (is_executive_or_higher(request.user, chapter) and request.user != u))
        exec_fields = request.user.is_superuser or is_executive_or_higher(request.user, chapter)

        return render_to_response('profile_edit.html', {'join': join,
                                                        'adduser': adduser,
                                                        'chpass': chpass,
                                                        'exec_fields': exec_fields,
                                                        'formpart1': formpart1,
                                                        'formpart2': formpart2,
                                                        'formpart3': formpart3,
                                                        'formpart4': formpart4,
                                                        'formpart5': formpart5,
                                                        'u': u,
                                                        'chapter': chapter,
                                                        'usererr': usererr,
                                                        'pwerr': pwerr,
                                                        'carderr': carderr,
                                                        'new_username': new_username,
                                                        'return': return_url},
                                  context_instance=RequestContext(request))
    else:
        raise Http404  # don't have permission to change
Пример #7
0
def deleteuser(request, userpk):
    userToBeDeleted = get_object_or_404(User, pk=userpk)
    if request.user.is_superuser or is_executive_or_higher(request.user, userToBeDeleted.chapter):
        msg = ''
        old_status = userToBeDeleted.memberstatus_set.get(status_date_end__isnull=True)
        canNotDelete = False
        if Position.objects.filter(user=userToBeDeleted):
            msg = _('<br>Member "%s" has held at least one officeholder position. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if EventAttendee.objects.filter(user=userToBeDeleted, actual_status=1):
            msg += _('<br>Member "%s" has attended at least one school visit. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if Event.objects.filter(creator=userToBeDeleted):
            msg += _('<br>Member "%s" has created at least one school visit. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if EmailMessage.objects.filter(sender=userToBeDeleted):
            msg += _('<br>Member "%s" has sent at least one email. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if SMSMessage.objects.filter(sender=userToBeDeleted):
            msg += _('<br>Member "%s" has sent at least one SMS message. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if LogEntry.objects.filter(user=userToBeDeleted):
            msg += _('<br>Member "%s" owned at least one admin log object. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if not canNotDelete:
            if (request.method != 'POST') or (('delete' not in request.POST) and ('alumni' not in request.POST)):
                return render_to_response('user_delete_confirm.html',
                                          {'userToBeDeleted': userToBeDeleted, 'return': request.GET['return']},
                                          context_instance=RequestContext(request))
            else:
                if ('delete' in request.POST) and ('alumni' not in request.POST):
                    userToBeDeleted.delete()
                    msg = _('Member "%s" deleted') % userToBeDeleted.get_full_name()
                elif ('delete' not in request.POST) and ('alumni' in request.POST):
                    if old_status.statusType == MemberStatusType.objects.get(pk=2):
                        msg = _('Member "%s" is already marked as alumni') % userToBeDeleted.get_full_name()
                    else:
                        if userToBeDeleted.membertype().description != 'Inactive':
                            old_status.status_date_end = date.today()
                            old_status.save()
                        new_status = MemberStatus()
                        new_status.user = userToBeDeleted
                        new_status.statusType = MemberStatusType.objects.get(pk=2)
                        new_status.status_date_start = date.today()
                        new_status.save()
                        msg = _('Member "%s" marked as alumni') % userToBeDeleted.get_full_name()
                else:
                    raise Http404
        if canNotDelete:
            messages.success(request, message=unicode(
                _('- Cannot delete member. Reason(s): %s<br>Consider marking this member as alumni instead.') % msg))
        else:
            messages.success(request, message=unicode(msg))
        if 'return' in request.GET:
            return HttpResponseRedirect(request.GET['return'])
        else:
            return HttpResponseRedirect(
                '/chapters/' + request.user.chapter.myrobogals_url + '/edit/users/?search=&status=' + str(
                    old_status.statusType.pk))
    else:
        raise Http404
Пример #8
0
def importcsv(filerows, welcomeemail, defaults, chapter, updateuser,
              ignore_email):
    columns = None
    users_imported = 0
    username_pos = 0
    users_updated = 0
    existing_users = 0
    existing_emails = 0
    count = -1
    username_field_exists_flag = False
    user_already_exists = False
    msg = ""
    if 'date_joined' not in defaults:
        defaults['date_joined'] = timezone.now()
    elif defaults['date_joined'] == None:
        defaults['date_joined'] = timezone.now()
    for row in filerows:
        if any(row):
            # Create new user
            newuser = User()
            count += 1
            user_already_exists_flag = False
            # Get column names from first row, also get the positions of the fields so that we can extract their values
            # using their positions later.
            if (columns == None):
                columns = row
                if 'first_name' not in columns:
                    raise RgImportCsvException(
                        _('You must specify a first_name field'))
                else:
                    first_name_pos = columns.index('first_name')

                if 'last_name' not in columns:
                    raise RgImportCsvException(
                        _('You must specify a last_name field'))
                else:
                    last_name_pos = columns.index('last_name')

                if 'email' not in columns:
                    raise RgImportCsvException(
                        _('You must specify an email field'))
                else:
                    email_pos = columns.index('email')

                if 'username' in columns:
                    username_pos = columns.index('username')
                    username_field_exists_flag = True

                if 'mobile' in columns:
                    mobile_pos = columns.index('mobile')

                continue

            # Process row
            i = 0

            # extracting the values of the username, email, first_name and last_name fields for each row.
            if username_field_exists_flag:
                uname = row[username_pos]
            else:
                uname = ''
            email = row[email_pos]
            first_name = row[first_name_pos]
            last_name = row[last_name_pos]

            # now remove all the whitespaces from the extracted values.
            uname_data = uname.strip()
            email_data = email.strip()
            first_name_data = first_name.strip()
            last_name_data = last_name.strip()

            # check if any of the values is None or empty for a row. If yes, form an error message and ignore that row.
            if first_name_data == None or first_name_data == '':
                msg += ("<br>First name not provided for row %d - row ignored."
                        ) % count
                continue
            if last_name_data == None or last_name_data == '':
                msg += ("<br>Last name not provided for row %d - row ignored."
                        ) % count
                continue
            if email_data == None or email_data == '':
                msg += (
                    "<br>Email not provided for row %d - row ignored.") % count
                continue

            # check if the username exists, if yes, check if the 'updateuser' checkbox is ticked. If it is ticked,
            # then get the row with the matching username (and, as we will see, replace its contents). Otherwise, ignore.
            # Also, they must be from the same chapter
            if not check_username(uname_data):
                user_already_exists_flag = True
                if updateuser:
                    newuser = User.objects.get(username=uname_data)
                    if newuser.chapter == chapter:
                        existing_users += 1
                    else:
                        msg += (
                            "<br>Row %d has a username clash (%s) with another chapter - row ignored"
                        ) % (count, uname_data)
                        continue
                else:
                    msg += (
                        "<br>Row %d has a username clash (%s) - row ignored"
                    ) % (count, uname_data)
                    continue

            # check if the email exists for any user, if yes, check if the 'ignore_email' checkbox is ticked. If it is not ticked,
            # then get the row with the matching username (and, as we will see, replace its contents). Otherwise, ignore.
            # Also, they must be from the same chapter
            elif not check_email_and_chapter(email_data, chapter):
                existing_emails += 1
                if ignore_email:
                    msg += (
                        "<br>Row %d's email address (%s) matches an existing user - row ignored"
                    ) % (count, email_data)
                    continue

            for cell in row:
                colname = columns[i]
                if colname == 'first_name':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'last_name':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'email':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'username':
                    data = cell.strip()
                    if data != "":
                        new_username = data
                    else:
                        new_username = generate_unique_username(row, columns)
                    newuser.username = new_username
                elif colname == 'password':
                    data = cell.strip()
                    if data != "":
                        plaintext_password = data
                    else:
                        plaintext_password = User.objects.make_random_password(
                            6)
                    newuser.set_password(plaintext_password)
                elif colname == 'alt_email':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'mobile':
                    num = cell.strip().replace(' ', '').replace('+', '')
                    if num != '':
                        regexes = MobileRegex.objects.filter(
                            collection=chapter.mobile_regexes)
                        try:
                            number_valid = False
                            for regex in regexes:
                                matches = re.compile(regex.regex).findall(num)
                                if matches == []:
                                    matches = re.compile(
                                        regex.regex).findall("0" + num)
                                    if matches == []:
                                        continue
                                    else:
                                        num = "0" + num
                                num = regex.prepend_digits + num[regex.
                                                                 strip_digits:]
                                number_valid = True
                        except ValueError:
                            number_valid = False
                        if number_valid:
                            newuser.mobile = num
                elif colname == 'date_joined':
                    dateval(colname, cell, newuser, defaults)
                elif colname == 'dob':
                    dateval(colname, cell, newuser, defaults)
                elif colname == 'gender':
                    numval(colname, cell, newuser, defaults, [0, 1, 2])
                elif colname == 'course':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'uni_start':
                    dateval(colname, cell, newuser, defaults)
                elif colname == 'uni_end':
                    dateval(colname, cell, newuser, defaults)
                elif colname == 'university_id':
                    unis = University.objects.all()
                    uni_ids = [-1]
                    for uni in unis:
                        uni_ids.append(uni.pk)
                    numval(colname, cell, newuser, defaults, uni_ids)
                    if getattr(newuser, 'university_id', 0) == -1:
                        newuser.university_id = chapter.university_id
                elif colname == 'course_type':
                    numval(colname, cell, newuser, defaults, [1, 2])
                elif colname == 'student_type':
                    numval(colname, cell, newuser, defaults, [1, 2])
                elif colname == 'student_number':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'privacy':
                    numval(colname, cell, newuser, defaults, [0, 5, 10, 20])
                elif colname == 'dob_public':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_public':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_chapter_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'mobile_marketing_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_reminder_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'mobile_reminder_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_newsletter_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_careers_newsletter_AU_optin':
                    boolval(colname, cell, newuser, defaults)
                else:
                    pass  # Unknown column, ignore
                # Increment column and do the loop again
                i += 1

            # If we still don't have a username and/or password
            # by this stage, let's generate one
            if getattr(newuser, 'username', '') == '':
                new_username = generate_unique_username(row, columns)
                newuser.username = new_username
            if getattr(newuser, 'password', '') == '':
                plaintext_password = User.objects.make_random_password(6)
                newuser.set_password(plaintext_password)

            # And finally...
            newuser.chapter = chapter
            newuser.save()

            # If updating an existing user, we don't need to do the rest
            if user_already_exists_flag:
                continue

            # Should be the default at the model-level,
            # but just to be sure...
            newuser.is_active = True
            newuser.is_staff = False
            newuser.is_superuser = False

            # Apply any unapplied defaults
            for key, value in defaults.iteritems():
                if key not in columns:
                    setattr(newuser, key, value)

            newuser.save()

            # Must be called after newuser.save() because the primary key
            # is required for these
            mt = MemberStatus(user_id=newuser.pk,
                              statusType_id=1,
                              status_date_start=newuser.date_joined)
            mt.save()

            # Send welcome email
            if welcomeemail:
                message = EmailMessage()
                try:
                    message.subject = welcomeemail['subject'].format(
                        chapter=chapter,
                        user=newuser,
                        plaintext_password=plaintext_password)
                except Exception:
                    newuser.delete()
                    raise RgImportCsvException(
                        _('Welcome email subject format is invalid'))
                try:
                    message.body = welcomeemail['body'].format(
                        chapter=chapter,
                        user=newuser,
                        plaintext_password=plaintext_password)
                except Exception:
                    newuser.delete()
                    raise RgImportCsvException(
                        _('Welcome email format is invalid'))
                message.from_address = '*****@*****.**'
                message.reply_address = '*****@*****.**'
                message.from_name = chapter.name
                message.sender = User.objects.get(username='******')
                message.html = welcomeemail['html']
                message.status = -1
                message.save()
                recipient = EmailRecipient()
                recipient.message = message
                recipient.user = newuser
                recipient.to_name = newuser.get_full_name()
                recipient.to_address = newuser.email
                recipient.save()
                message.status = 0
                message.save()

            users_imported += 1

    return users_imported, existing_users, existing_emails, msg
Пример #9
0
def deleteuser(request, userpk):
    userToBeDeleted = get_object_or_404(User, pk=userpk)
    if request.user.is_superuser or is_executive_or_higher(request.user, userToBeDeleted.chapter):
        msg = ''
        old_status = userToBeDeleted.memberstatus_set.get(status_date_end__isnull=True)
        canNotDelete = False
        if Position.objects.filter(user=userToBeDeleted):
            msg = _('<br>Member "%s" has held at least one officeholder position. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if EventAttendee.objects.filter(user=userToBeDeleted, actual_status=1):
            msg += _('<br>Member "%s" has attended at least one school visit. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if Event.objects.filter(creator=userToBeDeleted):
            msg += _('<br>Member "%s" has created at least one school visit. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if EmailMessage.objects.filter(sender=userToBeDeleted):
            msg += _('<br>Member "%s" has sent at least one email. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if SMSMessage.objects.filter(sender=userToBeDeleted):
            msg += _('<br>Member "%s" has sent at least one SMS message. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if LogEntry.objects.filter(user=userToBeDeleted):
            msg += _('<br>Member "%s" owned at least one admin log object. ') % userToBeDeleted.get_full_name()
            canNotDelete = True
        if not canNotDelete:
            if (request.method != 'POST') or (('delete' not in request.POST) and ('alumni' not in request.POST)):
                return render_to_response('user_delete_confirm.html',
                                          {'userToBeDeleted': userToBeDeleted, 'return': request.GET['return']},
                                          context_instance=RequestContext(request))
            else:
                if ('delete' in request.POST) and ('alumni' not in request.POST):
                    userToBeDeleted.delete()
                    msg = _('Member "%s" deleted') % userToBeDeleted.get_full_name()
                elif ('delete' not in request.POST) and ('alumni' in request.POST):
                    if old_status.statusType == MemberStatusType.objects.get(pk=2):
                        msg = _('Member "%s" is already marked as alumni') % userToBeDeleted.get_full_name()
                    else:
                        if userToBeDeleted.membertype().description != 'Inactive':
                            old_status.status_date_end = date.today()
                            old_status.save()
                        new_status = MemberStatus()
                        new_status.user = userToBeDeleted
                        new_status.statusType = MemberStatusType.objects.get(pk=2)
                        new_status.status_date_start = date.today()
                        new_status.save()
                        msg = _('Member "%s" marked as alumni') % userToBeDeleted.get_full_name()
                else:
                    raise Http404
        if canNotDelete:
            messages.success(request, message=unicode(
                _('- Cannot delete member. Reason(s): %s<br>Consider marking this member as alumni instead.') % msg))
        else:
            messages.success(request, message=unicode(msg))
        if 'return' in request.GET:
            return HttpResponseRedirect(request.GET['return'])
        else:
            return HttpResponseRedirect(
                '/chapters/' + request.user.chapter.myrobogals_url + '/edit/users/?search=&status=' + str(
                    old_status.statusType.pk))
    else:
        raise Http404
Пример #10
0
def newuser(request, chapter):
    pwerr = ''
    usererr = ''
    carderr = ''
    err = []

    signup_form = FormPartOne(request.POST or None,
                              chapter=chapter,
                              user_id='')

    coc_form_text = openconductfile()

    if coc_form_text is not None:
        coc_form = CodeOfConductForm(request.POST or None)

    if request.method == 'POST':
        # Checks coc_form is assigned before calling is valid
        if coc_form_text is not None:
            valid_forms = signup_form.is_valid() and coc_form.is_valid()
        else:
            valid_forms = signup_form.is_valid()

        if valid_forms:
            data = signup_form.cleaned_data

            new_username = data['username']

            # Checking validity of length
            username_len = len(new_username)
            if username_len < 3:
                usererr = _('Your username must be 3 or more characters')
            elif username_len > 30:
                usererr = _('Your username must be less than 30 characters')

            # Regex check for words, letters, numbers and underscores only in username
            matches = re.compile(r'^\w+$').findall(new_username)
            if matches == []:
                usererr = _(
                    'Your username must contain only letters, numbers and underscores'
                )

            # See if it already exists in database
            else:
                try:
                    User.objects.get(username=new_username)
                except User.DoesNotExist:
                    if request.POST['password1'] == request.POST['password2']:
                        if len(request.POST['password1']) < 5:
                            pwerr = _(
                                'Your password must be at least 5 characters long'
                            )
                        else:
                            # Creates, saves and returns a User object
                            u = User.objects.create_user(
                                new_username, '', request.POST['password1'])
                            u.chapter = chapter
                            mt = MemberStatus(user_id=u.pk, statusType_id=1)
                            mt.save()
                            u.is_active = True
                            u.is_staff = False
                            u.is_superuser = False
                            u.code_of_conduct = True if coc_form_text is not None else False

                            u.first_name = data['first_name']
                            u.last_name = data['last_name']
                            u.email = data['email']
                            u.alt_email = data['alt_email']
                            u.mobile = data['mobile']
                            u.mobile_verified = False
                            u.gender = data['gender']

                            if 'student_number' in data:
                                u.student_number = data['student_number']

                            if 'union_member' in data:
                                u.union_member = data['union_member']

                            if 'tshirt' in data:
                                u.tshirt = data['tshirt']

                            # If chapter has enabled police check (required check is performed in clean() method
                            if 'police_check_number' in data and 'police_check_expiration' in data:
                                u.police_check_number = data[
                                    'police_check_number']
                                u.police_check_expiration = data[
                                    'police_check_expiration']
                                notify_chapter(chapter, u)

                            u.save()

                            if chapter.welcome_email_enable:
                                welcome_email(request, chapter, u)

                            return HttpResponseRedirect(
                                "/welcome/" + chapter.myrobogals_url + "/")
                    else:
                        pwerr = _(
                            'The password and repeated password did not match. Please try again'
                        )
                else:
                    usererr = _('That username is already taken')

            # Compile all the errors into a list
            err = [usererr, pwerr, carderr]

    if coc_form_text is not None:
        return render_to_response('sign_up.html', {
            'signup_form': signup_form,
            'conduct_form': coc_form,
            'chapter': chapter,
            'err': err
        },
                                  context_instance=RequestContext(request))
    else:
        return render_to_response('sign_up.html', {
            'signup_form': signup_form,
            'chapter': chapter,
            'err': err
        },
                                  context_instance=RequestContext(request))