示例#1
0
def generateArchives(request):
    """ Generates archive files (DwC-A) for all datasets.
    """
    error_message = None
    #
    if request.method == "GET":
        form = forms.GenerateArchivesForm()
        contextinstance = {'form'   : form,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("generate_archives.html", contextinstance)
    elif request.method == "POST":
        #
        form = forms.GenerateArchivesForm(request.POST)
        if form.is_valid():
            #
            user = request.POST['user']
            password = request.POST['password']
            if password != settings.APPS_VALID_USERS_AND_PASSWORDS_FOR_TEST.get(user, None):
                error_message = 'Not a valid user or password. Please try again...'   
            #
            if error_message == None:
                    sharkdata_core.SharkdataAdminUtils().generateArchivesForAllDatasetsInThread(user)
            # OK.
            if error_message == None:
                return HttpResponseRedirect("/sharkdataadmin")
        #
        contextinstance = {'form'   : form,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("generate_archives.html", contextinstance)
    # Not a valid request method.
    return HttpResponseRedirect("/sharkdataadmin")
示例#2
0
def kpi(request, id_assigned_kpi):
    if not request.user.is_authenticated():
        return redirect('login')
    try:
        assigned_kpi = AssignedKPI.objects.get(id=id_assigned_kpi)
    except AssignedKPI.DoesNotExist:
        access_error = "Такого KPI не существует."
        return render(request, 'app/access_error.html', {'access_error': access_error})
    profile = UserProfile.objects.get(user=request.user)
    department = assigned_kpi.department
    args = {}
    args.update(csrf(request))
    args['access_flag']= profile.has_access(department)
    if department == profile.department or args['access_flag']:
        args.update(csrf(request))
        args['profile'] = profile
        args['assigned_kpi'] = assigned_kpi
        args['percent'] = assigned_kpi.to_percent()

        comment = Comments(sender=request.user, kpi=assigned_kpi, datetime=datetime.now())
        args['comment_form'] = CommentCreationForm(instance=comment)
        args['comments_set'] = Comments.objects.filter(kpi=assigned_kpi)
        if assigned_kpi.accepted is None:
            return render(request, 'app/kpi.html', args)
        if assigned_kpi.accepted == True:
            if args['access_flag'] is False:
                args['form'] = KPIReportForm()
            return render(request, 'app/kpi.html', args)
        else:
            args['access_error'] = "Задание отклонено"
            return render(request, 'app/access_error.html', args)
    else:
        access_error = "Вы не имеете доступа к данному KPI"
        return render(request, 'app/access_error.html', {'access_error': access_error})
示例#3
0
def activar_cuenta(request,codigo):
    try:
        u = validation.objects.get(ash=codigo)
    except:
        print('error al buscar la validacion')
        c = {}
        c.update(csrf(request))
        return render(request,'web/'+request.session['lang']+'/activation_link_error.html',c)

    if u is None:
        c = {}
        c.update(csrf(request))
        return render(request,'web/'+request.session['lang']+'/activacionerror.html',c)

    else:
        expired_date = u.creation_date - timedelta(days=2)
        print(expired_date)
        if expired_date > u.creation_date :
            u.user.delete()
            u.delete()
            c = {}
            c.update(csrf(request))
            return render(request,'web/'+request.session['lang']+'/activation_link_error.html',c)

        u.user.is_active = True
        u.user.save()
        u.delete()
        c = {}
        c.update(csrf(request))
        return render(request,'web/'+request.session['lang']+'/activacion_complete.html',c)
示例#4
0
def activate_account_studio(request, key):
    """
    When link in activation e-mail is clicked and the link belongs to studio.
    """
    try:
        registration = Registration.objects.get(activation_key=key)
    except (Registration.DoesNotExist, Registration.MultipleObjectsReturned):
        return render_to_response(
            "registration/activation_invalid.html",
            {'csrf': csrf(request)['csrf_token']}
        )
    else:
        user_logged_in = request.user.is_authenticated
        already_active = True
        if not registration.user.is_active:
            if waffle().is_enabled(PREVENT_AUTH_USER_WRITES):
                return render_to_response('registration/activation_invalid.html',
                                          {'csrf': csrf(request)['csrf_token']})
            registration.activate()
            already_active = False

        return render_to_response(
            "registration/activation_complete.html",
            {
                'user_logged_in': user_logged_in,
                'already_active': already_active
            }
        )
示例#5
0
文件: views.py 项目: nitish116/Jumper
def index(request):
    if request.POST:
        form = MyRegistrationForm(request.POST)

        if form.is_valid():
            ride_num = form.cleaned_data["ride_num"]
            runopt = form.cleaned_data["runopt"]
            run_input = {}
            run_input["ride_num"] = int(ride_num)
            run_input["runopt"] = int(runopt)
            cPickle.dump(run_input, open("run_input.dat", "w"))
            os.system("python run.py")
        else:
            print "Not valid"
        t = loader.get_template("maps/index.html")

        markers_ds = cPickle.load(open(BASE_DIR + "/tmp.dat", "r"))
        c = Context(markers_ds)
        c.update(csrf(request))
        return HttpResponse(t.render(c))
    else:
        t = loader.get_template("maps/index.html")
        markers_ds = cPickle.load(open(BASE_DIR + "/tmp.dat", "r"))
        c = Context(markers_ds)
        c.update(csrf(request))
        return HttpResponse(t.render(c))
示例#6
0
文件: views.py 项目: hxoxh/yan_han
def UploadExcelForm(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            wb = xlrd.open_workbook(filename = None,file_contents = request.FILES['excel'].read())
            ws = wb.sheet_by_index(0)
            for r in range(1,ws.nrows):
                megaNo = ws.cell(r,19).value
                sample = models.MedicineSampleInfo.objects.filter(sampleno=megaNo)
                mut_det_res = models.MedicineMutDetRes(id = sample[0].id,chr = ws.cell(r,0).value,start=ws.cell(r,1).value,ref=ws.cell(r,2).value,alt=ws.cell(r,3).value,gene=ws.cell(r,4).value,ref_seq=ws.cell(r,5).value,dna_ch=ws.cell(r,6).value,aa_ch=ws.cell(r,7).value,het=ws.cell(r,8).value,mut_type=ws.cell(r,9).value,disease=ws.cell(r,10).value,result=ws.cell(r,11).value,inher_type=ws.cell(r,12).value,info_gene=ws.cell(r,13).value,info_locus=ws.cell(r,14).value,info_disease=ws.cell(r,15).value,conclusion=ws.cell(r,16).value,ref_paper=ws.cell(r,17).value,ana_type=ws.cell(r,18).value,sam_num=ws.cell(r,19).value)
                mut_det_res.save()
                now = time.strftime('%Y%m%d-%H%M%S', time.localtime())

                try:
                    mut_res_get = models.MedicineMutRes.objects.get(id = sample[0].id)
                except:
                    print "数据库不存在此样本解读结果,执行插入操作"
                    mut_res = models.MedicineMutRes(id=sample[0].id, create_time=now, record_time=now, up_num=1)
                    mut_res.save()
                else:
                    print "数据库已存在此样本解读结果,执行更新操作"
                    up_num = mut_res_get.up_num + 1
                    models.MedicineMutRes.objects.filter(id=sample[0].id).update(record_time=now,up_num=up_num)

            return render_to_response('index/test.html',csrf(request).update({'mut_det_res': mut_det_res}))
    else:
        form = UploadFileForm()
    return render_to_response('index/parsemut.html',csrf(request).update({'from':form,}))
示例#7
0
def Subscription(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/accounts/login/?next=/event/subscribe/")
    parameters = {}
    parameters.update(csrf(request))
    parameters["request"] = request
    parameters.update(csrf(request))
    if request.method == 'POST':
        if len(GeneralUser.objects.filter(user=request.user)) != 0:
            form = SubscriptionForm(request.POST, instance=GeneralUser.objects.get(user=request.user))
        else:
            form = SubscriptionForm(request.POST)
        if form.is_valid():
            general_user = form.save(commit=False)
            general_user.user = request.user
            general_user.save()
            form.save_m2m()
            parameters['message'] = "Submitted successfully"

    else:
        print GeneralUser.objects.filter(user=request.user)
        try:
            form = SubscriptionForm(instance=GeneralUser.objects.get(user=request.user))
        except:
            form = SubscriptionForm()
        parameters['form'] = form
    return render_to_response('Event/subscription.html', parameters)
示例#8
0
def user_details_entry(request):
    # import ipdb; ipdb.set_trace()

    context = {}
    if request.method == "POST":
        try:
            full_name = request.POST.get("full_name")
            pic = request.FILES.get("pic")
            sex = request.POST.get("sex")

            user = request.user
            user = UserProfile.objects.get(user=user)
            user = UserProfileInfo(
                userlink=user,
                full_name=full_name,
                gender=sex,
                profile_pic=pic)
            user.save()
            context = {
                "status": True, 'message': "Profile Saved."
            }
            context.update(csrf(request))
            return render_to_response("userdetailsentry.html", context)
        except:
            context = {
                "status": False, 'message': "Profile Not Saved."
            }
            context.update(csrf(request))
            return render_to_response("userdetailsentry.html", context)
    context = {'message': "not saved"}
    context.update(csrf(request))
    return render_to_response("userdetailsentry.html", context)
示例#9
0
文件: views.py 项目: qyczyr/tomb
def login(request):
    if request.method == 'GET':
        next_url = request.GET.get('next', '/home')
        c = {'next': next_url}
        c.update(csrf(request))
        return render_to_response('djsite/login.html', c)
    else: # POST
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        next_url = request.POST.get('next', '/home')
        user = auth_authenticate(username = username, password = password)
        # if user and user.is_active:
        if user and user.is_active:
            auth_login(request, user)
            return redirect(next_url)
        elif user and not user.is_active:
            ctx = {}
            ctx['username'] = username
            ctx['email'] = user.email
            ctx['cookie'] = verification_cookie_of_user(user)
            return HttpResponse('<a href="/active?username=%s&email=%s&cookie=%s">Active link</a>' % (
                username, email, cookie))
        else:
            c = {'next': next_url, 'auth_fail' : True,
                 'username': username, 'password': password}
            c.update(csrf(request))
            return render_to_response('djsite/login.html', c)
示例#10
0
文件: views.py 项目: hxoxh/yan_han
def getaddinfo(request):
    if request.method == 'GET':
        form = GetAddInfoFrom()
        return render_to_response('index/index.html',csrf(request).update({'from':form,}))
    else:
        form = GetAddInfoFrom(request.POST)
        if form.is_valid():
            megaNo = request.POST.get('megaNo','')
            rsSite = request.POST.get('rsSite','')
            geneResult = request.POST.get('geneResult','')
            now = time.strftime('%Y%m%d-%H:%M', time.localtime())
            if megaNo is not None and rsSite is not None and geneResult is not None:
                sample = models.MedicineSampleInfo.objects.filter(sampleno = megaNo)
                now = time.strftime('%Y%m%d-%H%M%S', time.localtime())
                addres = models.MedicineAddResult(id = sample[0].id,add_rs = rsSite,add_gt = geneResult,current_time=now)
                try:
                    addget = models.MedicineAddResult.objects.get(id=sample[0].id, add_rs=rsSite)
                except:
                    print "数据库不存在此样本位点补点结果,执行插入操作",addres.id
                    addres.save()
                else:
                    print "数据库中存在此样本位点补点结果,执行更新操作",addres.id
                    models.MedicineAddResult.objects.filter(id=sample[0].id, add_rs=rsSite).update(add_gt=geneResult)

                return render_to_response('index/success.html',csrf(request).update({'from':form,}))
            else:
                return  render_to_response('index/index.html',csrf(request).update({'from':form,}))
        else:
            return render_to_response('index/index.html',csrf(request).update({'from':form,}))
示例#11
0
def form_inscription(request):  # user sign in form
    if request.method == "POST":
        if request.POST.get("accept_CGU", ""):  # check wether user accepted CGU
            form = FoInscription(request.POST)
            if form.is_valid():
                password = form.cleaned_data.get("password")  # two password fields
                # to check
                password2 = form.cleaned_data.get("password2")  # the user did
                # no mistake
                if password != password2:  # check wether passwords matches
                    msg1 = 1  # used to send a "password mismatch" message to user
                    form = FoInscription()
                    c = {"msg1": msg1, "form": form}
                    c.update(csrf(request))
                    # send back the requester to the sign in form
                    return render_to_response("templates/inscription.html", c)
                lastname = form.cleaned_data.get("user_lastname")
                firstname = form.cleaned_data.get("user_firstname")
                email = form.cleaned_data.get("user_mail")
                age = form.cleaned_data.get("user_age")
                login = form.cleaned_data.get("user_login")
                email_subject = "Création de compte"
                email_body = "Merci de vous être enregistré."
                try:
                    user = orangeuser.objects.create_user(firstname, lastname, age, login, email, password)
                    # create a session user
                except IntegrityError:
                    message = 1
                    # send message user already exists
                    form = FoInscription()
                    # create a variable dictionnary
                    c = {"form": form, "message": message}
                    c.update(csrf(request))
                    # add a csrf token, protects against cross site request forgery
                    return render_to_response("orange/inscription.html", c)
                    # redirect user to the html page with the dictionnary
                # send_mail(email_subject, email_body, '*****@*****.**', \
                # ['*****@*****.**']\
                # , fail_silently=False)
                # send an email to the new user to activate the account with an
                # activation link
                user.save()  # save the session user in DB
                return HttpResponseRedirect("/home/")
                # form = FoInscription()
        else:
            err = 1
            # check wether a user checked or not the box "Conditions générales.."
            form = FoInscription()
            c = {"form": form, "error": err}
            # err : send an error "CGU not checked"
            c.update(csrf(request))
            return render_to_response("orange/inscription.html", c)

    else:
        form = FoInscription()
    c = {"form": form}
    c.update(csrf(request))

    return render_to_response("orange/inscription.html", c)
示例#12
0
def work_report(request):
    try:
        human_resource = HumanResource.objects.filter(user=UserExtension.get_user_extension(request.user))
        if len(human_resource) == 0:
            error_message = "User "+request.user.__str__()+" is not registered as human resource"
            raise UserIsNoHumanResource(error_message)
        if request.POST.get('post'):
            if 'cancel' in request.POST:
                return HttpResponseRedirect('/admin/')
            elif 'save' in request.POST:
                range_selection_form = RangeSelectionForm(request.POST)
                if range_selection_form.is_valid():
                    formset = BaseWorkEntryFormset.load_formset(range_selection_form,
                                                                request)
                    if not formset.is_valid():
                        c = {'range_selection_form': range_selection_form,
                             'formset': formset}
                        c.update(csrf(request))
                        return render(request, 'crm/admin/time_reporting.html', c)
                    else:
                        for form in formset:
                            form.update_work(request)
                        messages.success(request, _('you have successfully updated your work'))
                formset = BaseWorkEntryFormset.create_updated_formset(range_selection_form,
                                                                      human_resource)
                range_selection_form.update_from_input()
                c = {'range_selection_form': range_selection_form,
                     'formset': formset}
                c.update(csrf(request))
                return render(request, 'crm/admin/time_reporting.html', c)
            return HttpResponseRedirect('/admin/')
        else:
            datetime_now = datetime.datetime.today()
            to_date = (datetime_now + datetime.timedelta(days=30)).date()
            from_date = datetime_now.date()
            range_selection_form = RangeSelectionForm.create_range_selection_form(from_date, to_date)
            formset = BaseWorkEntryFormset.create_new_formset(from_date,
                                                              to_date,
                                                              human_resource)
            c = {'formset': formset,
                 'range_selection_form': range_selection_form}
            c.update(csrf(request))
            return render(request, 'crm/admin/time_reporting.html', c)
    except (UserExtensionMissing,
            ReportingPeriodNotFound,
            TooManyUserExtensionsAvailable,
            UserIsNoHumanResource) as e:
        if isinstance(e, UserExtensionMissing):
            return HttpResponseRedirect(e.view)
        elif isinstance(e, ReportingPeriodNotFound):
            return HttpResponseRedirect(e.view)
        elif isinstance(e, TooManyUserExtensionsAvailable):
            return HttpResponseRedirect(e.view)
        elif isinstance(e, UserIsNoHumanResource):
            return HttpResponseRedirect(e.view)
        else:
            raise Http404
示例#13
0
def deleteResource(request, resource_id):
    """ Deletes one row in the database. The FTP area is not affected. """
    resource = models.Resources.objects.get(id=resource_id)
    #
    if request.method == "GET":
        form = forms.DeleteResourceForm()
        contextinstance = {'form'   : form,
                           'resource' : resource,
                           'error_message' : None}
        contextinstance.update(csrf(request))
        return render_to_response("delete_resource.html",  contextinstance)
    elif request.method == "POST":
        # Reloads db-stored data.
        sharkdata_core.ResourcesUtils().clear()
        #
        error_message = None # initially.
        #
        form = forms.DeleteResourceForm(request.POST)
        if form.is_valid():
            #
            user = request.POST['user']
            if user not in settings.APPS_VALID_USERS_AND_PASSWORDS_FOR_TEST.keys():
                error_message = 'Not a valid user. Please try again...'   
            #
            if error_message == None:
                if ('delete_ftp' in request.POST) and (request.POST['delete_ftp'] == 'on'):
                    logrow_id = admin_models.createLogRow(command = 'Delete resource (FTP)', status = 'RUNNING', user = user)
                    try:
                        sharkdata_core.ResourcesUtils().deleteFileFromFtp(resource.resource_file_name)
                        admin_models.changeLogRowStatus(logrow_id, status = 'FINISHED')
                    except:
                        error_message = u"Can't delete resources from the database."
                        admin_models.changeLogRowStatus(logrow_id, status = 'FAILED')
                        admin_models.addResultLog(logrow_id, result_log = error_message)
            #
            if error_message == None:
                logrow_id = admin_models.createLogRow(command = 'Delete resource (DB)', status = 'RUNNING', user = user)
                try:
                    resource = models.Resources.objects.get(id=resource_id)
                    resource.delete()
                    admin_models.changeLogRowStatus(logrow_id, status = 'FINISHED')
                except:
                    error_message = u"Can't delete resource from the database."
                    admin_models.changeLogRowStatus(logrow_id, status = 'FAILED')
                    admin_models.addResultLog(logrow_id, result_log = error_message)
            # OK.
            if error_message == None:
                return HttpResponseRedirect("/resources")
        #
        contextinstance = {'form'   : form,
                           'resource' : resource,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("delete_resource.html", contextinstance)
    # Not a valid request method.
    return HttpResponseRedirect("/resources")
示例#14
0
def deleteDataset(request, dataset_id):
    """ Deletes one row in the database. """
    dataset = models.Datasets.objects.get(id=dataset_id)
    #
    if request.method == "GET":
        form = forms.DeleteDatasetForm()
        contextinstance = {'form'   : form,
                           'dataset' : dataset,
                           'error_message' : None}
        contextinstance.update(csrf(request))
        return render_to_response("delete_dataset.html", contextinstance)
    elif request.method == "POST":
        error_message = None # initially.
        #
        form = forms.DeleteDatasetForm(request.POST)
        if form.is_valid():
            #
            user = request.POST['user']
            password = request.POST['password']
            if password != settings.APPS_VALID_USERS_AND_PASSWORDS_FOR_TEST.get(user, None):
                error_message = 'Not a valid user or password. Please try again...'   
            #
            if error_message == None:
                if ('delete_ftp' in request.POST) and (request.POST['delete_ftp'] == 'on'):
                    # Delete the marked dataset version. Earlier versions vill be used, if there are any. 
                    logrow_id = admin_models.createLogRow(command = 'Delete dataset (FTP)', status = 'RUNNING', user = user)
                    try:
                        error_message = sharkdata_core.DatasetUtils().deleteFileFromFtp(dataset.dataset_file_name)
                        error_message = sharkdata_core.DatasetUtils().writeLatestDatasetsInfoToDb(user)
                        admin_models.changeLogRowStatus(logrow_id, status = 'FINISHED')
                    except:
                        error_message = u"Can't delete dataset from the ftp."
                        admin_models.changeLogRowStatus(logrow_id, status = 'FAILED')
                        admin_models.addResultLog(logrow_id, result_log = error_message)
                else:
                    logrow_id = admin_models.createLogRow(command = 'Delete dataset (DB)', status = 'RUNNING', user = user)
                    try:
                        dataset = models.Datasets.objects.get(id=dataset_id)
                        dataset.delete()
                    except:
                        error_message = u"Can't delete dataset from the database."
                        admin_models.changeLogRowStatus(logrow_id, status = 'FAILED')
                        admin_models.addResultLog(logrow_id, result_log = error_message)
            # OK.
            if error_message == None:
                return HttpResponseRedirect("/datasets")
        #
        contextinstance = {'form'   : form,
                           'dataset' : dataset,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("delete_dataset.html", contextinstance)
    # Not a valid request method.
    return HttpResponseRedirect("/datasets")
示例#15
0
def deleteResources(request):
    """ Deletes all rows in the database. The FTP area is not affected. """
    error_message = None
    #
    if request.method == "GET":
        #
        form = forms.DeleteAllResourcesForm()
        contextinstance = {'form'   : form,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("resources_delete_all.html", contextinstance)
    elif request.method == "POST":
        # Reloads db-stored data.
        sharkdata_core.ResourcesUtils().clear()
        #
        form = forms.DeleteAllResourcesForm(request.POST)
        if form.is_valid():
            #
            user = request.POST['user']
            password = request.POST['password']
            if password != settings.APPS_VALID_USERS_AND_PASSWORDS_FOR_TEST.get(user, None):
                error_message = 'Not a valid user or password. Please try again...'   
            #
            if error_message == None:
                if ('delete_ftp' in request.POST) and (request.POST['delete_ftp'] == 'on'):
                    logrow_id = admin_models.createLogRow(command = 'Delete all resources (FTP)', status = 'RUNNING', user = user)
                    try:
                        sharkdata_core.ResourcesUtils().deleteAllFilesFromFtp()
                        admin_models.changeLogRowStatus(logrow_id, status = 'FINISHED')
                    except:
                        error_message = u"Can't delete resources from the database."
                        admin_models.changeLogRowStatus(logrow_id, status = 'FAILED')
                        admin_models.addResultLog(logrow_id, result_log = error_message)
            #
            if error_message == None:
                logrow_id = admin_models.createLogRow(command = 'Delete all resources (DB)', status = 'RUNNING', user = user)
                try:
                    resources_models.Resources.objects.all().delete()
                    admin_models.changeLogRowStatus(logrow_id, status = 'FINISHED')
                except:
                    error_message = u"Can't delete resources from the database."
                    admin_models.changeLogRowStatus(logrow_id, status = 'FAILED')
                    admin_models.addResultLog(logrow_id, result_log = error_message)
            # OK.
            if error_message == None:
                return HttpResponseRedirect("/sharkdataadmin")
        #
        contextinstance = {'form'   : form,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("resources_delete_all.html", contextinstance)
    # Not a valid request method.
    return HttpResponseRedirect("/sharkdataadmin")
示例#16
0
def generateIcesXml(request):
    """ Generates ICES-XML file. """
    error_message = None
    #
    if request.method == "GET":
        form = forms.GenerateIcesXmlForm()
        contextinstance = {'form'   : form,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("generate_ices_xml.html", contextinstance)
    elif request.method == "POST":
        #
        form = forms.GenerateIcesXmlForm(request.POST)
        if form.is_valid():
            #
            datatype_list = []
            year_from = request.POST['year_from']
            year_to = request.POST['year_to']
            status = request.POST['status']
            user = request.POST['user']
            password = request.POST['password']
            #
            if ('phytobenthos' in request.POST) and (request.POST['phytobenthos'] == 'on'):
                datatype_list.append('Phytobenthos')
            if ('phytoplankton' in request.POST) and (request.POST['phytoplankton'] == 'on'):
                datatype_list.append('Phytoplankton')
            if ('zoobenthos' in request.POST) and (request.POST['zoobenthos'] == 'on'):
                datatype_list.append('Zoobenthos')
            if ('zooplankton' in request.POST) and (request.POST['zooplankton'] == 'on'):
                datatype_list.append('Zooplankton')
            #
            if ('Phytobenthos' in datatype_list) or \
               ('Phytoplankton' in datatype_list) or \
               ('Zooplankton' in datatype_list):
                error_message = 'Support for Zoobenthos only, others are under development. Please try again...'   
            #
            if password != settings.APPS_VALID_USERS_AND_PASSWORDS_FOR_TEST.get(user, None):
                error_message = 'Not a valid user or password. Please try again...'   
            #
            if error_message == None:
                    sharkdata_core.SharkdataAdminUtils().generateIcesXmlInThread(
                                                    datatype_list, year_from, year_to, status, user)
            # OK.
            if error_message == None:
                return HttpResponseRedirect("/sharkdataadmin")
        #
        contextinstance = {'form'   : form,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("generate_ices_xml.html", contextinstance)
    # Not a valid request method.
    return HttpResponseRedirect("/sharkdataadmin")
示例#17
0
def autorespond_view(request):
    """List/update accounts and autoresponses."""

    if not request.user.is_authenticated():
        return redirect('logged_out')

    gcredentials = GoogleCredential.objects.filter(user=request.user)
    license = request.user.currentlicense.license

    if request.method == 'GET':
        autoresponds = AutoResponse.objects.filter(user=request.user)

        formset = AutoResponseFormSet(credentials=gcredentials, queryset=autoresponds)

        c = {
            'user': request.user,
            'is_active': license.is_active,
            'gcredentials': gcredentials,
            'autorespond_formset': formset,
        }
        c.update(csrf(request))

        return render_to_response('logged_in.html', c)

    elif request.method == 'POST':
        formset = AutoResponseFormSet(gcredentials, request.POST)
        if formset.is_valid():
            autoresponds = formset.save(commit=False)   # save_m2m if add many 2 many
            for autorespond in formset.deleted_objects:
                thread_pool.submit(_send_to_worker, 'post', "/stop/%s" % autorespond.id)
                autorespond.delete()
                report_ga_event_async(autorespond.credentials.email, category='autoresponse', action='delete')

            for autorespond in autoresponds:
                autorespond.user = request.user
                autorespond.save()
                thread_pool.submit(_send_to_worker, 'post', "/restart/%s" % autorespond.id)
                report_ga_event_async(autorespond.credentials.email, category='autoresponse', action='upsert')

            return redirect('autorespond')
        else:
            c = {
                'user': request.user,
                'is_active': license.is_active,
                'gcredentials': gcredentials,
                'autorespond_formset': formset,
            }
            c.update(csrf(request))

            return render_to_response('logged_in.html', c, status=400)
    else:
        return HttpResponseBadRequest()
示例#18
0
def deleteExportFiles(request):
    """ Deletes rows in the database. """
    error_message = None
    #
    if request.method == "GET":
        #
        form = forms.DeleteExportFilesForm()
        contextinstance = {'form'   : form,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("exportfiles_delete_all.html", contextinstance)
    elif request.method == "POST":
        #
        form = forms.DeleteExportFilesForm(request.POST)
        if form.is_valid():
            #
            user = request.POST['user']
            password = request.POST['password']
            if password != settings.APPS_VALID_USERS_AND_PASSWORDS_FOR_TEST.get(user, None):
                error_message = 'Not a valid user or password. Please try again...'   
            #
#             if error_message == None:
#                 if ('delete_ftp' in request.POST) and (request.POST['delete_ftp'] == 'on'):
#                     logrow_id = admin_models.createLogRow(command = 'Delete all datasets from FTP', status = 'RUNNING', user = user)
#                     try:
#                         error_message = dataset_utils.DatasetUtils().deleteAllFilesFromFtp()
#                         admin_models.changeLogRowStatus(logrow_id, status = 'FINISHED')
#                     except:
#                         error_message = u"Can't delete datasets from the FTP area."
#                         admin_models.changeLogRowStatus(logrow_id, status = 'FAILED')
#                         admin_models.addResultLog(logrow_id, result_log = error_message)
            #
            if error_message == None:
                logrow_id = admin_models.createLogRow(command = 'Delete all ICES-XML files from DB', status = 'RUNNING', user = user)
                try:
                    exportformats_models.ExportFiles.objects.all().delete()
                    admin_models.changeLogRowStatus(logrow_id, status = 'FINISHED')
                except:
                    error_message = u"Can't delete datasets from the database."
                    admin_models.changeLogRowStatus(logrow_id, status = 'FAILED')
                    admin_models.addResultLog(logrow_id, result_log = error_message)
            # OK.
            if error_message == None:
                return HttpResponseRedirect("/sharkdataadmin")
        #
        contextinstance = {'form'   : form,
                           'error_message' : error_message}
        contextinstance.update(csrf(request))
        return render_to_response("exportfiles_delete_all.html", contextinstance)
    # Not a valid request method.
    return HttpResponseRedirect("/sharkdataadmin")
示例#19
0
def batch_import_zfb_upload(request):
    if request.method == 'POST' and request.FILES:
        txtfile = request.FILES['txt_file']
        start_flag = False
        accountingDocuments = []
        account_fy = Account.objects.filter(account_type='FY')[:1].get()
        account_zc = Account.objects.filter(account_type='ZC')[:1].get()
        curr_user = User.objects.filter(sys_user=request.user)[:1].get()
        for line in txtfile:
            values = line.split(',')
            if start_flag and len(values) > 14:
                for i in range(0, len(values)):
                    values[i] = values[i].strip()
                if values[10] == '支出' and values[11] == '交易成功' and values[5] != '支付宝网站':
                    acc_doc = AccountingDocumentHeader()
                    acc_doc.creation_date = datetime.strptime(values[3], '%Y-%m-%d %H:%M:%S')
                    acc_doc.creator = curr_user
                    acc_doc.comment = values[8]

                    acc_item1 = AccountingDocumentItem()
                    acc_item1.dc_indicator = 'J'
                    acc_item1.amount = values[9]
                    acc_item1.document_header = acc_doc
                    acc_item1.account = account_fy

                    acc_item2 = AccountingDocumentItem()
                    acc_item2.dc_indicator = 'D'
                    acc_item2.amount = values[9]
                    acc_item2.document_header = acc_doc
                    acc_item2.account = account_zc

                    accountingDocuments.append({
                        'header': acc_doc,
                        'items': [acc_item1, acc_item2]
                    })
            for value in values:
                value = value.strip()
                if value == '交易号':
                    start_flag = True
                    break

        context = {}
        context.update(csrf(request))
        context['acc_docs'] = accountingDocuments
        return render_to_response(template_name='housefinance/batch_import/batch_import_zfb_step2.html', context=context)
    elif request.method == 'GET':
        context = {}
        context.update(csrf(request))
        return render_to_response(template_name='housefinance/batch_import/batch_import_zfb_step1.html', context=context)
示例#20
0
def _create_base_discussion_view_context(request, course_key):
    """
    Returns the default template context for rendering any discussion view.
    """
    user = request.user
    cc_user = cc.User.from_django_user(user)
    user_info = cc_user.to_dict()
    course = get_course_with_access(user, 'load', course_key, check_if_enrolled=True)
    course_settings = make_course_settings(course, user)
    uses_bootstrap = USE_BOOTSTRAP_FLAG.is_enabled()
    return {
        'csrf': csrf(request)['csrf_token'],
        'course': course,
        'user': user,
        'user_info': user_info,
        'staff_access': bool(has_access(user, 'staff', course)),
        'roles': utils.get_role_ids(course_key),
        'can_create_comment': has_permission(user, "create_comment", course.id),
        'can_create_subcomment': has_permission(user, "create_sub_comment", course.id),
        'can_create_thread': has_permission(user, "create_thread", course.id),
        'flag_moderator': bool(
            has_permission(user, 'openclose_thread', course.id) or
            has_access(user, 'staff', course)
        ),
        'course_settings': course_settings,
        'disable_courseware_js': True,
        'uses_bootstrap': uses_bootstrap,
        'uses_pattern_library': not uses_bootstrap,
    }
示例#21
0
文件: views.py 项目: in1gma/mysite
def show_master(request, master_id):
	args = {}
	args.update(csrf(request))
	#args['master'] = Master.objects.get(id = master_id)
	args['master'] = Master.objects.getById(master_id)
	args['form'] = MasterEditForm(instance = args['master'])
	return render_to_response('labbd2_master.html', args)
示例#22
0
文件: views.py 项目: in1gma/mysite
def show_client(request, client_id):
	args = {}
	args.update(csrf(request))
	#args['client'] = Client.objects.get(id = client_id)
	args['client'] = Client.objects.getById(client_id)
	args['form'] = ClientEditForm(instance = args['client'])
	return render_to_response('labbd2_client.html', args)
示例#23
0
文件: views.py 项目: in1gma/mysite
def show_edit_order(request, order_id):
	args = {}
	args.update(csrf(request))
	#args['order'] = Order.objects.get(id = order_id)
	args['order'] = Order.objects.getById(order_id)
	args['form'] = OrderEditForm(instance = args['order'])
	return render_to_response('labbd2_edit_order.html', args)
示例#24
0
def library(request):

    books = []
    for book in Book.objects.all():
        books.append(book)

    if request.method == 'POST':
        form = BookRequestForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('library_home'))
    else:
        form = BookRequestForm()

    hottest_titles = ['Pickup Lines... of Code', 'Say it With Ruby', 'Wooing Potential Employers', '50 Shades of Django']

    context = {
        'form': form.as_p(),
        'books': books,
        'hottest_titles': hottest_titles,
        'checkedout': 3,
    }
    context.update(csrf(request))

    return render_to_response(
        'library_home.html',
        context=context,

    )
示例#25
0
文件: views.py 项目: in1gma/mysite
def show_hairstyle(request, hairstyle_id):
	args = {}
	args.update(csrf(request))
	#args['hairstyle'] = Hairstyle.objects.get(id = hairstyle_id)
	args['hairstyle'] = Hairstyle.objects.getById(hairstyle_id)
	args['form'] = HairstyleEditForm(instance = args['hairstyle'])
	return render_to_response('labbd2_hairstyle.html', args)
示例#26
0
    def get(self, request, *args, **kwargs):
        form = ContactForm()
        args = {}
        args.update(csrf(request))
        args['form'] = form

        return render_to_response('pages/contact.html', args, RequestContext(request))
示例#27
0
文件: views.py 项目: echopen/kit-soft
def load(request):
    from_feed = request.GET.get('from_feed')
    page = request.GET.get('page')
    feed_source = request.GET.get('feed_source')
    all_feeds = Feed.get_feeds(from_feed)
    if feed_source != 'all':
        all_feeds = all_feeds.filter(user__id=feed_source)
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    try:
        feeds = paginator.page(page)
    except PageNotAnInteger:
        return HttpResponseBadRequest()
    except EmptyPage:
        feeds = []
    html = u''
    csrf_token = unicode(csrf(request)['csrf_token'])
    for feed in feeds:
        html = u'{0}{1}'.format(html,
                                render_to_string('feeds/partial_feed.html',
                                                 {
                                                    'feed': feed,
                                                    'user': request.user,
                                                    'csrf_token': csrf_token
                                                    }))

    return HttpResponse(html)
示例#28
0
def yournest(request):
    #Try if user is authenticated, if not authenticated redirect to /unauthorised
    if unreg(request.user.username) is True:
        return HttpResponseRedirect('/unauthorised')
    if not request.user.is_authenticated:
        return HttpResponseRedirect('/')
    try:
        if request.user.username == "chris":
            return HttpResponseRedirect('/chris')
    except:
        return HttpResponseRedirect('/')
        
    '''
    try:
        fullnamedict = {'full_name':request.user.username}
        yourdict = ordrd
        yourdict.update(ordernamedict)
    except:
        ordrd = {}
        yourdict = {}
    finally:
        yourdict.update(fullnamedict)
        yourdict.update(csrf(request))
        yourdict.update({'menulist':menulist})
    '''
    yourdict = {'menulist': ordermodel.objects.all(),
                'full_name': str(request.user.first_name + ' ' + request.user.last_name),
            }
    yourdict.update(csrf(request))
    return render(request, 'webapp/yournest.html', yourdict)
示例#29
0
文件: views.py 项目: k7-223UPP/upp
def registration(request):
    if request.user.is_authenticated():
        return redirect('access')
    args = {}
    args.update(csrf(request))
    args['form'] = UserCreationForm()
    if request.POST:
        newuser_form = UserCreationForm(request.POST)
        if len(request.POST.get('username')) < 6 or len(request.POST.get('username')) > 18 or not re.match(
                r'^[a-zA-Z0-9]+$', request.POST.get('username')):
            args['incorrect_login'] = "******"
            return render_to_response('registration/registration.html', args)
        if len(request.POST.get('password1')) < 6 or len(request.POST.get('password1')) > 18 or not re.match(
                r'^(?=[0-9+а-яА-ЯёЁa-zA-Z0-9]*(?=.*?\d).*)', request.POST.get('password1')):
            args['incorrect_password'] = "******"
            return render_to_response('registration/registration.html', args)
        if request.POST.get('password1') != request.POST.get('password2'):
            args['mismatch_passwords'] = "Пароли не совпадают"
            return render_to_response('registration/registration.html', args)
        if newuser_form.is_valid():
            newuser_form.save()
            auth.authenticate(username=newuser_form['username'], password=newuser_form['password1'])
            args['success_registration'] = "Поздравляем! Вы успешно зарегистрировались в системе!"
            return render_to_response('login/login.html', args)
        else:
            args['form'] = newuser_form
            args['non_unique_login'] = "******"
            return render_to_response('registration/registration.html', args)
    else:
        return render_to_response('registration/registration.html', args)
示例#30
0
def buy_now(request, id):
    if request.method == 'POST':
        print(request.POST)
        form = MakePaymentForm(request.POST)
        if form.is_valid():
            try:
                product = get_object_or_404(Products, pk=id)
                customer = stripe.Charge.create(
                    amount= int(product.price * 100),
                    currency="EUR",
                    description=product.name,
                    card=form.cleaned_data['stripe_id'],
                )
            except (stripe.error.CardError, e):
                messages.error(request, "Your card was declined!")

            if customer.paid:
                messages.success(request, "You have successfully paid")
                return redirect(reverse('products'))
            else:
                messages.error(request, "Unable to take payment")
        else:
            messages.error(request, "We were unable to take a payment with that card!")

    else:
        form = MakePaymentForm()
        product = get_object_or_404(Products, pk=id)

    args = {'form': form, 'publishable': settings.STRIPE_PUBLISHABLE_KEY, 'product': product}
    args.update(csrf(request))

    return render(request, 'pay.html', args)
示例#31
0
def index(request):
	context = {}
	context.update(csrf(request))
	return render(request, 'frontend/index.html', context)
示例#32
0
def thread(request, thread_id):
    thread_ = get_object_or_404(Thread, pk=thread_id)
    args = {'thread': thread_}
    args.update(csrf(request))
    return render(request, 'forum/thread.html', args)
示例#33
0
def session_view(request, project_id, session_id):
    project = get_object_or_404(Project, pk=project_id)
    session = get_object_or_404(Session, pk=session_id)

    # All results from this session
    results = Result.objects.filter(session=session)

    # Group the session's results by DBMS & workload
    dbmss = {}
    workloads = {}
    dbmss_ids = set()
    workloads_ids = set()
    for res in results:
        if res.dbms_id not in dbmss_ids:
            dbmss_ids.add(res.dbms_id)
            res_dbms = res.dbms
            dbmss[res_dbms.key] = res_dbms

        if res.workload_id not in workloads_ids:
            workloads_ids.add(res.workload_id)
            res_workload = res.workload
            workloads[res_workload.name] = set()
            workloads[res_workload.name].add(res_workload)

    # Sort so names will be ordered in the sidebar
    workloads = OrderedDict([(k, sorted(list(v)))
                             for k, v in sorted(workloads.items())])
    dbmss = OrderedDict(sorted(dbmss.items()))

    if len(workloads) > 0:
        # Set the default workload to whichever is first
        default_workload, default_confs = next(iter(list(workloads.items())))
        default_confs = ','.join([str(c.pk) for c in default_confs])
    else:
        # Set the default to display nothing if there are no results yet
        default_workload = 'show_none'
        default_confs = 'none'

    default_metrics = MetricCatalog.objects.get_default_metrics(
        session.target_objective)
    metric_meta = MetricCatalog.objects.get_metric_meta(
        session.dbms, session.target_objective)

    form_labels = Session.get_labels()
    form_labels['title'] = "Session Info"
    context = {
        'project': project,
        'dbmss': dbmss,
        'workloads': workloads,
        'results_per_page': [10, 50, 100, 500, 1000],
        'default_dbms': session.dbms.key,
        'default_results_per_page': 10,
        'default_equidistant': "on",
        'default_workload': default_workload,
        'defaultspe': default_confs,
        'metrics': list(metric_meta.keys()),
        'metric_meta': metric_meta,
        'default_metrics': default_metrics,
        'filters': [],
        'session': session,
        'results': results,
        'labels': form_labels,
    }
    context.update(csrf(request))
    return render(request, 'session.html', context)
示例#34
0
def profile_edit(request, username):
    # import ipdb; ipdb.set_trace()
    title = "Let us know you a little"

    instance = get_object_or_404(User, username=username)
    instance = UserProfile.objects.get(user=instance)
    if UserProfileInfo.objects.filter(userlink=instance).exists():
        instance = UserProfileInfo.objects.get(userlink=instance)
        if request.method == "GET":
            form = UserProfileInfoForm(request.POST or None,
                                       request.FILES or None,
                                       instance=instance)
            context = {
                "title": title,
                "form": form,
                "instance": instance,
            }
            context.update(csrf(request))
            return render(request, "userdetailsentry.html", context)
        else:

            user = request.user
            user = UserProfile.objects.get(user=user)
            form = UserProfileInfoForm(request.POST or None,
                                       request.FILES or None,
                                       instance=instance)
            if form.is_valid():
                instance = form.save(commit=False)

                instance.save()

            #print request.POST.get('full_name')
            #print request.POST.get('sex')
            context = {
                "instance": instance,
                "title": "thanks for telling us more about you.",
            }
            context.update(csrf(request))
            return HttpResponseRedirect("/users/%s/" % username)
    else:
        if request.method == "GET":
            form = UserProfileInfoForm(request.POST or None)
            context = {
                "title": "Please tell us something about you",
                "form": form,
                "instance": instance,
            }
        else:
            user = request.user
            user = UserProfile.objects.get(user=user)
            form = UserProfileInfoForm(request.POST, request.FILES or None)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.userlink = user
                instance.save()

            context = {
                "instance": instance,
                "title": "thanks for telling us more about you.",
            }
        context.update(csrf(request))
        return render(request, "userdetailsentry.html", context)

    context.update(csrf(request))
    return render(request, "user.html", context)
示例#35
0
def user(request, username):
    #import ipdb; ipdb.set_trace()

    if str(request.user) != "AnonymousUser":
        visitor = request.user
        visitor = UserProfile.objects.get(user=visitor)
        user = username
        user_name = UserProfile.objects.get(name=user)
        user = UserProfile.objects.get(name=user)
        cards = Cards.objects.all()
        user_cat = CategoryFollowers.objects.get(user=user_name)
        user_cat = user_cat.cat.all()
        cats = Categories.objects.all()[0:7]
        user_followers = Followers.objects.get(user=user_name)
        user_followers = user_followers.followed_by.all()
        user_journal = Journal.objects.get(user=user_name)
        show_cards = []
        for card in cards:
            if card.user.name == username:

                show_cards.append(card)
        #user_followed= Followers.objects.get(user=user)
        #user_following=request.user
        #user_following = UserProfile.objects.get(name=user_following)

        username = UserProfile.objects.get(name=user)
        if UserProfileInfo.objects.filter(userlink=user).exists():

            user = UserProfileInfo.objects.get(userlink=user)
            if user_name.follower.filter(followed_by=visitor).exists():
                follow_button = "unfollow"

            else:
                follow_button = "follow"
            #if user_followed.objects.filter(followed_by=user_following).exists():

            context = {
                'user': user,
                'username': username,
                'user_name': user_name,
                "follow_button": follow_button,
                "cards": show_cards,
                "user_cat": user_cat,
                "user_followers": user_followers,
                "cats": cats,
                'visitor': visitor,
            }
            context.update(csrf(request))
            return render(request, "user.html", context)
        else:
            title = "we dont know anything about you. please fill the details form"
            context = {'title': title}
    else:

        user = username
        user_name = UserProfile.objects.get(name=user)
        user = UserProfile.objects.get(name=user)
        cards = Cards.objects.all()
        user_cat = CategoryFollowers.objects.get(user=user_name)
        user_cat = user_cat.cat.all()
        user_followers = Followers.objects.get(user=user_name)
        user_followers = user_followers.followed_by.all()
        cats = Categories.objects.all()[0:7]
        show_cards = []
        for card in cards:
            if card.user.name == username:

                show_cards.append(card)
        #user_followed= Followers.objects.get(user=user)
        #user_following=request.user
        #user_following = UserProfile.objects.get(name=user_following)

        username = UserProfile.objects.get(name=user)
        if UserProfileInfo.objects.filter(userlink=user).exists():

            user = UserProfileInfo.objects.get(userlink=user)
            follow_button = "follow"
            #if user_followed.objects.filter(followed_by=user_following).exists():

            context = {
                'user': user,
                'username': username,
                "follow_button": follow_button,
                "cards": show_cards,
                "user_cat": user_cat,
                "user_followers": user_followers,
                "cats": cats,
            }
            context.update(csrf(request))
            return render(request, "user.html", context)
        else:
            title = "we dont know anything about you. please fill the details form"
            context = {'title': title}

    context.update(csrf(request))
    return render(request, "userdetailsentry.html", context)
示例#36
0
def logout(request):
    c = {}
    c.update(csrf(request))
    return render(request, 'login.html')
def signup(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('signup/signup.html', c)
示例#38
0
def changepassword(request):
    c1={}
    c1.update(csrf(request))
    return render_to_response('EmployeeChangepassword.html',c1)
示例#39
0
文件: views.py 项目: amelgmar/newblog
 def get(self, request, *args, **kwargs):
     self.object = self.get_object()
     ct = self.get_context_data()
     form_html = render_crispy_form(ct["form"], context=csrf(self.request))
     return JsonResponse({'html_form': form_html})
示例#40
0
                        return redirect(reverse('profile'))
                    else:
                        messages.error(request,
                                       "Sorry we are unable to log you in")
                else:
                    messages.error(
                        request,
                        "Sorry we are unable to take a payment with that card")
            except stripe.error.CardError, e:
                messages.error(request, "Your card was declined!")
    else:
        today = datetime.date.today()
        form = UserRegistrationForm()

    args = {'form': form, 'publishable': settings.STRIPE_PUBLISHABLE}
    args.update(csrf(request))

    return render(request, 'register.html', args)


@login_required(login_url='/accounts/login/')
def cancel_subscription(request):
    try:
        customer = stripe.Customer.retrieve(request.user.stripe_id)
        customer.cancel_subscription(at_period_end=True)
    except Exception, e:
        messages.error(request, e)
    return redirect('profile')


@csrf_exempt
示例#41
0
def electricitybill(request):
    c1={}
    c1.update(csrf(request))
    return render_to_response('electricitybill.html',c1)
示例#42
0
def login(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('login.html', c)
示例#43
0
    def _create_courseware_context(self, request):
        """
        Returns and creates the rendering context for the courseware.
        Also returns the table of contents for the courseware.
        """
        course_url_name = default_course_url_name(self.course.id)
        course_url = reverse(course_url_name,
                             kwargs={'course_id': unicode(self.course.id)})

        courseware_context = {
            'csrf':
            csrf(self.request)['csrf_token'],
            'course':
            self.course,
            'course_url':
            course_url,
            'chapter':
            self.chapter,
            'section':
            self.section,
            'init':
            '',
            'fragment':
            Fragment(),
            'staff_access':
            self.is_staff,
            'masquerade':
            self.masquerade,
            'supports_preview_menu':
            True,
            'studio_url':
            get_studio_url(self.course, 'course'),
            'xqa_server':
            settings.FEATURES.get('XQA_SERVER', "http://your_xqa_server.com"),
            'bookmarks_api_url':
            reverse('bookmarks'),
            'language_preference':
            self._get_language_preference(),
            'disable_optimizely':
            not WaffleSwitchNamespace('RET').is_enabled(
                'enable_optimizely_in_courseware'),
            'section_title':
            None,
            'sequence_title':
            None,
            'disable_accordion':
            COURSE_OUTLINE_PAGE_FLAG.is_enabled(self.course.id),
        }
        courseware_context.update(
            get_experiment_user_metadata_context(
                self.course,
                self.effective_user,
            ))
        table_of_contents = toc_for_course(
            self.effective_user,
            self.request,
            self.course,
            self.chapter_url_name,
            self.section_url_name,
            self.field_data_cache,
        )
        courseware_context['accordion'] = render_accordion(
            self.request,
            self.course,
            table_of_contents['chapters'],
        )

        courseware_context['course_sock_fragment'] = CourseSockFragmentView(
        ).render_to_fragment(request, course=self.course)

        # entrance exam data
        self._add_entrance_exam_to_context(courseware_context)

        # staff masquerading data
        if not check_course_open_for_learner(self.effective_user, self.course):
            # Disable student view button if user is staff and
            # course is not yet visible to students.
            courseware_context['disable_student_access'] = True
            courseware_context['supports_preview_menu'] = False

        if self.section:
            # chromeless data
            if self.section.chrome:
                chrome = [
                    s.strip() for s in self.section.chrome.lower().split(",")
                ]
                if 'accordion' not in chrome:
                    courseware_context['disable_accordion'] = True
                if 'tabs' not in chrome:
                    courseware_context['disable_tabs'] = True

            # default tab
            if self.section.default_tab:
                courseware_context['default_tab'] = self.section.default_tab

            # section data
            courseware_context[
                'section_title'] = self.section.display_name_with_default
            section_context = self._create_section_context(
                table_of_contents['previous_of_active_section'],
                table_of_contents['next_of_active_section'],
            )
            courseware_context['fragment'] = self.section.render(
                STUDENT_VIEW, section_context)
            if self.section.position and self.section.has_children:
                self._add_sequence_title_to_context(courseware_context)

        return courseware_context
示例#44
0
def new_registration2(request):
    c = {}
    c.update(csrf(request))
    return render(request, 'registration2.html', c)
def home_page(request):
    c = {}
    c.update(csrf(request))
    return render_to_response("Search_Engine/home_page.html", c)
示例#46
0
def new_certificate(request):
    c = {}
    c.update(csrf(request))
    AppId = request.session['AppId']
    request.session['AppId'] = AppId
    return redirect(request, 'certificate.html', {"AppId": AppId})
示例#47
0
def index(request):
    response = {}

    response.update(csrf(request))
    return render(request, 'usermedia/index.html', response)
示例#48
0
def about(request):
    c = {}
    c.update(csrf(request))
    return render(request, 'contact.html', c)
示例#49
0
def examcompleted(request):
    c = {}
    c.update(csrf(request))
    AppId = request.session['AppId']
    request.session['AppId'] = AppId
    return redirect(request, 'examcompleted.html', {"AppId": AppId})
示例#50
0
def certi(request):
    c = {}
    c.update(csrf(request))
    return render(request, 'certi.html')
示例#51
0
def paymenterror(request):
    c = {}
    c.update(csrf(request))
    return render(request, 'paymenterror', {"AppId": AppId})
示例#52
0
def welcome(request):
    c = {}
    c.update(csrf(request))
    AppId = request.session['AppId']
    request.session['AppId'] = AppId
    return render(request, 'welcome.html', {"AppId": AppId})
示例#53
0
文件: resources.py 项目: kdmsit/qmpy
def project_view(request, project_id):
    proj = Project.get(project_id)
    chart = {
        "running": proj.running.count(),
        "completed": proj.completed.count(),
        "failed": proj.failed.count(),
        "held": proj.held.count(),
        "waiting": proj.waiting.count(),
    }
    upcoming = proj.waiting
    if chart["waiting"] > 20:
        upcoming = upcoming[:20]

    if request.method == "POST":
        p = request.POST
        if "reset" in p:
            task_id = p.get("reset")
            task = Task.objects.get(id=task_id)
            for j in task.jobs:
                if j.state == 0:
                    j.delete()
            task.state = 0
            task.save()
            logger.info("Web reset: Task {}".format(task.id))
        elif "restartall" in p:
            for t in proj.running:
                if t.last_job_state != 1:
                    for j in t.jobs:
                        if j.state == 0:
                            j.delete()
                    t.state = 0
                    t.save()
                    logger.info("Web reset: Task {}".format(t.id))
        elif "reset_entry" in p:
            task_id = p.get("reset_entry")
            task = Task.objects.get(id=task_id)
            task.entry.reset()
            logger.info("Web reset: Entry {}".format(task.entry.id))
        else:
            if not "active" in p:
                proj.state = -2
            else:
                proj.state = 1
            proj.priority = p.get("priority", 50)
            proj.save()

            allocs = [
                k.split("_")[1] for k in list(p.keys())
                if "alloc_" in k and p.get(k) == "on"
            ]
            proj.allocations.set(allocs)

            users = [
                k.split("_")[1] for k in list(p.keys())
                if "user_" in k and p.get(k) == "on"
            ]
            proj.users.set([User.get(u) for u in users])

    allocs = get_marked_list(proj.allocations.all(), Allocation.objects.all())
    users = get_marked_list(proj.users.all(), User.objects.all())

    data = {
        "project": proj,
        "allocations": allocs,
        "users": users,
        "plot": construct_flot(chart),
        "upcoming": upcoming,
    }
    data.update(csrf(request))
    return render_to_response("computing/project.html", get_globals(data),
                              RequestContext(request))
示例#54
0
def payment(request):
    c = {}
    c.update(csrf(request))
    AppId = request.session['AppId']
    request.session['AppId'] = AppId
    return render(request, 'payment.html', {"AppId": AppId})
示例#55
0
def home(request):
    if request.method == 'POST':
        form = CDContentForm(request.POST)

        if form.is_valid():
            try:
                zipfile_name = '{}.zip'.format(datetime.now().strftime('%Y%m%d%H%M%S%f'))
                file_obj = open('{}cdimage/{}'.format(settings.MEDIA_ROOT, zipfile_name), 'w')
                archive = zipfile.ZipFile(file_obj, 'w', zipfile.ZIP_DEFLATED, allowZip64=True)
                selectedfoss = json.loads(request.POST.get('selected_foss', {}))
                all_foss_details = get_all_foss_details(selectedfoss)
                eng_rec = Language.objects.get(name="English")
                languages = set()

                for key, values in list(selectedfoss.items()):
                    foss_rec = FossCategory.objects.get(pk=key)
                    level = int(values[1])
                    eng_flag = True
                    srt_files = set()
                    common_files = set()

                    if str(eng_rec.id) in values[0]:
                        eng_flag = False

                    t_resource_qs = TutorialResource.objects.filter(Q(status=1) | Q(status=2),
                                                                    tutorial_detail__foss_id=key)

                    if level:
                        t_resource_qs = t_resource_qs.filter(tutorial_detail__level_id=level)

                    for value in values[0]:
                        language = Language.objects.get(pk=value)
                        add_sheets(archive, foss_rec, language)

                        tr_recs = t_resource_qs.filter(language_id=value).order_by(
                            'tutorial_detail__level', 'tutorial_detail__order', 'language__name')

                        languages.add(language.name)

                        for rec in tr_recs:
                            filepath = 'videos/{}/{}/{}'.format(key, rec.tutorial_detail_id, rec.video)
                             # get list of questions of a particular tutorial
                            question_s = Question.objects.filter(category=foss_rec.foss.replace(' ','-'),tutorial=rec.tutorial_detail.tutorial.replace(' ','-')).order_by('-date_created')


                            if os.path.isfile(settings.MEDIA_ROOT + filepath):
                                archive.write(settings.MEDIA_ROOT + filepath, 'spoken/' + filepath)

                            # add srt file to archive
                            add_srt_file(archive, rec, filepath, eng_flag, srt_files)

                            # collect common files
                            collect_common_files(rec, common_files)

                            tutorial_path = '{}/{}/'.format(rec.tutorial_detail.foss_id, rec.tutorial_detail_id)
                            filepath = 'spoken/videos/{}show-video-{}.html'.format(tutorial_path, rec.language.name)
                            ctx = {'tr_rec': rec, 'tr_recs': tr_recs,
                                   'media_path': settings.MEDIA_ROOT, 'tutorial_path': tutorial_path,'question_s': question_s}
                            convert_template_to_html_file(archive, filepath, request,
                                                          "cdcontent/templates/watch_tutorial.html", ctx)
                            # for each question find the answers
                            for question in question_s:
                                answer=Answer.objects.filter(question=question)
                                ctx = {'question': question, 'answer': answer}
                                filepath = 'spoken/videos/' + str(foss_rec.id) + '/' + str(rec.tutorial_detail_id) + '/answer-to-question-' + str(question.id) + '.html'
                                convert_template_to_html_file(archive, filepath, request, "cdcontent/templates/answer_to_question.html", ctx)




                        filepath = 'spoken/videos/' + str(foss_rec.id) + '/list-videos-' + language.name + '.html'
                        ctx = {'collection': tr_recs, 'foss_details': all_foss_details,
                               'foss': foss_rec.id, 'lang': language.id}
                        convert_template_to_html_file(archive, filepath, request,
                                                      "cdcontent/templates/tutorial_search.html", ctx)

                    # add common files for current foss
                    add_common_files(archive, common_files)

                # add side-by-side tutorials for selected languages
                languages = add_side_by_side_tutorials(archive, languages)

                ctx = {'foss_details': all_foss_details, 'foss': foss_rec.id,
                       'lang': language.id, 'languages': languages}
                convert_template_to_html_file(archive, 'spoken/videos/home.html', request,
                                              "cdcontent/templates/home.html", ctx)

                # add all required static files to archive
                add_static_files(archive)
                archive.close()

                file_obj.close()
                # wrapper = FileWrapper(temp)
                # response = HttpResponse(wrapper, content_type='application/zip')
                # response['Content-Disposition'] = 'attachment; filename=spoken-tutorial-cdcontent.zip'
                # response['Content-Length'] = temp.tell()
                # return response
                context = {'path': '/media/cdimage/{}'.format(zipfile_name), 'status': True}
            except Exception:
                context = {'path': '', 'status': False}
        return HttpResponse(json.dumps(context), content_type='application/json')
    else:
        form = CDContentForm()
    context = {
        'form': form
    }
    context.update(csrf(request))

    return render(request, "cdcontent/templates/cdcontent_home.html", context)
示例#56
0
 def widget(self):
     context = {'widget_id': self.id, 'widget_title': self.title, 'widget_icon': self.widget_icon,
                'widget_type': self.widget_type, 'form': self, 'widget': self}
     context.update(csrf(self.request))
     self.context(context)
     return loader.render_to_string(self.template, context)
示例#57
0
文件: views.py 项目: Aronja/Forum-App
def add_csrf(request, ** kwargs):
    d = dict(user=request.user, ** kwargs)
    d.update(csrf(request))
    return d
示例#58
0
def index(request):
    request.session['dash'] = 1
    request.session['emr'] = None
    request.session['profile'] = None
    request.session['messages'] = None

    request.session['name'] = None
    request.session['date'] = None
    request.session['start_time'] = None
    new_event_form = EventForm()
    now = datetime.date.today()
    year = now.year
    month = now.month
    cal = calendar.Calendar(calendar.SUNDAY)
    month_days = cal.monthdatescalendar(year, month)

    events = []
    times = [
        datetime.time(9, 00),
        datetime.time(9, 30),
        datetime.time(10, 00),
        datetime.time(10, 30),
        datetime.time(11, 00),
        datetime.time(11, 30),
        datetime.time(12, 00),
        datetime.time(12, 30),
        datetime.time(13, 00),
        datetime.time(13, 30),
        datetime.time(14, 00),
        datetime.time(14, 30),
        datetime.time(15, 00),
        datetime.time(15, 30),
        datetime.time(16, 00),
        datetime.time(16, 30),
        datetime.time(17, 00)
    ]
    if request.method == 'GET':
        for week in month_days:
            week_events = [
                (day,
                 Event.objects.filter(patient=request.user.patient,
                                      date=day).order_by('start_time'))
                for day in week
            ]
            events.append(week_events)
        args = {
            'events': events,
            'month': month,
            'year': year,
            'date': now,
            'month_days': month_days
        }
        args.update(csrf(request))
        args['new_event_form'] = new_event_form
        args['calendar_view'] = 'Monthly'
        args['times'] = times
        return render(request, 'patient_homepage/patient_homepage.html', args)
    elif request.method == 'POST':
        if request.POST['dob_month']:
            month = int(request.POST['dob_month'])
        if request.POST['dob_year']:
            year = int(request.POST['dob_year'])
        if request.POST['dob_day']:
            day = int(request.POST['dob_day'])
            chosen_day = day
        else:
            chosen_day = now.day
        try:
            chosen_day = datetime.date(year, month, chosen_day)
        except ValueError:
            for week in month_days:
                week_events = [
                    (day,
                     Event.objects.filter(patient=request.user.patient,
                                          date=day).order_by('start_time'))
                    for day in week
                ]
                events.append(week_events)
            args = {
                'events': events,
                'month': now.month,
                'year': now.year,
                'date': now,
                'month_days': month_days
            }
            args.update(csrf(request))
            args['new_event_form'] = new_event_form
            args['calendar_view'] = 'Monthly'
            args['times'] = times
            return render(request, 'patient_homepage/patient_homepage.html',
                          args)

        month_days = cal.monthdatescalendar(year, month)

        if not request.POST['calendar_view']:
            calendar_view = 'Monthly'
        else:
            calendar_view = request.POST['calendar_view']

        if calendar_view == 'Monthly':
            for week in month_days:
                week_events = [
                    (day,
                     Event.objects.filter(patient=request.user.patient,
                                          date=day).order_by('start_time'))
                    for day in week
                ]
                events.append(week_events)
        elif calendar_view == 'Weekly':
            for week in month_days:
                if chosen_day in week:
                    week_events = [
                        (day,
                         Event.objects.filter(patient=request.user.patient,
                                              date=day).order_by('start_time'))
                        for day in week
                    ]
                    events.append(week_events)
        elif calendar_view == 'Daily':
            for week in month_days:
                for day in week:
                    if day == chosen_day:
                        week_events = [(day,
                                        Event.objects.filter(
                                            patient=request.user.patient,
                                            date=day).order_by('start_time'))]
                        events.append(week_events)
        doctor_events = Event.objects.filter(
            doctor=request.user.patient.doctor,
            date=chosen_day).exclude(patient=request.user.patient)
        args = {
            'events': events,
            'month': month,
            'year': year,
            'date': chosen_day,
            'month_days': month_days
        }
        args.update(csrf(request))
        args['new_event_form'] = new_event_form
        args['calendar_view'] = calendar_view
        args['times'] = times
        args['doctor_events'] = doctor_events
        return render(request, 'patient_homepage/patient_homepage.html', args)
    return render(request, 'patient_homepage/patient_homepage.html')
示例#59
0
def addque(request):
    c = {}
    c.update(csrf(request))
    return render(request, "addque.html")
示例#60
0
def edit_user(request, pk):
    '''does the corresponding form validation and stores the edited details of administrator'''
    current_user = User.objects.get(pk=pk)
    if request.method == 'POST':
        if request.user.is_superuser or request.user == current_user:
            validate_user = UserForm(request.POST, instance=current_user)
            old_password = current_user.password
            if validate_user.is_valid():
                if old_password != request.POST.get('password'):
                    current_user.set_password(request.POST.get('password'))
                edit_user = validate_user.save(commit=False)
                edit_user.user_roles = request.POST.get('user_roles')
                if request.POST.get('user_roles') == 'Admin':
                    edit_user.is_admin = True
                    edit_user.is_superuser = True

                if request.POST.get('google_plus_url'):
                    edit_user.google_plus_url = request.POST.get('google_plus_url')
                else:
                    edit_user.google_plus_url = ''

                if request.POST.get('fb_profile'):
                    edit_user.fb_profile = request.POST.get('fb_profile')
                else:
                    edit_user.fb_profile = ''

                if request.POST.get('tw_profile'):
                    edit_user.tw_profile = request.POST.get('tw_profile')
                else:
                    edit_user.tw_profile = ''

                if request.POST.get('ln_profile'):
                    edit_user.ln_profile = request.POST.get('ln_profile')
                else:
                    edit_user.ln_profile = ''

                if request.POST.get('is_active', False):
                    edit_user.is_active = True

                if request.POST.get('is_special', False):
                    edit_user.is_special = True

                edit_user.save()

                data = {'error': False, 'message': 'updated successfully'}
            else:
                data = {'error': True, 'message': validate_user.errors}
            return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
        else:
            data = {'error': True, 'error_message': "You Dont have permission to edit."}
            return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
    else:
        if request.user.is_superuser or request.user == current_user:
            c = {}
            c.update(csrf(request))
            current_user = User.objects.get(pk=pk)
            user_roles = USER_ROLES
            return render(
                request,
                'admin/user/edit.html',
                {
                    'role_list': user_roles, 'edit_user': current_user, 'csrf_token': c['csrf_token']
                })
        else:
            return render(request, 'admin/accessdenied.html')