Ejemplo n.º 1
0
def register(request):
    if not settings.OPPIA_ALLOW_SELF_REGISTRATION:
        raise Http404

    if request.method == 'POST':  # if form submitted...
        form = RegisterForm(request.POST)
        form.fields['location'].choices = get_location_choices()
        if form.is_valid():  # All validation rules pass
            # Create new user
            username = form.cleaned_data.get("username")
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")
            first_name = form.cleaned_data.get("first_name")
            last_name = form.cleaned_data.get("last_name")
            user = User.objects.create_user(username, email, password)
            user.first_name = first_name
            user.last_name = last_name
            user.save()

            try:
                facility = Facility.objects.get(
                    pk=form.cleaned_data.get("location"))
            except Facility.DoesNotExist:
                facility = None

            user_profile = UserProfile()
            user_profile.user = user
            user_profile.job_title = form.cleaned_data.get("job_title")
            user_profile.organisation = form.cleaned_data.get("organisation")
            user_profile.profession = form.cleaned_data.get("profession")
            user_profile.service_entry_date = form.cleaned_data.get(
                "service_entry_date")
            user_profile.location = facility
            user_profile.save()
            u = authenticate(username=username, password=password)
            if u is not None:
                if u.is_active:
                    login(request, u)
                    return HttpResponseRedirect('thanks/')
            return HttpResponseRedirect('thanks/')  # Redirect after POST
    else:
        form = RegisterForm(initial={
            'next': filterRedirect(request.GET),
        })
        form.fields['location'].choices = get_location_choices()

    return render_to_response(
        'oppia/form.html',
        {
            'form': form,
            'title': _(u'Register'),
        },
        context_instance=RequestContext(request),
    )
Ejemplo n.º 2
0
def register(request):
    if not settings.OPPIA_ALLOW_SELF_REGISTRATION:
        raise Http404

    if request.method == 'POST':  # if form submitted...
        form = RegisterForm(request.POST)
        if form.is_valid():  # All validation rules pass
            # Create new user
            username = form.cleaned_data.get("username")
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")
            first_name = form.cleaned_data.get("first_name")
            last_name = form.cleaned_data.get("last_name")
            user = User.objects.create_user(username, email, password)
            user.first_name = first_name
            user.last_name = last_name
            user.save()
            
            user_profile = UserProfile()
            user_profile.user = user
            user_profile.sex = form.cleaned_data.get("sex")
            user_profile.age_range =  form.cleaned_data.get("age_range")
            user_profile.role =  form.cleaned_data.get("role")
            user_profile.location = form.cleaned_data.get("location")
            user_profile.save()

            u = authenticate(username=username, password=password)
            if u is not None and u.is_active:
                login(request, u)
                return HttpResponseRedirect('thanks/')
            return HttpResponseRedirect('thanks/')  # Redirect after POST
    else:
        form = RegisterForm(initial={'next': filter_redirect(request.GET), })

    return render(request, 'oppia/form.html',
                              {'form': form,
                               'title': _(u'Register'), })
Ejemplo n.º 3
0
    def obj_create(self, bundle, **kwargs):
        if not settings.OPPIA_ALLOW_SELF_REGISTRATION:
            raise BadRequest(_(u'Registration is disabled on this server.'))
        required = [
            'username', 'password', 'passwordagain', 'email', 'firstname',
            'lastname'
        ]

        check_required_params(bundle, required)

        data = {
            'username': bundle.data['username'],
            'password': bundle.data['password'],
            'password_again': bundle.data['passwordagain'],
            'email': bundle.data['email'],
            'first_name': bundle.data['firstname'],
            'last_name': bundle.data['lastname'],
        }
        rf = RegisterForm(data)
        if not rf.is_valid():
            str = ""
            for key, value in rf.errors.items():
                for error in value:
                    str += error + "\n"
            raise BadRequest(str)
        else:
            username = bundle.data['username']
            password = bundle.data['password']
            email = bundle.data['email']
            first_name = bundle.data['firstname']
            last_name = bundle.data['lastname']
        try:
            bundle.obj = User.objects.create_user(username, email, password)
            bundle.obj.first_name = first_name
            bundle.obj.last_name = last_name
            bundle.obj.save()

            user_profile = UserProfile()
            user_profile.user = bundle.obj
            if 'jobtitle' in bundle.data:
                user_profile.job_title = bundle.data['jobtitle']
            if 'organisation' in bundle.data:
                user_profile.organisation = bundle.data['organisation']
            if 'phoneno' in bundle.data:
                user_profile.phone_number = bundle.data['phoneno']
            user_profile.save()

            u = authenticate(username=username, password=password)
            if u is not None and u.is_active:
                login(bundle.request, u)
                # Add to tracker
                tracker = Tracker()
                tracker.user = u
                tracker.type = 'register'
                tracker.ip = bundle.request.META.get(
                    'REMOTE_ADDR', oppia.api.DEFAULT_IP_ADDRESS)
                tracker.agent = bundle.request.META.get(
                    'HTTP_USER_AGENT', 'unknown')
                tracker.save()
            key = ApiKey.objects.get(user=u)
            bundle.data['api_key'] = key.key
        except IntegrityError:
            raise BadRequest(
                _(u'Username "%s" already in use, please select another' %
                  username))
        del bundle.data['passwordagain']
        del bundle.data['password']
        del bundle.data['firstname']
        del bundle.data['lastname']
        return bundle
Ejemplo n.º 4
0
def home_view(request):

    activity = []
    leaderboard = None

    if request.user.is_authenticated:
        # create profile if none exists (historical for very old users)
        try:
            up = request.user.userprofile
        except UserProfile.DoesNotExist:
            up = UserProfile()
            up.user = request.user
            up.save()

        dashboard_accessed.send(sender=None, request=request, data=None)

        # if user is student redirect to their scorecard
        if up.is_student_only():
            return HttpResponseRedirect(reverse('profile_user_activity', args=[request.user.id]))

        # is user is teacher redirect to teacher home
        if up.is_teacher_only():
            return HttpResponseRedirect(reverse('oppia_teacher_home'))

        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = 'days'
        if request.method == 'POST':
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")
                start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
                interval = form.cleaned_data.get("interval")
        else:
            data = {}
            data['start_date'] = start_date
            data['end_date'] = end_date
            data['interval'] = interval
            form = DateRangeIntervalForm(initial=data)

        if interval == 'days':
            no_days = (end_date - start_date).days + 1
            tracker_stats = CourseDailyStats.objects.filter(day__gte=start_date, day__lte=end_date).values('day').annotate(count=Sum('total'))

            for i in range(0, no_days, +1):
                temp = start_date + datetime.timedelta(days=i)
                count = next((dct['count'] for dct in tracker_stats if dct['day'] == temp.date()), 0)
                activity.append([temp.strftime("%d %b %Y"), count])
        else:
            delta = relativedelta(months=+1)

            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                tmp_date += delta
                no_months += 1

            for i in range(0, no_months, +1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = CourseDailyStats.objects.filter(day__month=month, day__year=year).aggregate(total=Sum('total')).get('total', 0)
                activity.append([temp.strftime("%b %Y"), 0 if count is None else count])

        leaderboard = Points.get_leaderboard(10)

    else:
        form = None

    return render(request, 'oppia/home.html',
                              {'form': form,
                               'activity_graph_data': activity,
                               'leaderboard': leaderboard})
Ejemplo n.º 5
0
def edit(request, user_id=0):
    if user_id != 0:
        if can_edit_user(request, user_id):
            view_user = User.objects.get(pk=user_id)
        else:
            return HttpResponse('Unauthorized', status=401)
    else:
        view_user = request.user

    key = ApiKey.objects.get(user=view_user)
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        form.fields['location'].choices = get_location_choices()
        if form.is_valid():
            # update basic data
            email = form.cleaned_data.get("email")
            first_name = form.cleaned_data.get("first_name")
            last_name = form.cleaned_data.get("last_name")
            view_user.email = email
            view_user.first_name = first_name
            view_user.last_name = last_name
            view_user.save()

            try:
                facility = Facility.objects.get(
                    pk=form.cleaned_data.get("location"))
            except Facility.DoesNotExist:
                facility = None

            try:
                user_profile = UserProfile.objects.get(user=view_user)
                user_profile.job_title = form.cleaned_data.get("job_title")
                user_profile.organisation = form.cleaned_data.get(
                    "organisation")
                user_profile.profession = form.cleaned_data.get("profession")
                user_profile.service_entry_date = form.cleaned_data.get(
                    "service_entry_date")
                user_profile.location = facility
                user_profile.save()
            except UserProfile.DoesNotExist:
                user_profile = UserProfile()
                user_profile.user = view_user
                user_profile.job_title = form.cleaned_data.get("job_title")
                user_profile.organisation = form.cleaned_data.get(
                    "organisation")
                user_profile.profession = form.cleaned_data.get("profession")
                user_profile.service_entry_date = form.cleaned_data.get(
                    "service_entry_date")
                user_profile.location = facility
                user_profile.save()
            messages.success(request, _(u"Profile updated"))

            # if password should be changed
            password = form.cleaned_data.get("password")
            if password:
                view_user.set_password(password)
                view_user.save()
                messages.success(request, _(u"Password updated"))
    else:
        try:
            user_profile = UserProfile.objects.get(user=view_user)
        except UserProfile.DoesNotExist:
            user_profile = UserProfile()

        if user_profile.location is None:
            location = 0
        else:
            location = user_profile.location.id

        print location
        form = ProfileForm(
            initial={
                'username': view_user.username,
                'email': view_user.email,
                'first_name': view_user.first_name,
                'last_name': view_user.last_name,
                'api_key': key.key,
                'job_title': user_profile.job_title,
                'organisation': user_profile.organisation,
                'profession': user_profile.profession,
                'service_entry_date': user_profile.service_entry_date,
                'location': location,
            })
        form.fields['location'].choices = get_location_choices()

    return render_to_response('oppia/profile/profile.html', {
        'form': form,
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 6
0
def upload_view(request):
    if not request.user.is_staff:
        raise Http404

    if request.method == 'POST':  # if form submitted...
        form = UploadProfileForm(request.POST, request.FILES)
        if form.is_valid():
            request.FILES['upload_file'].open("rb")
            csv_file = csv.DictReader(request.FILES['upload_file'].file)
            required_fields = ['username', 'firstname', 'lastname', 'email']
            results = []
            try:
                for row in csv_file:
                    # check all required fields defined
                    all_defined = True
                    for rf in required_fields:
                        if rf not in row or row[rf].strip() == '':
                            result = {}
                            result['username'] = row['username']
                            result['created'] = False
                            result['message'] = _(u'No %s set' % rf)
                            results.append(result)
                            all_defined = False

                    if not all_defined:
                        continue

                    user = User()
                    user.username = row['username']
                    user.first_name = row['firstname']
                    user.last_name = row['lastname']
                    user.email = row['email']
                    auto_password = False
                    if 'password' in row:
                        user.set_password(row['password'])
                    else:
                        password = User.objects.make_random_password()
                        user.set_password(password)
                        auto_password = True
                    try:
                        user.save()
                        up = UserProfile()
                        up.user = user
                        for col_name in row:
                            setattr(up, col_name, row[col_name])
                        up.save()
                        result = {}
                        result['username'] = row['username']
                        result['created'] = True
                        if auto_password:
                            result['message'] = _(
                                u'User created with password: %s' % password)
                        else:
                            result['message'] = _(u'User created')
                        results.append(result)
                    except IntegrityError as ie:
                        result = {}
                        result['username'] = row['username']
                        result['created'] = False
                        result['message'] = _(u'User already exists')
                        results.append(result)
                        continue
            except:
                result = {}
                result['username'] = None
                result['created'] = False
                result['message'] = _(u'Could not parse file')
                results.append(result)

    else:
        results = []
        form = UploadProfileForm()

    return render_to_response(
        'oppia/profile/upload.html',
        {
            'form': form,
            'results': results
        },
        context_instance=RequestContext(request),
    )
Ejemplo n.º 7
0
def edit(request, user_id=0):
    if user_id != 0:
        if can_edit_user(request, user_id):
            view_user = User.objects.get(pk=user_id)
        else:
            raise exceptions.PermissionDenied
    else:
        view_user = request.user

    key = ApiKey.objects.get(user=view_user)
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        build_form_options(form)
        if form.is_valid():
            # update basic data
            email = form.cleaned_data.get("email")
            first_name = form.cleaned_data.get("first_name")
            last_name = form.cleaned_data.get("last_name")

            view_user.email = email
            view_user.first_name = first_name
            view_user.last_name = last_name
            view_user.save()
            
            try:
                user_profile = UserProfile.objects.get(user=view_user)
            except UserProfile.DoesNotExist:
                user_profile = UserProfile()
                user_profile.user = view_user
                
            user_profile.sex = form.cleaned_data.get("sex")
            user_profile.age_range =  form.cleaned_data.get("age_range")
            user_profile.role =  form.cleaned_data.get("role")
            user_profile.location = form.cleaned_data.get("location")
            user_profile.save()
            
            messages.success(request, _(u"Profile updated"))

            # if password should be changed
            password = form.cleaned_data.get("password")
            if password:
                view_user.set_password(password)
                view_user.save()
                messages.success(request, _(u"Password updated"))
    else:
        try:
            user_profile = UserProfile.objects.get(user=view_user)
        except UserProfile.DoesNotExist:
            user_profile = UserProfile()
            
        form = ProfileForm(initial={'username':view_user.username,
                                    'email':view_user.email,
                                    'first_name':view_user.first_name,
                                    'last_name':view_user.last_name,
                                    'sex': user_profile.sex,
                                    'age_range': user_profile.age_range,
                                    'role': user_profile.role,
                                    'location': user_profile.location, 
                                    'api_key': key.key})
        build_form_options(form)
        
    return render(request, 'oppia/profile/profile.html', {'form': form,})