Пример #1
0
def active_resend(request):
    data = prepare_template_data(request)
    note = _("Please activate your account.  If you want to re-send an activation email, please click following button") 
    if request.POST:
        user = request.user
        user_verification, created = UserVerification.objects.get_or_create(user_email=user.username)
        context={}
        context['user'] = user
        domain = Site.objects.get(is_active=True).home_url
        if domain.endswith('/'):
            domain = domain.rstrip('/')
        context['domain'] = domain
        
        user_verification, created = UserVerification.objects.get_or_create(user_email=user.username)
        user_verification.activation_key = create_verification_link(user)
        user_verification.save()
        context['activation_key'] = user_verification.activation_key
        try:
            send_email("userprofile/messages/send_confirm_subject.html",
                            "userprofile/messages/send_confirm.html",
                            "userprofile/messages/send_confirm.text",
                            context,
                            settings.EMAIL_FROM_ADDRESS,
                            [user.username])

            note = _("Your activation link has been sent to your email address")
        except Exception as e:
            note = e.message
    data['note'] = note
    return render_to_response("userprofile/activate_resend.html", data, context_instance=RequestContext(request))
Пример #2
0
def active_resend(request):
    data = prepare_template_data(request)
    note = _(
        "Please activate your account.  If you want to re-send an activation email, please click following button"
    )
    if request.POST:
        user = request.user
        user_verification, created = UserVerification.objects.get_or_create(
            user_email=user.username)
        context = {}
        context['user'] = user
        domain = Site.objects.get(is_active=True).home_url
        if domain.endswith('/'):
            domain = domain.rstrip('/')
        context['domain'] = domain

        user_verification, created = UserVerification.objects.get_or_create(
            user_email=user.username)
        user_verification.activation_key = create_verification_link(user)
        user_verification.save()
        context['activation_key'] = user_verification.activation_key
        try:
            send_email("userprofile/messages/send_confirm_subject.html",
                       "userprofile/messages/send_confirm.html",
                       "userprofile/messages/send_confirm.text", context,
                       settings.EMAIL_FROM_ADDRESS, [user.username])

            note = _(
                "Your activation link has been sent to your email address")
        except Exception as e:
            note = e.message
    data['note'] = note
    return render_to_response("userprofile/activate_resend.html",
                              data,
                              context_instance=RequestContext(request))
Пример #3
0
def send_email_by_operation_name(context, operation_name):
    try:
        emailtemplate = EmailTemplate.objects.get(operation_name=operation_name)
        send_email(emailtemplate.subject,
                   emailtemplate.body_html,
                   context,
                   EMAIL_FROM_ADDRESS,
                   context['recipientlist'])
        return 1
    except Exception as e:
        log.error(e.message, extra={'clientip': context.get('clientip', ''), 'user': context.get('user', '')})
        return 0
Пример #4
0
def send_email_by_operation_name(context, operation_name):
    try:
        emailtemplate = EmailTemplate.objects.get(operation_name=operation_name)
        send_email(emailtemplate.subject,
                   emailtemplate.body_html,
                   context,
                   EMAIL_FROM_ADDRESS,
                   context['recipientlist'])
        return 1
    except Exception as e:
        log.error(e.message, extra={'clientip': context.get('clientip', ''), 'user': context.get('user', '')})
        return 0
Пример #5
0
def cancel_all_preference(request):
    d = {"clientip": request.META["REMOTE_ADDR"], "user": request.user}
    if request.POST:
        try:
            data = prepare_template_data(request)
            userprofile = UserProfile.objects.get(user=request.user)
            trainess_course_records = TrainessCourseRecord.objects.filter(trainess=userprofile)
            context = {}
            for tcr in trainess_course_records:
                try:
                    # x. tercih onaylama donemi baslangic zamani ile x. tercih teyit etme donemi arasinda ise mail atsin.
                    now_for_approve = timezone.now()
                    preference_order = tcr.preference_order
                    check_start = ApprovalDate.objects.get(
                        site=data["site"], preference_order=preference_order, for_instructor=True
                    ).start_date
                    check_end = ApprovalDate.objects.get(
                        site=data["site"], preference_order=preference_order, for_trainess=True
                    ).end_date
                    if (now_for_approve > check_start and now_for_approve < check_end) or (
                        tcr.trainess_approved == True
                    ):
                        context["trainess_course_record"] = tcr
                        send_email(
                            "training/messages/notice_for_canceled_courses_subject.html",
                            "training/messages/notice_for_canceled_courses.html",
                            "training/messages/notice_for_canceled_courses.text",
                            context,
                            EMAIL_FROM_ADDRESS,
                            tcr.course.trainer.all().values_list("user__username", flat=True),
                        )
                except Exception as e:
                    log.error(e.message, extra=d)
                trainess_course_records.delete()
            message = "Tüm Başvurularınız Silindi"
            log.debug(message, extra=d)
        except ObjectDoesNotExist:
            message = "Başvurularınız Silinirken Hata Oluştu"
        except Exception as e:
            message = "Başvurularınız Silinirken Hata Oluştu"
            log.error(e.message, extra=d)
        return HttpResponse(json.dumps({"status": "-1", "message": message}), content_type="application/json")
    message = "Başvurularınız Silinirken Hata Oluştu"
    return HttpResponse(json.dumps({"status": "-1", "message": message}), content_type="application/json")
Пример #6
0
def password_reset_key(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = prepare_template_data(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_email=user.username)
                user_verification.password_reset_key = create_verification_link(
                    user)
                user_verification.save()
                context = {}
                context['user'] = user
                context[
                    'activation_key'] = user_verification.password_reset_key
                domain = Site.objects.get(is_active=True).home_url
                if domain.endswith('/'):
                    domain = domain.rstrip('/')
                context['domain'] = domain
                send_email(
                    "userprofile/messages/send_reset_password_key_subject.html",
                    "userprofile/messages/send_reset_password_key.html",
                    "userprofile/messages/send_reset_password_key.text",
                    context, settings.EMAIL_FROM_ADDRESS, [user.username])
                note = _("""Password reset key has been sent""")
            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 password_reset_key(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = prepare_template_data(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_email=user.username)
                user_verification.password_reset_key = create_verification_link(user)
                user_verification.save()
                context = {}
                context['user'] = user
                context['activation_key'] = user_verification.password_reset_key
                domain = Site.objects.get(is_active=True).home_url
                if domain.endswith('/'):
                    domain = domain.rstrip('/')
                context['domain'] = domain
                send_email("userprofile/messages/send_reset_password_key_subject.html",
                                "userprofile/messages/send_reset_password_key.html",
                                "userprofile/messages/send_reset_password_key.text",
                                context,
                                settings.EMAIL_FROM_ADDRESS,
                                [user.username]) 
                note = _("""Password reset key has been sent""")
            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))
Пример #8
0
def send_confirm_link(sender, instance, created, **kwargs):
    if not instance.is_staff:
        if created:
            instance.is_active=False
            user_verification, created = UserVerification.objects.get_or_create(user_email=instance.username)
            user_verification.activation_key = create_verification_link(instance)
            user_verification.save()
            context={}
            context['user'] = instance
            context['activation_key'] = user_verification.activation_key
            domain = Site.objects.get(is_active=True).home_url
            if domain.endswith('/'):
                 domain = domain.rstrip('/')
            context['domain'] = domain
            try:
                send_email("userprofile/messages/send_confirm_subject.html",
                       "userprofile/messages/send_confirm.html",
                       "userprofile/messages/send_confirm.text",
                       context,
                       EMAIL_FROM_ADDRESS,
                       [instance.username])
            except:
                 log.error(("%s account has been created but has been failed send email verification link") % (instance.username),extra={'clientip':'','user':''})
Пример #9
0
def control_panel(request):
    d = {"clientip": request.META["REMOTE_ADDR"], "user": request.user}
    data = prepare_template_data(request)
    note = _("You can accept trainees")
    try:
        uprofile = UserProfile.objects.get(user=request.user).is_student
        log.info(uprofile, extra=d)
        if not uprofile:
            courses = Course.objects.filter(approved=True).filter(trainer__user=request.user)
            log.info(courses, extra=d)
            if courses:
                log.info("egitmenin " + str(len(courses)) + " tane kursu var", extra=d)
                trainess = {}
                now_for_approve = timezone.now()
                log.debug("now_for_approve : egitmen kendi kursunu listeliyor", extra=d)
                log.debug(now_for_approve, extra=d)
                first_pref_approve_start = ApprovalDate.objects.get(
                    site=data["site"], preference_order=1, for_instructor=True
                ).start_date
                first_pref_approve_end = ApprovalDate.objects.get(
                    site=data["site"], preference_order=1, for_instructor=True
                ).end_date
                second_pref_approve_start = ApprovalDate.objects.get(
                    site=data["site"], preference_order=2, for_instructor=True
                ).start_date
                second_pref_approve_end = ApprovalDate.objects.get(
                    site=data["site"], preference_order=2, for_instructor=True
                ).end_date
                third_pref_approve_start = ApprovalDate.objects.get(
                    site=data["site"], preference_order=3, for_instructor=True
                ).start_date
                third_pref_approve_end = ApprovalDate.objects.get(
                    site=data["site"], preference_order=3, for_instructor=True
                ).end_date
                addition1_pref_approve_start = ApprovalDate.objects.get(
                    site=data["site"], preference_order=-1, for_instructor=True
                ).start_date
                addition1_pref_approve_end = ApprovalDate.objects.get(
                    site=data["site"], preference_order=-1, for_instructor=True
                ).end_date
                note = (
                    "  1. Tercihleri %s - %s tarihleri arasında onaylayabilirsiniz"
                    % (
                        first_pref_approve_start.strftime(DATETIME_FORMAT),
                        first_pref_approve_end.strftime(DATETIME_FORMAT),
                    )
                    + "  "
                )
                note += (
                    "  2. Tercihten %s - %s tarihleri arasında seçebilirsiniz"
                    % (
                        second_pref_approve_start.strftime(DATETIME_FORMAT),
                        second_pref_approve_end.strftime(DATETIME_FORMAT),
                    )
                    + "  "
                )
                note += (
                    "  3. Tercihten %s - %s tarihleri arasında seçebilirsiniz"
                    % (
                        third_pref_approve_start.strftime(DATETIME_FORMAT),
                        third_pref_approve_end.strftime(DATETIME_FORMAT),
                    )
                    + "  "
                )
                data["closed_pref_1"] = "1"
                data["closed_pref_2"] = "1"
                data["closed_pref_3"] = "1"
                data["closed_pref_addition1"] = "1"
                data["note_edit_closed"] = "1"
                if now_for_approve > first_pref_approve_start and now_for_approve < addition1_pref_approve_end:
                    if (now_for_approve > first_pref_approve_start) and (now_for_approve < first_pref_approve_end):
                        data["closed_pref_1"] = "0"
                    if (now_for_approve > second_pref_approve_start) and (now_for_approve < second_pref_approve_end):
                        data["closed_pref_2"] = "0"
                    if (now_for_approve > third_pref_approve_start) and (now_for_approve < third_pref_approve_end):
                        data["closed_pref_3"] = "0"
                    if (now_for_approve > addition1_pref_approve_start) and (
                        now_for_approve < addition1_pref_approve_end
                    ):
                        data["closed_pref_addition1"] = "0"
                if now_for_approve > addition1_pref_approve_end:
                    data["note_edit_closed"] = "0"
                for course in courses:
                    trainess[course] = {}
                    if (
                        now_for_approve
                        < ApprovalDate.objects.get(site=data["site"], preference_order=-1, for_trainess=True).end_date
                    ):
                        trainess[course]["trainess1"] = (
                            TrainessCourseRecord.objects.filter(course=course.pk)
                            .filter(preference_order=1)
                            .exclude(
                                trainess__in=TrainessCourseRecord.objects.values_list("trainess")
                                .filter(~Q(course=course.pk))
                                .filter(trainess_approved=True)
                            )
                            .prefetch_related("course")
                        )
                        trainess[course]["trainess2"] = (
                            TrainessCourseRecord.objects.filter(course=course.pk)
                            .filter(preference_order=2)
                            .exclude(
                                trainess__in=TrainessCourseRecord.objects.values_list("trainess")
                                .filter(~Q(course=course.pk))
                                .filter(trainess_approved=True)
                            )
                            .prefetch_related("course")
                        )
                        trainess[course]["trainess3"] = (
                            TrainessCourseRecord.objects.filter(course=course.pk)
                            .filter(preference_order=3)
                            .exclude(
                                trainess__in=TrainessCourseRecord.objects.values_list("trainess")
                                .filter(~Q(course=course.pk))
                                .filter(trainess_approved=True)
                            )
                            .prefetch_related("course")
                        )
                        trainess[course]["trainess_addition_1"] = (
                            TrainessCourseRecord.objects.filter(course=course.pk)
                            .filter(preference_order=-1)
                            .exclude(
                                trainess__in=TrainessCourseRecord.objects.values_list("trainess")
                                .filter(~Q(course=course.pk))
                                .filter(trainess_approved=True)
                            )
                            .prefetch_related("course")
                        )
                    else:
                        trainess[course]["trainess1"] = (
                            TrainessCourseRecord.objects.filter(course=course.pk)
                            .filter(preference_order=1)
                            .filter(approved=True)
                            .filter(trainess_approved=True)
                            .prefetch_related("course")
                        )
                        trainess[course]["trainess2"] = (
                            TrainessCourseRecord.objects.filter(course=course.pk)
                            .filter(preference_order=2)
                            .filter(approved=True)
                            .filter(trainess_approved=True)
                            .prefetch_related("course")
                        )
                        trainess[course]["trainess3"] = (
                            TrainessCourseRecord.objects.filter(course=course.pk)
                            .filter(preference_order=3)
                            .filter(approved=True)
                            .filter(trainess_approved=True)
                            .prefetch_related("course")
                        )
                        trainess[course]["trainess_addition_1"] = (
                            TrainessCourseRecord.objects.filter(course=course.pk)
                            .filter(preference_order=-1)
                            .filter(approved=True)
                            .filter(trainess_approved=True)
                            .prefetch_related("course")
                        )
                data["trainess"] = trainess
                if request.POST:
                    log.info("kursiyer onay islemi basladi", extra=d)
                    log.info(request.POST, extra=d)
                    for course in courses:
                        try:
                            if now_for_approve > first_pref_approve_start and now_for_approve < third_pref_approve_end:
                                allprefs = []
                                if (now_for_approve > first_pref_approve_start) and (
                                    now_for_approve < first_pref_approve_end
                                ):
                                    allprefs.extend(
                                        TrainessCourseRecord.objects.filter(course=course.pk).filter(preference_order=1)
                                    )
                                    log.debug(allprefs, extra=d)
                                if (now_for_approve > second_pref_approve_start) and (
                                    now_for_approve < second_pref_approve_end
                                ):
                                    allprefs.extend(
                                        TrainessCourseRecord.objects.filter(course=course.pk).filter(preference_order=2)
                                    )
                                    log.debug(allprefs, extra=d)
                                if (now_for_approve > third_pref_approve_start) and (
                                    now_for_approve < third_pref_approve_end
                                ):
                                    allprefs.extend(
                                        TrainessCourseRecord.objects.filter(course=course.pk).filter(preference_order=3)
                                    )
                                    log.debug(allprefs, extra=d)
                                approvedr = request.POST.getlist("students" + str(course.pk))
                                log.debug(allprefs, extra=d)
                                for p in allprefs:
                                    if str(p.pk) not in approvedr:
                                        p.approved = False
                                    elif str(p.pk) in approvedr:
                                        p.approved = True
                                    p.save()
                                    log.debug(p, extra=d)
                                course.trainess.clear()
                                allprefs = TrainessCourseRecord.objects.filter(course=course.pk)
                                for p in allprefs:
                                    if p.approved == True:
                                        course.trainess.add(p.trainess)
                                course.save()

                                data["user"] = request.user
                                data["course"] = course
                                send_email(
                                    "training/messages/inform_trainers_about_changes_subject.txt",
                                    "training/messages/inform_trainers_about_changes.html",
                                    "training/messages/inform_trainers_about_changes.txt",
                                    data,
                                    EMAIL_FROM_ADDRESS,
                                    course.trainer.all().values_list("user__username", flat=True),
                                )

                                note = "Seçimleriniz başarılı bir şekilde kaydedildi."
                            else:
                                if (now_for_approve > addition1_pref_approve_start) and (
                                    now_for_approve < addition1_pref_approve_end
                                ):
                                    allprefs = []
                                    allprefs.extend(
                                        TrainessCourseRecord.objects.filter(course=course.pk).filter(
                                            preference_order=-1
                                        )
                                    )
                                    approvedr = request.POST.getlist("students" + str(course.pk))
                                    log.debug(allprefs, extra=d)
                                    for p in allprefs:
                                        if str(p.pk) not in approvedr:
                                            p.approved = False
                                        elif str(p.pk) in approvedr:
                                            p.approved = True
                                            p.trainess_approved = True
                                        p.save()
                                        log.debug(p, extra=d)
                                    course.trainess.clear()
                                    allprefs = TrainessCourseRecord.objects.filter(course=course.pk)
                                    for p in allprefs:
                                        if p.approved == True:
                                            course.trainess.add(p.trainess)
                                    course.save()

                                    data["user"] = request.user
                                    data["course"] = course
                                    send_email(
                                        "training/messages/inform_trainers_about_changes_subject.txt",
                                        "training/messages/inform_trainers_about_changes.html",
                                        "training/messages/inform_trainers_about_changes.txt",
                                        data,
                                        EMAIL_FROM_ADDRESS,
                                        course.trainer.all().values_list("user__username", flat=True),
                                    )

                                    note = "Seçimleriniz başarılı bir şekilde kaydedildi."
                                else:
                                    note = "Onaylama dönemi dışındasınız"
                        except Exception as e:
                            note = "Beklenmedik bir hata oluştu!"
                            log.error(e.message, extra=d)
            data["TRAINESS_SCORE"] = TRAINESS_SCORE
            data["note"] = note
            return render_to_response("training/controlpanel.html", data, context_instance=RequestContext(request))
        else:
            return redirect("applytocourse")
    except UserProfile.DoesNotExist:
        return redirect("createprofile")
Пример #10
0
def apply_to_course(request):
    d = {"clientip": request.META["REMOTE_ADDR"], "user": request.user}
    data = prepare_template_data(request)
    userprofile = None
    try:
        userprofile = UserProfile.objects.get(user=request.user)
    except ObjectDoesNotExist:
        return redirect("createprofile")
    if userprofile.userpassedtest:
        data["closed"] = "0"
        data["additional1_pref_closed"] = "1"
        data["PREFERENCE_LIMIT"] = PREFERENCE_LIMIT
        data["ADDITION_PREFERENCE_LIMIT"] = ADDITION_PREFERENCE_LIMIT
        message = ""
        now = datetime.date(datetime.now())
        note = _("You can choose courses in order of preference.")
        if request.method == "POST":
            if now < data["site"].application_start_date:
                message = _("You can choose courses in future")
                data["closed"] = True
                return HttpResponse(json.dumps({"status": "-1", "message": message}), content_type="application/json")
            elif now > data["site"].application_end_date:
                message = _("The course choosing process is closed")
                data["closed"] = True
                return HttpResponse(json.dumps({"status": "-1", "message": message}), content_type="application/json")
            TrainessCourseRecord.objects.filter(trainess=userprofile).delete()
            course_prefs = json.loads(request.POST.get("course"))
            if len(course_prefs) <= PREFERENCE_LIMIT:
                if len(set([i["value"] for i in course_prefs])) == len([i["value"] for i in course_prefs]):
                    for course_pre in course_prefs:
                        try:
                            course_record = TrainessCourseRecord(
                                trainess=userprofile,
                                course=Course.objects.get(id=course_pre["value"]),
                                preference_order=course_pre["name"],
                            )
                            course_record.save()
                            message = "Tercihleriniz başarılı bir şekilde güncellendi"
                        except Exception as e:
                            log.error(e.message, extra=d)
                            message = "Tercihleriniz kaydedilirken hata oluştu"
                            return HttpResponse(
                                json.dumps({"status": "-1", "message": message}), content_type="application/json"
                            )
                else:
                    message = "Farklı Tercihlerinizde Aynı Kursu Seçemezsiniz"
                    return HttpResponse(
                        json.dumps({"status": "-1", "message": message}), content_type="application/json"
                    )
                try:
                    context = {}
                    context["user"] = request.user
                    domain = Site.objects.get(is_active=True).home_url
                    if domain.endswith("/"):
                        domain = domain.rstrip("/")
                    context["domain"] = domain

                    send_email(
                        "training/messages/preference_saved_subject.html",
                        "training/messages/preference_saved.html",
                        "training/messages/preference_saved.text",
                        context,
                        EMAIL_FROM_ADDRESS,
                        [request.user.username],
                    )
                except Exception as e:
                    log.error(e.message, extra=d)

                return HttpResponse(json.dumps({"status": "0", "message": message}), content_type="application/json")
            else:
                message = "En fazla " + PREFERENCE_LIMIT + " tane tercih hakkına sahipsiniz"
                return HttpResponse(json.dumps({"status": "-1", "message": message}), content_type="application/json")

        additipnal_pref_start_for_trainess = ApprovalDate.objects.get(
            site=data["site"], preference_order=1, for_instructor=True
        ).start_date
        courses = Course.objects.filter(approved=True)
        course_records = TrainessCourseRecord.objects.filter(trainess__user=request.user).order_by("preference_order")
        data["courses"] = courses
        data["course_records"] = course_records
        data["note"] = note
        if now < data["site"].application_start_date:
            data["note"] = _("You can choose courses in future")
            data["closed"] = "1"
            return render_to_response("training/courserecord.html", data)
        elif now > data["site"].application_end_date:
            data["note"] = _("The course choosing process is closed")
            data["closed"] = "1"
            if (
                len(
                    TrainessCourseRecord.objects.filter(trainess_approved=True)
                    .filter(preference_order__gte=0)
                    .filter(trainess=userprofile)
                )
                == 0
            ):
                try:
                    additional1_pref_for_trainess = ApprovalDate.objects.get(
                        site=data["site"], preference_order=-1, for_trainess=True
                    )
                    now_for_pref = timezone.now()
                    if (
                        now_for_pref > additional1_pref_for_trainess.start_date
                        and now_for_pref < additional1_pref_for_trainess.end_date
                    ):
                        data["additional1_pref_closed"] = "0"
                        log.debug("ek tercih aktif", extra=d)
                        data["note"] = _("Ek tercih dönemi içindesiniz, ek tercih yapabilirsiniz")
                except ObjectDoesNotExist:
                    log.error("ek tercih icin sure bulunamadi", extra=d)
                except Exception as e:
                    log.error(e.message, extra=d)
            return render_to_response("training/courserecord.html", data)
        return render_to_response("training/courserecord.html", data)
    else:
        return redirect("testbeforeapply")
Пример #11
0
def apply_to_course(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = prepare_template_data(request)
    userprofile = None
    try:
        userprofile = UserProfile.objects.get(user=request.user)
    except ObjectDoesNotExist:
        return redirect("createprofile")
    if userprofile.userpassedtest:
        data['closed'] = "0"
        data['PREFERENCE_LIMIT'] = PREFERENCE_LIMIT
        message = ""
        now = datetime.date(datetime.now())
        note = _("You can choose courses in order of preference.")
        if request.method == "POST":
            if now < data['site'].application_start_date:
                message = _("You can choose courses in future")
                data['closed'] = True
                return HttpResponse(json.dumps({
                    'status': '-1',
                    'message': message
                }),
                                    content_type="application/json")
            elif now > data['site'].application_end_date:
                message = _("The course choosing process is closed")
                data['closed'] = True
                return HttpResponse(json.dumps({
                    'status': '-1',
                    'message': message
                }),
                                    content_type="application/json")
            TrainessCourseRecord.objects.filter(trainess=userprofile).delete()
            course_prefs = json.loads(request.POST.get('course'))
            if len(course_prefs) <= PREFERENCE_LIMIT:
                if len(set([i['value'] for i in course_prefs
                            ])) == len([i['value'] for i in course_prefs]):
                    for course_pre in course_prefs:
                        try:
                            course_record = TrainessCourseRecord(
                                trainess=userprofile,
                                course=Course.objects.get(
                                    id=course_pre['value']),
                                preference_order=course_pre['name'])
                            course_record.save()
                            message = "Tercihleriniz başarılı bir şekilde güncellendi"
                        except Exception as e:
                            log.error(e.message, extra=d)
                            message = "Tercihleriniz kaydedilirken hata oluştu"
                            return HttpResponse(
                                json.dumps({
                                    'status': '-1',
                                    'message': message
                                }),
                                content_type="application/json")
                else:
                    message = "Farklı Tercihlerinizde Aynı Kursu Seçemezsiniz"
                    return HttpResponse(json.dumps({
                        'status': '-1',
                        'message': message
                    }),
                                        content_type="application/json")
                try:
                    context = {}
                    context['user'] = request.user
                    domain = Site.objects.get(is_active=True).home_url
                    if domain.endswith('/'):
                        domain = domain.rstrip('/')
                    context['domain'] = domain

                    send_email(
                        "training/messages/preference_saved_subject.html",
                        "training/messages/preference_saved.html",
                        "training/messages/preference_saved.text", context,
                        EMAIL_FROM_ADDRESS, [request.user.username])
                except Exception as e:
                    log.error(e.message, extra=d)

                return HttpResponse(json.dumps({
                    'status': '0',
                    'message': message
                }),
                                    content_type="application/json")
            else:
                message = "En fazla " + PREFERENCE_LIMIT + " tane tercih hakkına sahipsiniz"
                return HttpResponse(json.dumps({
                    'status': '-1',
                    'message': message
                }),
                                    content_type="application/json")
        courses = Course.objects.filter(approved=True)
        course_records = TrainessCourseRecord.objects.filter(
            trainess__user=request.user).order_by('preference_order')
        data['courses'] = courses
        data['course_records'] = course_records
        data['note'] = note
        if now < data['site'].application_start_date:
            data['note'] = _("You can choose courses in future")
            data['closed'] = "1"
            return render_to_response('training/courserecord.html', data)
        elif now > data['site'].application_end_date:
            data['note'] = _("The course choosing process is closed")
            data['closed'] = "1"
            return render_to_response('training/courserecord.html', data)
        return render_to_response('training/courserecord.html', data)
    else:
        return redirect("testbeforeapply")
Пример #12
0
def apply_to_course(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data=prepare_template_data(request)
    userprofile=None
    try:
        userprofile = UserProfile.objects.get(user=request.user)
    except ObjectDoesNotExist:
        return redirect("createprofile")
    if userprofile.userpassedtest:
        data['closed'] = "0"
        data['PREFERENCE_LIMIT'] = PREFERENCE_LIMIT
        message = ""
        now = datetime.date(datetime.now())
        note = _("You can choose courses in order of preference.")
        if request.method == "POST":
            if now < data['site'].application_start_date:
                message = _("You can choose courses in future")
                data['closed'] = True
                return HttpResponse(json.dumps({'status':'-1', 'message':message}), content_type="application/json")
            elif now > data['site'].application_end_date:
                message = _("The course choosing process is closed")
                data['closed'] = True
                return HttpResponse(json.dumps({'status':'-1', 'message':message}), content_type="application/json")
            TrainessCourseRecord.objects.filter(trainess=userprofile).delete()
            course_prefs = json.loads(request.POST.get('course'))
            if len(course_prefs) <= PREFERENCE_LIMIT:
                if len(set([i['value'] for i in course_prefs])) == len([i['value'] for i in course_prefs]):
                    for course_pre in course_prefs:
                        try:
                            course_record = TrainessCourseRecord(trainess=userprofile, 
                                                  course=Course.objects.get(id=course_pre['value']), 
                                                  preference_order=course_pre['name'])
                            course_record.save()
                            message = "Tercihleriniz başarılı bir şekilde güncellendi"
                        except Exception as e:
                            log.error(e.message, extra = d)
                            message = "Tercihleriniz kaydedilirken hata oluştu"
                            return HttpResponse(json.dumps({'status':'-1', 'message':message}), content_type="application/json")
                else:
                    message = "Farklı Tercihlerinizde Aynı Kursu Seçemezsiniz"
                    return HttpResponse(json.dumps({'status':'-1', 'message':message}), content_type="application/json")
                try:
                    context={}
                    context['user'] = request.user
                    domain = Site.objects.get(is_active=True).home_url
                    if domain.endswith('/'):
                        domain = domain.rstrip('/')
                    context['domain'] = domain
 
                    send_email("training/messages/preference_saved_subject.html",
                                 "training/messages/preference_saved.html",
                                 "training/messages/preference_saved.text",
                                 context,
                                 EMAIL_FROM_ADDRESS,
                                 [request.user.username])
                except Exception as e:
                    log.error(e.message, extra = d)
 
                return HttpResponse(json.dumps({'status':'0', 'message':message}), content_type="application/json")
            else:
                message = "En fazla "+ PREFERENCE_LIMIT + " tane tercih hakkına sahipsiniz"
                return HttpResponse(json.dumps({'status':'-1', 'message':message}), content_type="application/json")
        courses = Course.objects.filter(approved=True)
        course_records = TrainessCourseRecord.objects.filter(trainess__user=request.user).order_by('preference_order')
        data['courses'] = courses
        data['course_records'] = course_records
        data['note'] = note
        if now < data['site'].application_start_date:
            data['note'] = _("You can choose courses in future")
            data['closed'] = "1"
            return render_to_response('training/courserecord.html', data)
        elif now > data['site'].application_end_date:
            data['note'] = _("The course choosing process is closed")
            data['closed'] = "1"
            return render_to_response('training/courserecord.html', data) 
        return render_to_response('training/courserecord.html', data)
    else:
        return redirect("testbeforeapply")