예제 #1
0
def control_panel(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    note = _("You can accept trainees")
    now = timezone.now()
    data["user"] = request.user
    try:
        if UserProfileOPS.is_instructor(request.user.userprofile):
            courses = Course.objects.filter(site=data['site'], approved=True, trainer__user=request.user)
            if courses:
                log.info("egitmenin " + str(len(courses)) + " tane kursu var", extra=d)
                data['now'] = now
                data['dates'] = get_approve_start_end_dates_for_inst(data['site'], d)
                data['trainess'] = {}
                if data['dates']:
                    for course in courses:
                        if now <= data['dates'].get(1).end_date:
                            data['trainess'][course] = get_trainess_by_course(course, d)
                        else:
                            note = _("Consent period is closed")
                            data['trainess'][course] = get_approved_trainess(course, d)
                if "send" in request.POST:
                    log.info("kursiyer onay islemi basladi", extra=d)
                    log.info(request.POST, extra=d)
                    note = applytrainerselections(request.POST, courses, data, d)
            data['note'] = note
            return render_to_response("training/controlpanel.html", data, context_instance=RequestContext(request))
        elif not request.user.is_staff:
            return redirect("applytocourse")
        return redirect("statistic")
    except UserProfile.DoesNotExist:
        return redirect("createprofile")
예제 #2
0
def password_reset_key_done(request, key=None):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    form = ChangePasswordForm()
    note = _("Change your password")
    try:
        user_verification = UserVerification.objects.get(password_reset_key=key)
        user = user_verification.user
        user.is_authenticated = False
        user.save()
        request.user = user
    except Exception as e:
        note = _("""Password reset operation failed""")
        log.error(e.message, extra=d)
    if request.method == 'POST':
        form = ChangePasswordForm(request.POST)
        if form.is_valid():
            try:
                request.user.set_password(form.cleaned_data['password'])
                request.user.save()
                note = _("""Your password has been changed""")
                form = None
                redirect("index")
            except Exception as e:
                note = _("""Your password couldn't be changed""")
                log.error(e.message, extra=d)
    data['changepasswordform'] = form
    data['note'] = note
    data['user'] = request.user
    return render_to_response("userprofile/change_password.html", data, context_instance=RequestContext(request))
예제 #3
0
def list_courses(request):
    data = getsiteandmenus(request)
    courses = Course.objects.filter(site=data['site'])
    data['courses'] = courses
    return render_to_response('training/courses.html',
                              data,
                              context_instance=RequestContext(request))
예제 #4
0
def select_course_for_control_panel(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    note = "İşlem Yapmak İstediğiniz Kursu Seçiniz"
    data["user"] = request.user
    try:
        if UserProfileOPS.is_instructor(request.user.userprofile):
            courses = Course.objects.filter(site=data['site'],
                                            approved=True,
                                            trainer__user=request.user)
            if courses:
                log.info("egitmenin " + str(len(courses)) + " tane kursu var",
                         extra=d)
                data['courses'] = courses
            else:
                note = "Bu etkinlikte kursunuz yok."
            data['note'] = note
            return render_to_response("training/courselistforinst.html",
                                      data,
                                      context_instance=RequestContext(request))
        elif not request.user.is_staff:
            return redirect("applytocourse")
        return redirect("statistic")
    except UserProfile.DoesNotExist:
        return redirect("createprofile")
예제 #5
0
def addtrainess(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    now = datetime.date(datetime.now())
    if UserProfileOPS.is_authorized_inst(request.user.userprofile) and data['site'].event_start_date > now > data[
        'site'].application_end_date:
        data['form'] = AddTrainessForm(ruser=request.user)
        data['note'] = "Kursunuza eklemek istediğiniz katilimciyi seçin (E-posta adresine göre)"
        if "add" in request.POST:
            data['form'] = AddTrainessForm(request.POST, ruser=request.user)
            if data['form'].is_valid():
                tcourserecord = data['form'].save(commit=False)
                tcourserecord.preference_order = 1
                tcourserecord.trainess_approved = True
                tcourserecord.approved = True
                tcourserecord.save()
                notestr = "Bu kullanicinin %s kursu tercihi eğitmen tarafından eklendi." % tcourserecord.course.name
                note = TrainessNote(note=notestr, note_from_profile=request.user.userprofile,
                                    note_to_profile=tcourserecord.trainess,
                                    site=tcourserecord.course.site, note_date=timezone.now(), label="tercih")
                note.save()
                data['note'] = "Form kaydedildi. Eklediğiniz katılımcıları 1. tercih listesinde görüntüleyebilirsiniz."
                log.info("%s kullanicisi %s kullanicisini %s kursuna ekledi." % (
                    request.user.username, tcourserecord.trainess.user.username, tcourserecord.course.name), extra=d)
            else:
                data['note'] = "Form aşağıdaki sebeplerden dolayı kaydedilemedi."
        elif "cancel" in request.POST:
            return redirect("controlpanel")
        return render_to_response('training/addtrainess.html', data, context_instance=RequestContext(request))
    else:
        return redirect("controlpanel")
예제 #6
0
def password_reset_key(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    note = _("Please enter your registered email")
    if request.method == 'POST':
        email = request.POST['email']
        if email and email != "":
            try:
                user = User.objects.get(username=request.POST['email'])
                user_verification, created = UserVerification.objects.get_or_create(user=user)
                user_verification.password_reset_key = create_verification_link(user)
                user_verification.save()
                data['ruser'] = user
                data['activation_key'] = user_verification.password_reset_key
                domain = data['site'].home_url
                data['domain'] = domain.rstrip('/')
                data['recipientlist'] = [user.username]
                note = send_email_by_operation_name(data, "send_reset_password_key")
                if note:
                    note = "Parola sıfırlama e-postası adresinize gönderildi."
                else:
                    note = "E-posta gönderilemedi"
            except ObjectDoesNotExist:
                note = _("""There isn't any user record with this e-mail on the system""")
                log.error(note, extra=d)
            except Exception as e:
                note = _("""Password reset operation failed""")
                log.error(note, extra=d)
                log.error(e.message, extra=d)
        else:
            note = _("""Email field can not be empty""")
            log.error(note, extra=d)
    data['note'] = note
    return render_to_response("userprofile/change_password_key_request.html", data,
                              context_instance=RequestContext(request))
예제 #7
0
def alluserview(request):
    """
    Kabul edilen tüm kullanıcıların konaklama bilgileri
    :param request:
    :return:
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    userlist = []
    try:
        allcourserecord = TrainessCourseRecord.objects.filter(course__site__is_active=True).values_list(
            'trainess').order_by('trainess').distinct()
        if allcourserecord:

            for r in allcourserecord:
                up = UserProfile.objects.get(pk=r[0])
                usr = {
                    "pk": up.pk,
                    "firstname": up.user.first_name,
                    "email": up.user.username, "lastname": up.user.last_name,
                    "tcino": up.tckimlikno if up.tckimlikno != '' else up.ykimlikno,
                    "gender": up.gender,
                    "needs_document": up.needs_document,
                    "accomodation": up.useraccomodationpref_set.filter(accomodation__site__is_active=True),
                    "courserecordid": "0"}
                userlist.append(usr)
    except Exception as e:
        log.error("An error occured while showing alluserview", extra=d)
        log.error(e.message, extra=d)
    log.info("All user view showed", extra=d)
    data["datalist"] = userlist
    return render_to_response("userprofile/allusers.html", data, context_instance=RequestContext(request))
예제 #8
0
def subscribe(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    if not request.user.is_authenticated():
        data['buttonname1'] = "register"
        data['buttonname2'] = "cancel"
        data['buttonname1_value'] = _("Register")
        data['buttonname2_value'] = _("Cancel")
        note = _("Register to system to participate in courses before the conferences")
        form = CreateUserForm()
        if 'register' in request.POST:
            form = CreateUserForm(request.POST)
            if form.is_valid():
                try:
                    user = form.save(commit=True)
                    user.set_password(user.password)
                    try:
                        user.save()
                        note = _("Your account has been created. Please check your email for activation link")
                    except Exception as e:
                        note = e.message
                    form = None
                except Exception as e:
                    note = _("Your account couldn't create. Please try again!")
                    log.error(e.message, extra=d)
        elif 'cancel' in request.POST:
            return redirect("subscribe")
        data['createuserform'] = form
        data['note'] = note
        return render_to_response("userprofile/subscription.html", data, context_instance=RequestContext(request))
    else:
        return redirect("controlpanel")
예제 #9
0
def save_note(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    jsondata = {}
    if request.method == 'POST':
        trainess_username = request.POST['trainess_username']
        t_note = request.POST['note']
        if trainess_username and trainess_username != '':
            try:
                userprofile = UserProfile.objects.get(user__username=trainess_username)
                trainess_note = TrainessNote.objects.create(note_to_profile=userprofile, site=data['site'])
                trainess_note.label = "kurs"
                trainess_note.note = t_note
                trainess_note.note_from_profile = request.user.userprofile
                trainess_note.note_date = datetime.now()
                trainess_note.save()
                jsondata['status'] = "0"
                jsondata['message'] = "Durum güncellendi!"
            except Exception as e:
                jsondata['status'] = "-1"
                jsondata['message'] = "Durum güncelleme sırasında hata olustu"
                log.error(e.message, extra=d)
        else:
            jsondata['status'] = "-1"
            jsondata['message'] = "Hata: Kullanıcı adı boş olamaz!"
            log.error("username bos olamaz", extra=d)

    return HttpResponse(json.dumps(jsondata), content_type="application/json")
예제 #10
0
def show_course(request, course_id):
    try:
        data = getsiteandmenus(request)
        course = Course.objects.get(id=course_id)
        data['course'] = course
        return render_to_response('training/course_detail.html', data, context_instance=RequestContext(request))
    except ObjectDoesNotExist:
        return HttpResponse("Kurs Bulunamadi")
예제 #11
0
def allcourseprefview(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['datalist'] = TrainessCourseRecord.objects.filter(
        course__site=data['site'])
    return render_to_response("training/allcourseprefs.html",
                              data,
                              context_instance=RequestContext(request))
예제 #12
0
def showuserprofile(request, userid, courserecordid):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    if UserProfileOPS.is_instructor(request.user.userprofile) or request.user.is_staff:
        courserecord = None
        try:
            courserecord = TrainessCourseRecord.objects.get(pk=courserecordid,
                                                            trainess=UserProfile.objects.get(pk=userid))
            if not request.user.is_staff and request.user.userprofile not in courserecord.course.trainer.all() and \
                            request.user.userprofile not in courserecord.course.authorized_trainer.all():
                return redirect("controlpanel")
        except Exception as e:
            log.warning(e.message, extra=d)
            log.warning("Staff user show user profile", extra=d)
            if not request.user.is_staff:
                return redirect("controlpanel")
        user = UserProfile.objects.get(pk=userid)
        if user:
            data['note'] = "Detaylı kullanıcı bilgileri"
            data['tuser'] = user
            data['ruser'] = request.user
            if request.user.is_staff and "cancelall" in request.POST:
                cancelnote = request.POST.get('trainesscancelnotetext', '')
                res = cancel_all_prefs(user, cancelnote, data['site'], request.user, d)
                if res == 1:
                    data['note'] = "Kullanıcının Tüm Başvuruları Silindi"
                else:
                    data['note'] = "Kullanıcının Başvuruları silinirken hata oluştu"
            if courserecord:
                data['courseid'] = courserecord.course.pk
                if request.user.is_staff and courserecord.consentemailsent:
                    try:
                        data['forms'] = getparticipationforms(data['site'], courserecord)
                        if request.POST:
                            formsarevalid = []
                            frms = []
                            for f in data['forms']:
                                frm = ParticipationForm(request.POST,
                                                        prefix="participation" + str(
                                                            datetime.strptime(f.initial['day'], '%Y-%m-%d').day))
                                frm.courserecord = courserecord.pk
                                frm.day = f.initial['day']
                                formsarevalid.append(frm.is_valid())
                                frms.append(frm)
                            if all(formsarevalid):
                                for f in frms:
                                    f.save()
                                data['note'] = 'Seçimleriniz başarıyla kaydedildi.'
                                log.info("%s nolu kurs kaydinin yoklama kaydi girişi başarılı" % courserecord.pk, extra=d)
                            else:
                                data['note'] = 'Hata oluştu!'
                                log.info("%s nolu kurs kaydinin yoklama kaydi girişi hatalı" % courserecord.pk, extra=d)
                    except Exception as e:
                        log.error(e.message, extra=d)
        else:
            data['note'] = "Böyle Bir kullanıcı yoktur."
        return render_to_response("userprofile/showuserprofile.html", data, context_instance=RequestContext(request))
    return redirect("controlpanel")
예제 #13
0
def submitandregister(request):
    """
    Bu view'ı kullanmıyoruz. Egitmen ve egitim başvurularını sistemden aldığımızda kullanılabilir.
    :param request:
    :return:
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    userops = UserProfileOPS()
    data = getsiteandmenus(request)
    note = "Kurs onerisi olustur:"
    curinstprofform = InstProfileForm(prefix="cur")
    forms = {}
    for x in xrange(4):
        forms[x] = [CreateInstForm(prefix=str(x) + "inst"), InstProfileForm(prefix=str(x) + "instprof")]
    form = CreateCourseForm()
    if "submit" in request.POST:
        allf = []
        forms = {}
        for x in xrange(4):
            if str(x) + "inst-email" in request.POST:
                forms[x] = [CreateInstForm(request.POST, prefix=str(x) + "inst"),
                            InstProfileForm(request.POST, prefix=str(x) + "instprof")]
                allf.append(forms[x][0].is_valid())
                allf.append(forms[x][1].is_valid())
            else:
                pass
        curinstprofform = InstProfileForm(request.POST, prefix="cur")
        form = CreateCourseForm(request.POST)
        if all([curinstprofform.is_valid(), form.is_valid()]) and all(allf):
            curinst = curinstprofform.save(commit=False)
            curinst.user = request.user
            curinst.save()
            course = form.save(commit=False)
            if 'fulltext' in request.FILES:
                course.fulltext = request.FILES['fulltext']
            course.save()
            for key, f in forms.items():
                instx = f[0].save(commit=False)
                passwd = userops.generatenewpass(8)
                instx.set_password(passwd)
                instx.save()
                instxprof = f[1].save(commit=False)
                instxprof.user = instx
                instxprof.save()
                course.trainer.add(instxprof)
            course.trainer.add(curinst)
            course.save()
            note = "Egitim oneriniz basari ile alindi."
        else:
            note = "Olusturulamadi"
    data['note'] = note
    data['form'] = form
    data['curinstprofform'] = curinstprofform
    data['forms'] = forms
    return render_to_response("training/submitandregister.html",
                              data,
                              context_instance=RequestContext(request))
예제 #14
0
def participationstatuses(request):
    """
    Admin veya is_staff yetkisi verilmiş başka bir kullanıcı ile buraya view ile yoklama kaydı girilecek.
    :param request: HttpRequest
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['allcourses'] = Course.objects.filter(site=data['site'])
    data['note'] = "İşlem yapmak istediğiniz kursu seçiniz."
    return render_to_response('training/participationstatuses.html', data, context_instance=RequestContext(request))
예제 #15
0
def show_course(request, course_id):
    try:
        data = getsiteandmenus(request)
        course = Course.objects.get(id=course_id)
        data['course'] = course
        return render_to_response('training/course_detail.html',
                                  data,
                                  context_instance=RequestContext(request))
    except ObjectDoesNotExist:
        return HttpResponse("Kurs Bulunamadi")
예제 #16
0
def getaccomodations(request, usertype, gender):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    log.info("getaccomodation funtion call", extra=d)
    data = getsiteandmenus(request)
    jsondata = {}
    accomodations = Accommodation.objects.filter(
        usertype__in=[usertype, 'hepsi']).filter(
        gender__in=[gender, 'H']).filter(
        site=data['site']).values_list('id', 'name').order_by('name')
    for a in accomodations:
        jsondata[a[0]] = a[1]
    return HttpResponse(json.dumps(jsondata), content_type="application/json")
예제 #17
0
def get_all_trainers_view(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    try:
        trainers = []
        courses = Course.objects.filter(site__is_active=True)
        for course in courses:
            trainers.extend(course.trainer.all())
        data['trainers'] = set(trainers)
    except Exception as e:
        log.error(e.message, extra=d)
    return render_to_response("userprofile/alltrainess.html", data, context_instance=RequestContext(request))
예제 #18
0
def cancel_all_preference(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    hres = {'status': '-1', 'message': "Başvurularınız Silinirken Hata Oluştu"}
    if request.POST:
        cancelnote = request.POST.get('cancelnote', '')
        res = cancel_all_prefs(request.user.userprofile, cancelnote, data['site'], request.user, d)
        if res == 1:
            hres = {'status': '1', 'message': "Tüm Başvurularınız Silindi"}
        else:
            hres = {'status': '-1', 'message': "Başvurularınız silinirken hata oluştu"}
        log.debug(hres['message'], extra=d)
    return HttpResponse(json.dumps(hres), content_type="application/json")
예제 #19
0
def active_resend(request):
    data = getsiteandmenus(request)
    note = _("Please activate your account.  If you want to re-send an activation email, please click following button")
    if request.POST:
        domain = data['site'].home_url
        data['domain'] = domain.rstrip('/')
        user_verification, created = UserVerification.objects.get_or_create(user=request.user)
        user_verification.activation_key = create_verification_link(request.user)
        user_verification.save()
        data['activation_key'] = user_verification.activation_key
        data['recipientlist'] = [request.user.username]
        note = send_email_by_operation_name(data, "send_activation_key")
    data['note'] = note
    return render_to_response("userprofile/activate_resend.html", data, context_instance=RequestContext(request))
예제 #20
0
def participationstatuses(request):
    """
    Admin veya is_staff yetkisi verilmiş başka bir kullanıcı ile buraya view ile yoklama kaydı girilecek.
    :param request: HttpRequest
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['allcourses'] = Course.objects.filter(site=data['site'])
    data['daylist'] = list(
        daterange(data['site'].event_start_date, data['site'].event_end_date))
    data['note'] = "İşlem yapmak istediğiniz kursu seçiniz."
    return render_to_response('training/participationstatuses.html',
                              data,
                              context_instance=RequestContext(request))
예제 #21
0
def cancel_all_preference(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    hres = {'status': '-1', 'message': "Başvurularınız Silinirken Hata Oluştu"}
    if request.POST:
        cancelnote = request.POST.get('cancelnote', '')
        res = cancel_all_prefs(request.user.userprofile, cancelnote,
                               data['site'], request.user, d)
        if res == 1:
            hres = {'status': '1', 'message': "Tüm Başvurularınız Silindi"}
        else:
            hres = {
                'status': '-1',
                'message': "Başvurularınız silinirken hata oluştu"
            }
        log.debug(hres['message'], extra=d)
    return HttpResponse(json.dumps(hres), content_type="application/json")
예제 #22
0
def addtrainess(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    now = datetime.date(datetime.now())
    if UserProfileOPS.is_authorized_inst(request.user.userprofile) and data[
            'site'].event_start_date > now > data['site'].application_end_date:
        data['form'] = AddTrainessForm(ruser=request.user)
        data[
            'note'] = "Kursunuza eklemek istediğiniz katilimciyi seçin (E-posta adresine göre)"
        if "add" in request.POST:
            data['form'] = AddTrainessForm(request.POST, ruser=request.user)
            if data['form'].is_valid():
                tcourserecord = data['form'].save(commit=False)
                tcourserecord.preference_order = 1
                tcourserecord.trainess_approved = True
                tcourserecord.approved = True
                tcourserecord.save()
                notestr = "Bu kullanicinin %s kursu tercihi eğitmen tarafından eklendi." % tcourserecord.course.name
                note = TrainessNote(note=notestr,
                                    note_from_profile=request.user.userprofile,
                                    note_to_profile=tcourserecord.trainess,
                                    site=tcourserecord.course.site,
                                    note_date=timezone.now(),
                                    label="tercih")
                note.save()
                data[
                    'note'] = "Form kaydedildi. Eklediğiniz katılımcıları 1. tercih listesinde görüntüleyebilirsiniz."
                log.info("%s kullanicisi %s kullanicisini %s kursuna ekledi." %
                         (request.user.username,
                          tcourserecord.trainess.user.username,
                          tcourserecord.course.name),
                         extra=d)
            else:
                data[
                    'note'] = "Form aşağıdaki sebeplerden dolayı kaydedilemedi."
        elif "cancel" in request.POST:
            return redirect("selectcoursefcp")
        return render_to_response('training/addtrainess.html',
                                  data,
                                  context_instance=RequestContext(request))
    else:
        return redirect("selectcoursefcp")
예제 #23
0
def password_reset(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    form = ChangePasswordForm()
    note = _("Change your password")
    if request.method == 'POST':
        form = ChangePasswordForm(request.POST)
        if form.is_valid():
            try:
                request.user.set_password(form.cleaned_data['password'])
                request.user.save()
                backend_login(request, request.user)
                note = _("""Your password has been changed""")
                form = None
            except Exception as e:
                note = _("""Your password couldn't be changed""")
                log.error(e.message, extra=d)
    data['changepasswordform'] = form
    data['note'] = note
    return render_to_response("userprofile/change_password.html", data, context_instance=RequestContext(request))
예제 #24
0
def editparticipationstatusebycourse(request, courseid, date):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    courserecords = TrainessCourseRecord.objects.filter(
        course__pk=int(courseid), approved=True)
    data['courserecords'] = {}
    for courserecord in courserecords:
        data['courserecords'][courserecord] = getparticipationforms_by_date(
            courserecord, date)
    if request.POST:
        for courserecord in courserecords:
            morning = request.POST.get("participation" + str(courserecord.pk) +
                                       str(date) + "-morning")
            afternoon = request.POST.get("participation" +
                                         str(courserecord.pk) + str(date) +
                                         "-afternoon")
            evening = request.POST.get("participation" + str(courserecord.pk) +
                                       str(date) + "-evening")
            tp = TrainessParticipation.objects.filter(
                courserecord=courserecord, day=str(date)).first()
            if tp:
                tp.morning = morning
                tp.afternoon = afternoon
                tp.evening = evening
                tp.save()
            else:
                trainessp = TrainessParticipation(courserecord=courserecord,
                                                  day=str(date),
                                                  morning=morning,
                                                  afternoon=afternoon,
                                                  evening=evening)
                trainessp.save()
            data['courserecords'][
                courserecord] = getparticipationforms_by_date(
                    courserecord, date)
    data[
        'note'] = "Yoklama bilgilerini girmek için kullanıcı profiline gidiniz."
    data['date'] = date
    return render_to_response('training/courseparstatus.html',
                              data,
                              context_instance=RequestContext(request))
예제 #25
0
def testbeforeapply(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data[
        "note"] = "Kurs tercihi yapabilmek için aşağıdaki sorulara doğru yanıt vermelisiniz!"
    try:
        if not request.user.userprofile.userpassedtest:
            questions = Question.objects.filter(active=True,
                                                is_faq=True).order_by('no')
            if questions:
                data['questions'] = questions
                if request.POST:
                    userpasstest = True
                    wronganswers = ""
                    for q in questions:
                        uansw = request.POST.get(str(q.no))
                        if not uansw:
                            data['note'] = "Tüm sorulara cevap veriniz."
                            return render_to_response('abkayit/faqtest.html',
                                                      data)
                        ranswer = Answer.objects.get(pk=int(uansw))
                        if not ranswer.is_right:
                            log.info("yanlis cevap: %s" % q.no, extra=d)
                            wronganswers += "%s " % q.no
                            userpasstest = False
                    if userpasstest:
                        request.user.userprofile.userpassedtest = True
                        request.user.userprofile.save()
                        return redirect("applytocourse")
                    else:
                        data[
                            "note"] = "Tüm sorulara doğru cevap veriniz yanlış cevaplar %s" % wronganswers
                return render_to_response('abkayit/faqtest.html', data)
            else:
                request.user.userprofile.userpassedtest = True
                request.user.userprofile.save()
        return redirect("applytocourse")
    except ObjectDoesNotExist:
        return redirect('createprofile')
예제 #26
0
def allapprovedprefsview(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['datalist'] = TrainessCourseRecord.objects.filter(
        course__site=data['site'], approved=True)
    data['participations'] = {}
    for tcr in data['datalist']:
        tprs = TrainessParticipation.objects.filter(
            courserecord=tcr
        )  # Bir katilimcinin bu tercihi icin yoklama kayitlari
        if tprs:
            totalparticipation, totalcoursehour = calculate_participations(
                tprs, data['site'])
            data['participations'][
                tcr] = "%s saatlik kursun %s lik kısmına katildi" % (
                    totalcoursehour, totalparticipation)
        else:
            data['participations'][tcr] = "Bu kisinin yoklama kaydi yok"

    return render_to_response("training/allapprovedprefs.html",
                              data,
                              context_instance=RequestContext(request))
예제 #27
0
def index(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    content = None
    data['state'] = ""
    if not request.user.is_authenticated():
        data['alerttype'] = "alert-info"
        data['state'] = _(
            "If you already have an account, please login from top right hand side of the page"
        )
        if request.POST:
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                log.info("%s user successfuly logged in" % request.user,
                         extra=d)
                return HttpResponseRedirect('/')
            else:
                data['state'] = _("Login Failed!")
                data['alerttype'] = "alert-danger"
    try:
        if not request.GET.get('menu_id'):
            menu_id = Menu.objects.filter(
                site=data['site']).order_by('order').first()
        else:
            menu_id = request.GET.get('menu_id')
        content = Content.objects.get(menu=menu_id)
    except ObjectDoesNotExist:
        content = None
        log.error("%s entered content not found " % request.user, extra=d)
    except Exception as e:
        log.error("%s error occured %s " % (request.user, e.message), extra=d)
    data['content'] = content
    return render_to_response('dashboard.html', data)
예제 #28
0
def instructor_information(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    if not request.user.userprofile:
        log.error("Kullanıcı Profili Bulunamadı", extra=d)
        return redirect("createprofile")
    data = getsiteandmenus(request)
    if not UserProfileOPS.is_instructor(request.user.userprofile):
        note = _("You are not authorized to access here")
    else:
        note = _("Please enter your transformation, arrival date, departure date information")
        instructorinformation = None
        try:
            instructorinformation = InstructorInformation.objects.get(user=request.user.userprofile)
            form = InstructorInformationForm(instance=instructor_information)
        except Exception as e:
            log.debug("Egitmen bilgileri bulunamadi, yeni bilgiler olusturulmak icin form acilacak", extra=d)
            log.error(e.message, extra=d)
            form = InstructorInformationForm()
        if request.POST:
            if instructorinformation:
                form = InstructorInformationForm(request.POST, instance=instructorinformation)
            else:
                form = InstructorInformationForm(request.POST)
            if form.is_valid():
                try:
                    form.instance.user = request.user.userprofile
                    instructor_info = form.save(commit=True)
                    instructor_info.user = request.user.userprofile
                    instructor_info.save()
                    note = _("Your information saved successfully")
                except Exception as e:
                    note = _("An error occurred while saving your information")
                    log.error(e.message, extra=d)
        data['form'] = form
    data['note'] = note
    return render_to_response("userprofile/instructor_information.html", data, context_instance=RequestContext(request))
예제 #29
0
def control_panel(request, courseid):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['note'] = _("You can accept trainees")
    now = timezone.now()
    data["user"] = request.user
    try:
        course = Course.objects.get(pk=courseid)
        data['now'] = now
        data['dates'] = get_approve_start_end_dates_for_inst(data['site'], d)
        data['trainess'] = {}
        data['notesavedsuccessful'] = False
        if data['dates']:
            if now <= data['dates'].get(1).end_date:
                data['trainess'][course] = get_trainess_by_course(course, d)
            else:
                data['note'] = _("Consent period is closed")
                data['trainess'][course] = get_approved_trainess(course, d)
        if request.user.userprofile in course.authorized_trainer.all():
            log.info("Kullanıcı %s kursunda degisiklik yapiyor" % course.name,
                     extra=d)
            if "send" in request.POST:
                log.info("kursiyer onay islemi basladi", extra=d)
                log.info(request.POST, extra=d)
                data['note'] = applytrainerselections(request.POST, course,
                                                      data, d)
            return render_to_response("training/controlpanel.html",
                                      data,
                                      context_instance=RequestContext(request))
        elif request.user.userprofile in course.trainer.all():
            data['note'] = "Kursiyerler için not ekleyebilirsiniz."
            if "savescore" in request.POST:
                trainessnote = request.POST.get('trainessnotetext')
                trainessusername = request.POST.get('trainessnoteuser')
                user = User.objects.get(username=trainessusername)
                potentialinst = request.POST.get('potential-%s' % user.pk)
                if trainessnote:
                    tnote = TrainessNote(
                        note_to_profile=user.userprofile,
                        note_from_profile=request.user.userprofile,
                        note=trainessnote,
                        site=data['site'],
                        label='egitim')
                    tnote.save()
                uprobysite, created = UserProfileBySite.objects.get_or_create(
                    user=user, site=data['site'])
                if potentialinst == 'on':
                    uprobysite.potentialinstructor = True
                else:
                    uprobysite.potentialinstructor = False
                uprobysite.save()
                data['savednoteuserid'] = user.userprofile.pk
                data['notesavedsuccessful'] = True
                data['note'] = "Kursiyer notu başarıyla kaydedildi."
            return render_to_response(
                "training/controlpanelforunauthinst.html",
                data,
                context_instance=RequestContext(request))
        elif not request.user.is_staff:
            return redirect("applytocourse")
        return redirect("statistic")
    except UserProfile.DoesNotExist:
        return redirect("createprofile")
예제 #30
0
def approve_course_preference(request):
    """
    Bu view katilimci bir kursa kabul edilip edilmedigini görüntülemesi ve katilimcidan katılıp katılmayacağına dair
    son bir teyit alınır.
    :param request: HttpRequest
    :return:
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    message = ""
    status = "1"
    data = getsiteandmenus(request)
    data["note"] = "Başvuru Durumunuz"
    now = datetime.now()
    try:

        data["approve_is_open"] = False
        trainess_course_records = TrainessCourseRecord.objects.filter(trainess=request.user.userprofile,
                                                                      course__site__is_active=True)
        first_start_date_inst, last_end_date_inst = get_approve_first_start_last_end_dates_for_inst(data['site'], d)
        if not trainess_course_records:
            data['note'] = "Henüz herhangi bir kursa başvuru yapmadınız!"
        elif data['site'].application_start_date <= datetime.date(now) < data['site'].application_end_date:
            data['note'] = "Başvurunuz için teşekkürler. Değerlendirme sürecinin başlaması için " \
                           "tüm başvuruların tamamlanması beklenmektedir."
        else:
            recordapprovedbyinst = TrainessCourseRecord.objects.filter(trainess=request.user.userprofile, approved=True,
                                                                       consentemailsent=True,
                                                                       course__site__is_active=True)
            if not recordapprovedbyinst:
                
                if first_start_date_inst.start_date <= now < last_end_date_inst.end_date:
                    data['note'] = "Başvurular değerlendirilmektedir. En geç %s tarihine kadar sonuçları burada" \
                                   " görebilirsiniz." % last_end_date_inst.end_date.strftime("%d-%m-%Y")
                elif data['site'].event_start_date - 1 > now > last_end_date_inst.end_date:
                    data['note'] = "Kurslara kabul dönemi bitmiş olup başvurularınıza kabul edilmediniz ancak" \
                                   " kurs başlangıç tarihine kadar kabul edilme şansınız hala devam ediyor." \
                                   " Takip etmeye devam edin."
                elif data['site'].event_start_date - 1 <= now:
                    data['note'] = "Başvurularınız kabul edilmemiştir. Bir sonraki etkinlikte görüşmek dileğiyle."
            else:
                data["note"] = "Aşağıdaki Kursa Kabul Edildiniz"
                data['trainess_course_record'] = recordapprovedbyinst[0]
                if REQUIRE_TRAINESS_APPROVE:
                    recordapprovedbytra = recordapprovedbyinst.filter(trainess_approved=True)
                    if not recordapprovedbytra:
                        tra_approvaldate = ApprovalDate.objects.get(site__is_active=True, for_trainess=True,
                                                                    preference_order=recordapprovedbyinst[
                                                                        0].preference_order)
                        if tra_approvaldate.start_date <= now <= tra_approvaldate.end_date:
                            data['note'] = "Aşağıdaki kursa kabul edildiniz"
                            data["approve_is_open"] = True
                        else:
                            data[
                                "note"] = "Aşağıdaki kursa kabul edildiniz ancak teyit etmediniz. Kursa katılamazsınız."
                            data["approve_is_open"] = False
    except Exception as e:
        log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=d)
        log.error(e.message, extra=d)
        data['note'] = "Hata oluştu"
    if request.POST:
        try:
            log.debug(request.POST.get("courseRecordId"), extra=d)
            if request.POST.get("courseRecordId") and data['trainess_course_record']:
                data['trainess_course_record'].trainess_approved = True
                data['trainess_course_record'].save()
                message = "İşleminiz başarılı bir şekilde gerçekleştirildi"
                status = "0"
                log.debug("kursu onayladi " + data['trainess_course_record'].course.name, extra=d)
        except Exception as e:
            log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=d)
            log.error(e.message, extra=d)
            message = "İşleminiz Sırasında Hata Oluştu"
            status = "-1"
        return HttpResponse(json.dumps({'status': status, 'message': message}), content_type="application/json")
    return render_to_response("training/confirm_course_preference.html", data)
예제 #31
0
def submitandregister(request):
    """
    Bu view'ı kullanmıyoruz. Egitmen ve egitim başvurularını sistemden aldığımızda kullanılabilir.
    :param request:
    :return:
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    userops = UserProfileOPS()
    data = getsiteandmenus(request)
    note = "Kurs onerisi olustur:"
    curinstprofform = InstProfileForm(prefix="cur")
    forms = {}
    for x in xrange(4):
        forms[x] = [
            CreateInstForm(prefix=str(x) + "inst"),
            InstProfileForm(prefix=str(x) + "instprof")
        ]
    form = CreateCourseForm()
    if "submit" in request.POST:
        allf = []
        forms = {}
        for x in xrange(4):
            if str(x) + "inst-email" in request.POST:
                forms[x] = [
                    CreateInstForm(request.POST, prefix=str(x) + "inst"),
                    InstProfileForm(request.POST, prefix=str(x) + "instprof")
                ]
                allf.append(forms[x][0].is_valid())
                allf.append(forms[x][1].is_valid())
            else:
                pass
        curinstprofform = InstProfileForm(request.POST, prefix="cur")
        form = CreateCourseForm(request.POST)
        if all([curinstprofform.is_valid(), form.is_valid()]) and all(allf):
            curinst = curinstprofform.save(commit=False)
            curinst.user = request.user
            curinst.save()
            course = form.save(commit=False)
            if 'fulltext' in request.FILES:
                course.fulltext = request.FILES['fulltext']
            course.save()
            for key, f in forms.items():
                instx = f[0].save(commit=False)
                passwd = userops.generatenewpass(8)
                instx.set_password(passwd)
                instx.save()
                instxprof = f[1].save(commit=False)
                instxprof.user = instx
                instxprof.save()
                course.trainer.add(instxprof)
            course.trainer.add(curinst)
            course.save()
            note = "Egitim oneriniz basari ile alindi."
        else:
            note = "Olusturulamadi"
    data['note'] = note
    data['form'] = form
    data['curinstprofform'] = curinstprofform
    data['forms'] = forms
    return render_to_response("training/submitandregister.html",
                              data,
                              context_instance=RequestContext(request))
예제 #32
0
def approve_course_preference(request):
    """
    Bu view katilimci bir kursa kabul edilip edilmedigini görüntülemesi ve katilimcidan katılıp katılmayacağına dair
    son bir teyit alınır.
    :param request: HttpRequest
    :return:
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    message = ""
    status = "1"
    data = getsiteandmenus(request)
    data["note"] = "Başvuru Durumunuz"
    now = datetime.now()
    try:

        data["approve_is_open"] = False
        trainess_course_records = TrainessCourseRecord.objects.filter(
            trainess=request.user.userprofile, course__site__is_active=True)
        first_start_date_inst, last_end_date_inst = get_approve_first_start_last_end_dates_for_inst(
            data['site'], d)
        if not trainess_course_records:
            data['note'] = "Henüz herhangi bir kursa başvuru yapmadınız!"
        elif data['site'].application_start_date <= datetime.date(
                now) < data['site'].application_end_date:
            data['note'] = "Başvurunuz için teşekkürler. Değerlendirme sürecinin başlaması için " \
                           "tüm başvuruların tamamlanması beklenmektedir."
        else:
            recordapprovedbyinst = TrainessCourseRecord.objects.filter(
                trainess=request.user.userprofile,
                approved=True,
                consentemailsent=True,
                course__site__is_active=True)
            if not recordapprovedbyinst:

                if first_start_date_inst.start_date <= now < last_end_date_inst.end_date:
                    data['note'] = "Başvurular değerlendirilmektedir. En geç %s tarihine kadar sonuçları burada" \
                                   " görebilirsiniz." % last_end_date_inst.end_date.strftime("%d-%m-%Y")
                elif data[
                        'site'].event_start_date - 1 > now > last_end_date_inst.end_date:
                    data['note'] = "Kurslara kabul dönemi bitmiş olup başvurularınıza kabul edilmediniz ancak" \
                                   " kurs başlangıç tarihine kadar kabul edilme şansınız hala devam ediyor." \
                                   " Takip etmeye devam edin."
                elif data['site'].event_start_date - 1 <= now:
                    data[
                        'note'] = "Başvurularınız kabul edilmemiştir. Bir sonraki etkinlikte görüşmek dileğiyle."
            else:
                data["note"] = "Aşağıdaki Kursa Kabul Edildiniz"
                data['trainess_course_record'] = recordapprovedbyinst[0]
                if REQUIRE_TRAINESS_APPROVE:
                    recordapprovedbytra = recordapprovedbyinst.filter(
                        trainess_approved=True)
                    if not recordapprovedbytra:
                        tra_approvaldate = ApprovalDate.objects.get(
                            site__is_active=True,
                            for_trainess=True,
                            preference_order=recordapprovedbyinst[0].
                            preference_order)
                        if tra_approvaldate.start_date <= now <= tra_approvaldate.end_date:
                            data['note'] = "Aşağıdaki kursa kabul edildiniz"
                            data["approve_is_open"] = True
                        else:
                            data[
                                "note"] = "Aşağıdaki kursa kabul edildiniz ancak teyit etmediniz. Kursa katılamazsınız."
                            data["approve_is_open"] = False
    except Exception as e:
        log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
                  extra=d)
        log.error(e.message, extra=d)
        data['note'] = "Hata oluştu"
    if request.POST:
        try:
            log.debug(request.POST.get("courseRecordId"), extra=d)
            if request.POST.get(
                    "courseRecordId") and data['trainess_course_record']:
                data['trainess_course_record'].trainess_approved = True
                data['trainess_course_record'].save()
                message = "İşleminiz başarılı bir şekilde gerçekleştirildi"
                status = "0"
                log.debug("kursu onayladi " +
                          data['trainess_course_record'].course.name,
                          extra=d)
        except Exception as e:
            log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
                      extra=d)
            log.error(e.message, extra=d)
            message = "İşleminiz Sırasında Hata Oluştu"
            status = "-1"
        return HttpResponse(json.dumps({
            'status': status,
            'message': message
        }),
                            content_type="application/json")
    return render_to_response("training/confirm_course_preference.html", data)
예제 #33
0
def statistic(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    try:
        data = getsiteandmenus(request)

        record_data = TrainessCourseRecord.objects.filter(
            course__site__is_active=True).values(
                'course', 'preference_order').annotate(
                    Count('preference_order')).order_by(
                        'course', '-preference_order')
        statistic_by_course = {}
        for key, group in itertools.groupby(record_data,
                                            lambda item: item["course"]):
            course_object = Course.objects.get(pk=key, site__is_active=True)
            statistic_by_course[course_object] = {
                str(item['preference_order']): item['preference_order__count']
                for item in group
            }
            statistic_by_course[course_object]['total_apply'] = len(
                TrainessCourseRecord.objects.filter(course=course_object))
            statistic_by_course[course_object]['total_apply_by_trainer'] = len(
                TrainessCourseRecord.objects.filter(course=course_object,
                                                    approved=True))
            statistic_by_course[course_object]['applicationbywomen'] = len(
                TrainessCourseRecord.objects.filter(
                    course=course_object, trainess__gender="K").order_by(
                        "trainess").values_list("trainess").distinct())
            statistic_by_course[course_object]['applicationbymen'] = len(
                TrainessCourseRecord.objects.filter(
                    course=course_object, trainess__gender="E").order_by(
                        "trainess").values_list("trainess").distinct())
        data['statistic_by_course'] = statistic_by_course

        data['statistic_by_gender_k'] = len(
            TrainessCourseRecord.objects.filter(
                course__site__is_active=True, trainess__gender="K").order_by(
                    "trainess").values_list("trainess").distinct())
        data['statistic_by_gender_e'] = len(
            TrainessCourseRecord.objects.filter(
                course__site__is_active=True, trainess__gender="E").order_by(
                    "trainess").values_list("trainess").distinct())
        data['statistic_by_gender_k_approved'] = len(
            TrainessCourseRecord.objects.filter(
                course__site__is_active=True,
                trainess__gender="K",
                approved=True).order_by("trainess").values_list(
                    "trainess").distinct())
        data['statistic_by_gender_e_approved'] = len(
            TrainessCourseRecord.objects.filter(
                course__site__is_active=True,
                trainess__gender="E",
                approved=True).order_by("trainess").values_list(
                    "trainess").distinct())
        data['statistic_by_university_for_approved'] = []
        data['statistic_by_university'] = []
        for university in UNIVERSITIES:
            data['statistic_by_university'].append(
                (university[0],
                 len(
                     TrainessCourseRecord.objects.filter(
                         course__site__is_active=True,
                         trainess__university__contains=university[0]).
                     order_by("trainess").values_list("trainess").distinct())))
            data['statistic_by_university_for_approved'].append(
                (university[0],
                 len(
                     TrainessCourseRecord.objects.filter(
                         course__site__is_active=True,
                         trainess__university__contains=university[0],
                         approved=True).order_by("trainess").values_list(
                             "trainess").distinct())))
            # data['statistic_by_university'] = sorted(data['statistic_by_university'], key=lambda x: (x[1], x[1]),
        # reverse=True)

        # data['statistic_by_university_for_approved'] = sorted(data['statistic_by_university_for_approved'],
        #                                                      key=lambda x: (x[1], x[1]),
        #                                                      reverse=True)

        # kurs bazinda toplam teyitli olanlar
        total_profile = len(
            TrainessCourseRecord.objects.filter(course__site__is_active=True).
            order_by("trainess").values("trainess").distinct())
        total_preference = len(
            TrainessCourseRecord.objects.filter(course__site__is_active=True))
        data['statistic_by_totalsize'] = {
            'Toplam Profil(Kişi)': total_profile,
            'Toplam Tercih': total_preference
        }
    except Exception as e:
        log.error(e.message, extra=d)
    return render_to_response("training/statistic.html", data)
예제 #34
0
def apply_to_course(request):
    """
    controlpanel view'ında userprofile ogrenci ise buraya yonleniyor
    tercih zamanı ve ek tercih zamanı burada gorunuyor.
    :param request:
    :return: kullanıcı tercih zamanı eğer sıkca sorulan sorulara doğru yanıt vermisse PREFERENCE_LIMIT kadar tercih yapar
      eger profili yoksa createprofile yönlendirilir
      eger sıkca sorulan sorulara cevap vermemisse sıkca sorulan sorulara yonlendirilir.
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['closed'] = True
    data['additional1_pref_closed'] = True
    data['PREFERENCE_LIMIT'] = PREFERENCE_LIMIT
    data['ADDITION_PREFERENCE_LIMIT'] = ADDITION_PREFERENCE_LIMIT
    now = datetime.now()
    data['may_cancel_all'] = True if data['site'].event_start_date > datetime.date(now) else False
    """
    courses: mevcut etkinte onaylanmis ve basvuruya acik kurslar
    """
    data['courses'] = Course.objects.filter(approved=True, site=data['site'], application_is_open=True)
    """
    course_records: katilimcinin, mevcut etkinlikteki tercihleri
    """
    data['course_records'] = TrainessCourseRecord.objects.filter(trainess__user=request.user,
                                                                 course__site__is_active=True).order_by(
        'preference_order')
    userprofile = request.user.userprofile
    if not userprofile:
        log.info("userprofile not found", extra=d)
        return redirect("createprofile")
    if data['courses']:
        if data['site'].application_start_date <= datetime.date(now) <= data['site'].application_end_date:
            log.info("in between application start and end date", extra=d)
            if userprofile.userpassedtest:
                data['closed'] = False
                note = _("You can choose courses in order of preference.")
                if request.GET:
                    course_prefs = request.GET
                    pref_tests = gettestsofcourses(course_prefs)
                    if pref_tests:
                        data['note'] = "Lutfen asağidaki soruları yanıtlayın"
                        data['pref_tests'] = pref_tests
                        if "submitanswers" in request.POST:
                            answersforcourse = {}
                            for course, questions in pref_tests.items():
                                answersforcourse[course] = []
                                for question in questions[0]:
                                    uansw = request.POST.get(str(course.pk) + str(question.no))
                                    ranswer = Answer.objects.get(pk=int(uansw))
                                    if ranswer:
                                        answersforcourse[course].append(ranswer)
                                    else:
                                        data["note"] = "Lütfen tüm soruları doldurun!"
                                        return render_to_response("training/testforapplication.html", data,
                                                                  context_instance=RequestContext(request))
                                for question in questions[1]:
                                    tbansw = request.POST.get("answer" + str(question.pk))
                                    if tbansw:
                                        tcta, created = TrainessClassicTestAnswers.objects.get_or_create(
                                            user=request.user.userprofile, question=question)
                                        tcta.answer = tbansw
                                        tcta.save()
                            res = save_course_prefferences(userprofile, course_prefs, data['site'], d,
                                                           answersforcourse=answersforcourse)
                            data['note'] = res['message']
                            return render_to_response("training/applytocourse.html", data,
                                                      context_instance=RequestContext(request))
                        return render_to_response("training/testforapplication.html", data,
                                                  context_instance=RequestContext(request))
                    else:
                        res = save_course_prefferences(userprofile, course_prefs, data['site'], d)
                        data['note'] = res['message']
                    data['note'] = res['message']
                    return render_to_response("training/applytocourse.html", data,
                                              context_instance=RequestContext(request))
                data['note'] = note
            else:
                return redirect("testbeforeapply")
        elif datetime.date(now) < data['site'].application_start_date:
            log.info("before application start date", extra=d)
            data['note'] = "Tercih dönemi %s tarihinde açılacaktır" % data['site'].application_start_date
        elif datetime.date(now) > data['site'].application_end_date:
            log.info("after application end date", extra=d)
            data[
                'note'] = "Tercih dönemi %s tarihinde kapanmıştır. Başvuru durumunuzu İşlemler> Başvuru Durum/Onayla " \
                          "adımından görüntüleyebilirsiniz " % data['site'].application_end_date
            """
             Bu kod parcasi ek tercihler icindir. Eger kullanıcının kabul ettigi ve edildigi bir kurs yoksa ve
             ek tercih aktifse bu kod blogu calisir.
            """
            if ADDITION_PREFERENCE_LIMIT:
                adates = get_additional_pref_start_end_dates_for_trainess(data['site'], d)
                if adates:
                    for adate in adates:
                        if adates[adate].start_date <= now <= adates[adate].end_date:
                            if is_trainess_approved_any_course(userprofile, data['site'], d):
                                data['additional1_pref_closed'] = False
                                log.info("ek tercih aktif", extra=d)
                                data['note'] = _("You can make additional preference.")
    else:
        data['note'] = _("There isn't any course in this event.")
    return render_to_response('training/applytocourse.html', data)
예제 #35
0
def list_courses(request):
    data = getsiteandmenus(request)
    courses = Course.objects.filter(site=data['site'])
    data['courses'] = courses
    return render_to_response('training/courses.html', data, context_instance=RequestContext(request))
예제 #36
0
def testforapplication(request):
    data = getsiteandmenus(request)

    return render_to_response("testforapplication.html", data, context_instance=RequestContext(request))
예제 #37
0
def editparticipationstatusebycourse(request, courseid):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['courserecords'] = TrainessCourseRecord.objects.filter(course__pk=int(courseid), approved=True)
    data['note'] = "Yoklama bilgilerini girmek için kullanıcı profiline gidiniz."
    return render_to_response('training/courseparstatus.html', data, context_instance=RequestContext(request))
예제 #38
0
def apply_to_course(request):
    """
    controlpanel view'ında userprofile ogrenci ise buraya yonleniyor
    tercih zamanı ve ek tercih zamanı burada gorunuyor.
    :param request:
    :return: kullanıcı tercih zamanı eğer sıkca sorulan sorulara doğru yanıt vermisse PREFERENCE_LIMIT kadar tercih yapar
      eger profili yoksa createprofile yönlendirilir
      eger sıkca sorulan sorulara cevap vermemisse sıkca sorulan sorulara yonlendirilir.
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['closed'] = True
    data['additional1_pref_closed'] = True
    data['PREFERENCE_LIMIT'] = PREFERENCE_LIMIT
    data['ADDITION_PREFERENCE_LIMIT'] = ADDITION_PREFERENCE_LIMIT
    now = datetime.now()
    data['may_cancel_all'] = True if data[
        'site'].event_start_date > datetime.date(now) else False
    """
    courses: mevcut etkinte onaylanmis ve basvuruya acik kurslar
    """
    data['courses'] = Course.objects.filter(approved=True,
                                            site=data['site'],
                                            application_is_open=True)
    """
    course_records: katilimcinin, mevcut etkinlikteki tercihleri
    """
    data['course_records'] = TrainessCourseRecord.objects.filter(
        trainess__user=request.user,
        course__site__is_active=True).order_by('preference_order')
    userprofile = request.user.userprofile
    if not userprofile:
        log.info("userprofile not found", extra=d)
        return redirect("createprofile")
    if data['courses']:
        if data['site'].application_start_date <= datetime.date(
                now) <= data['site'].application_end_date:
            log.info("in between application start and end date", extra=d)
            if userprofile.userpassedtest:
                data['closed'] = False
                note = _("You can choose courses in order of preference.")
                if request.GET:
                    course_prefs = request.GET
                    pref_tests = gettestsofcourses(course_prefs)
                    if pref_tests:
                        data['note'] = "Lutfen asağidaki soruları yanıtlayın"
                        data['pref_tests'] = pref_tests
                        if "submitanswers" in request.POST:
                            answersforcourse = {}
                            for course, questions in pref_tests.items():
                                answersforcourse[course] = []
                                for question in questions[0]:
                                    uansw = request.POST.get(
                                        str(course.pk) + str(question.no))
                                    ranswer = Answer.objects.get(pk=int(uansw))
                                    if ranswer:
                                        answersforcourse[course].append(
                                            ranswer)
                                    else:
                                        data[
                                            "note"] = "Lütfen tüm soruları doldurun!"
                                        return render_to_response(
                                            "training/testforapplication.html",
                                            data,
                                            context_instance=RequestContext(
                                                request))
                                for question in questions[1]:
                                    tbansw = request.POST.get("answer" +
                                                              str(question.pk))
                                    if tbansw:
                                        tcta, created = TrainessClassicTestAnswers.objects.get_or_create(
                                            user=request.user.userprofile,
                                            question=question)
                                        tcta.answer = tbansw
                                        tcta.save()
                            res = save_course_prefferences(
                                userprofile,
                                course_prefs,
                                data['site'],
                                d,
                                answersforcourse=answersforcourse)
                            data['note'] = res['message']
                            return render_to_response(
                                "training/applytocourse.html",
                                data,
                                context_instance=RequestContext(request))
                        return render_to_response(
                            "training/testforapplication.html",
                            data,
                            context_instance=RequestContext(request))
                    else:
                        res = save_course_prefferences(userprofile,
                                                       course_prefs,
                                                       data['site'], d)
                        data['note'] = res['message']
                    data['note'] = res['message']
                    return render_to_response(
                        "training/applytocourse.html",
                        data,
                        context_instance=RequestContext(request))
                data['note'] = note
            else:
                return redirect("testbeforeapply")
        elif datetime.date(now) < data['site'].application_start_date:
            log.info("before application start date", extra=d)
            data['note'] = "Tercih dönemi %s tarihinde açılacaktır" % data[
                'site'].application_start_date
        elif datetime.date(now) > data['site'].application_end_date:
            log.info("after application end date", extra=d)
            data[
                'note'] = "Tercih dönemi %s tarihinde kapanmıştır. Başvuru durumunuzu İşlemler> Başvuru Durum/Onayla " \
                          "adımından görüntüleyebilirsiniz " % data['site'].application_end_date
            """
             Bu kod parcasi ek tercihler icindir. Eger kullanıcının kabul ettigi ve edildigi bir kurs yoksa ve
             ek tercih aktifse bu kod blogu calisir.
            """
            if ADDITION_PREFERENCE_LIMIT:
                adates = get_additional_pref_start_end_dates_for_trainess(
                    data['site'], d)
                if adates:
                    for adate in adates:
                        if adates[adate].start_date <= now <= adates[
                                adate].end_date:
                            if is_trainess_approved_any_course(
                                    userprofile, data['site'], d):
                                data['additional1_pref_closed'] = False
                                log.info("ek tercih aktif", extra=d)
                                data['note'] = _(
                                    "You can make additional preference.")
    else:
        data['note'] = _("There isn't any course in this event.")
    return render_to_response('training/applytocourse.html', data)
예제 #39
0
def allcourseprefview(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    data['datalist'] = TrainessCourseRecord.objects.filter(course__site=data['site'])
    return render_to_response("training/allcourseprefs.html", data, context_instance=RequestContext(request))
예제 #40
0
def statistic(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    try:
        data = getsiteandmenus(request)

        record_data = TrainessCourseRecord.objects.filter(course__site__is_active=True).values(
            'course', 'preference_order').annotate(
            Count('preference_order')).order_by(
            'course', '-preference_order')
        statistic_by_course = {}
        for key, group in itertools.groupby(record_data, lambda item: item["course"]):
            course_object = Course.objects.get(pk=key, site__is_active=True)
            statistic_by_course[course_object] = {str(item['preference_order']): item['preference_order__count'] for
                                                  item in group}
            statistic_by_course[course_object]['total_apply'] = len(TrainessCourseRecord.objects.filter(
                course=course_object))
            statistic_by_course[course_object]['total_apply_by_trainer'] = len(TrainessCourseRecord.objects.filter(
                course=course_object, approved=True))
            statistic_by_course[course_object]['applicationbywomen'] = len(
                TrainessCourseRecord.objects.filter(course=course_object, trainess__gender="K").order_by(
                    "trainess").values_list("trainess").distinct())
            statistic_by_course[course_object]['applicationbymen'] = len(
                TrainessCourseRecord.objects.filter(course=course_object, trainess__gender="E").order_by(
                    "trainess").values_list("trainess").distinct())
        data['statistic_by_course'] = statistic_by_course

        data['statistic_by_gender_k'] = len(
            TrainessCourseRecord.objects.filter(course__site__is_active=True, trainess__gender="K").order_by(
                "trainess").values_list("trainess").distinct())
        data['statistic_by_gender_e'] = len(
            TrainessCourseRecord.objects.filter(course__site__is_active=True, trainess__gender="E").order_by(
                "trainess").values_list("trainess").distinct())
        data['statistic_by_gender_k_approved'] = len(
            TrainessCourseRecord.objects.filter(course__site__is_active=True, trainess__gender="K",
                                                approved=True).order_by("trainess").values_list("trainess").distinct())
        data['statistic_by_gender_e_approved'] = len(
            TrainessCourseRecord.objects.filter(course__site__is_active=True, trainess__gender="E",
                                                approved=True).order_by("trainess").values_list("trainess").distinct())
        data['statistic_by_university_for_approved'] = []
        data['statistic_by_university'] = []
        for university in UNIVERSITIES:
            data['statistic_by_university'].append((university[0], len(
                TrainessCourseRecord.objects.filter(course__site__is_active=True,
                                                    trainess__university__contains=university[0]).order_by(
                    "trainess").values_list("trainess").distinct())))
            data['statistic_by_university_for_approved'].append((university[0],len(TrainessCourseRecord.objects.filter(course__site__is_active=True,trainess__university__contains=university[0],approved=True).order_by("trainess").values_list("trainess").distinct()))) 
        #data['statistic_by_university'] = sorted(data['statistic_by_university'], key=lambda x: (x[1], x[1]),
        #                                         reverse=True)

        #data['statistic_by_university_for_approved'] = sorted(data['statistic_by_university_for_approved'],
        #                                                      key=lambda x: (x[1], x[1]),
        #                                                      reverse=True)

        # kurs bazinda toplam teyitli olanlar
        total_profile = len(
            TrainessCourseRecord.objects.filter(course__site__is_active=True).order_by("trainess").values(
                "trainess").distinct())
        total_preference = len(TrainessCourseRecord.objects.filter(course__site__is_active=True))
        data['statistic_by_totalsize'] = {'Toplam Profil(Kişi)': total_profile, 'Toplam Tercih': total_preference}
    except Exception as e:
        log.error(e.message, extra=d)
    return render_to_response("training/statistic.html", data)
예제 #41
0
def createprofile(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    log.info("create profile form", extra=d)
    data['update_user_form'] = UpdateUserForm(instance=request.user)
    data['accomodations_preference_count'] = range(ACCOMODATION_PREFERENCE_LIMIT)
    data['form'] = None
    try:
        user_profile = request.user.userprofile
        note = _("You can update your profile below")
        data['form'] = StuProfileForm(instance=user_profile)
        if not UserProfileOPS.is_instructor(user_profile):
            log.debug("egitmen olmayan kullanici icin isleme devam ediliyor", extra=d)
            data['accomodations'] = Accommodation.objects.filter(
                usertype__in=['stu', 'hepsi'], gender__in=[user_profile.gender, 'H'], site=data['site']).order_by(
                'name')
            data['accomodation_records'] = UserAccomodationPref.objects.filter(user=user_profile).order_by(
                'preference_order')
    except:
        note = _("If you want to continue please complete your profile.")
        data['form'] = StuProfileForm()
        data['accomodations'] = Accommodation.objects.filter(usertype__in=['stu', 'hepsi'], gender__in=['K', 'E', 'H'],
                                                             site=data['site']).order_by('name')
    data['sitewidequestions'] = TextBoxQuestions.objects.filter(site=data["site"], active=True, is_sitewide=True)
    if 'register' in request.POST:
        data['update_user_form'] = UpdateUserForm(data=request.POST, instance=request.user)
        try:
            data['form'] = StuProfileForm(request.POST, request.FILES, instance=request.user.userprofile,
                                          ruser=request.user)
        except UserProfile.DoesNotExist:
            data['form'] = StuProfileForm(request.POST, request.FILES, ruser=request.user)

        if data['update_user_form'].is_valid():
            data['update_user_form'].save()
            if data['form'].is_valid():
                log.info("formvalid", extra=d)
                try:
                    profile = data['form'].save(commit=False)
                    profile.user = request.user
                    profile.profilephoto = data['form'].cleaned_data['profilephoto']
                    profile.save()
                    if data['sitewidequestions']:
                        for question in data['sitewidequestions']:
                            answer = request.POST.get("answer%s" % question.pk, "")
                            if answer:
                                tca, created = TrainessClassicTestAnswers.objects.get_or_create(
                                    user=request.user.userprofile, question=question)
                                tca.answer = answer
                                tca.save()
                    if not UserProfileOPS.is_instructor(request.user.userprofile) and ACCOMODATION_PREFERENCE_LIMIT:
                        prefs = UserAccomodationPref.objects.filter(user=request.user.userprofile)
                        if prefs:
                            prefs.delete()
                        for pref in range(0, len(data['accomodations'])):
                            if 'tercih' + str(pref + 1) in request.POST.keys():
                                try:
                                    uaccpref = UserAccomodationPref(user=profile,
                                                                    accomodation=Accommodation.objects.get(
                                                                        pk=request.POST['tercih' + str(pref + 1)]),
                                                                    usertype="stu", preference_order=pref + 1)
                                    uaccpref.save()
                                    note = "Profiliniz başarılı bir şekilde kaydedildi. Kurs tercihleri adımından" \
                                           " devam edebilirsiniz"
                                except Exception as e:
                                    log.error(e.message, extra=d)
                                    note = "Profiliniz kaydedildi ancak konaklama tercihleriniz kaydedilemedi." \
                                           " Sistem yöneticisi ile görüşün!"
                    else:
                        note = "Profiliniz başarılı bir şekilde kaydedildi. Kurs tercihleri adımından" \
                               " devam edebilirsiniz"
                except Exception as e:
                    log.error(e.message, extra=d)
                    note = "Profiliniz kaydedilirken hata oluştu lütfen sayfayı yeniden yükleyip tekrar deneyin"
            else:
                note = "Profiliniz aşağıdaki sebeplerden dolayı oluşturulamadı"
        else:
            note = "Profiliniz aşağıdaki sebeplerden dolayı oluşturulamadı"
    elif 'cancel' in request.POST:
        return redirect("createprofile")
    data['note'] = note
    return render_to_response("userprofile/user_profile.html", data, context_instance=RequestContext(request))
예제 #42
0
def testforapplication(request):
    data = getsiteandmenus(request)

    return render_to_response("testforapplication.html",
                              data,
                              context_instance=RequestContext(request))