def CoursePlanChange(request,courseplanform,iid,pid):
    if(iid==-1):
        form=CoursePlanForm(deserialize_form(courseplanform))
    else:
        form=CoursePlanForm(deserialize_form(courseplanform),instance=CoursePlan.objects.get(pk=iid))

    status=0
    courseplan_html=''
    if form.is_valid():
        if pid== -1:
            practice=PracticeProfile.objects.get(userid=request.user)
        else:
            practice=PracticeProfile.objects.get(pk=pid)
        courseplan=form.save(commit=False)
        courseplan.course_practice=practice
        courseplan.save()
        courseplan_html=render_to_string("widgets/course_plan_table.html",{
            "course_plan_list":practice.courseplan_set.all()
        })
    else:
        status=1
    return simplejson.dumps({
        'status':status,
        'error_list':form.as_p(),
        'courseplan_html':courseplan_html
    })
Ejemplo n.º 2
0
def fileTimeLine(request,formHistory,profileForm,ci):
	""" Call the timeline generator """

	dajax = Dajax()

	try:	
		#check that the import belong to the clouditem
		cloudQuery = checkCloudItem(ci,request.user.id)
		jsonReport = openReport(cloudQuery)

		f = HistoryTimeLineForm(deserialize_form(formHistory))
		
		fProfile = ProfileSelectorForm(deserialize_form(profileForm))
		fProfile.setChoices(jsonReport)

		if f.is_valid() and fProfile.is_valid():
			bc = BrowserFileController(cloudQuery,fProfile.cleaned_data['choices'])
			res = bc.generateTimeLine(f.cleaned_data['domainFilter'])
			
			print type(f.cleaned_data['startDate'])
			print type(f.cleaned_data['endDate'])

			table = render_to_string("clouditem/browserTimeLine.html", {'events':res})
			dajax.assign("#historyShow","innerHTML",table)
			dajax.assign("#historyError","innerHTML","")
			dajax.remove_css_class("#historyError",['alert','alert-danger'])
		else:
			dajax.assign("#historyShow","innerHTML","")
			dajax.assign("#historyError","innerHTML","Invalid Form")
			dajax.add_css_class("#historyError",['alert','alert-danger'])
	except Exception as e:
		dajax.add_css_class("#historyError",['alert','alert-danger'])
		dajax.assign("#historyError","innerHTML",formatException(e))

	return dajax.json()
Ejemplo n.º 3
0
def TemplateNoticeChange(request,template_form,mod,page):
    if mod==-1:
        template_form=TemplateNoticeMessageForm(deserialize_form(template_form))
        template_form.save()
    else:
        template_notice=TemplateNoticeMessage.objects.get(pk=mod)
        f=TemplateNoticeMessageForm(deserialize_form(template_form),instance=template_notice)
        f.save()
    table=refresh_template_notice_table(request,page)
    ret={"status":'0',"message":u"模版消息添加成功","table":table}
    return simplejson.dumps(ret)
Ejemplo n.º 4
0
def fundBudget(request, form, remarkmentform,pid,max_budget,projectcode,is_submited = False):
    profundbudget = ProjectFundBudget.objects.get(project_id = pid)
    profundbudgetform = ProFundBudgetForm(deserialize_form(form),instance = profundbudget)
    profundbudgetremarkmentform = ProFundBudgetRemarkmentForm(deserialize_form(remarkmentform),instance = profundbudget)
    project = ProjectSingle.objects.get(project_id = pid )
    flag = False
    identity = request.session.get('auth_role', "")
    accessList = [ADMINSTAFF_USER,SCHOOL_USER,FINANCE_USER]
    if not check_input(max_budget) or not check_input(projectcode):
        message = ""
        if not check_input(max_budget):
            message += u"项目最大预算不能为空 "
        if not check_input(projectcode):
            message += u"项目编号不能为空 "
        #if not check_input(finance_account):
        #   message += u"项目财务编号不能为空 "
        ret = {'message':message,'flag':flag,}
        return simplejson.dumps(ret)
    if identity in accessList:
        project.project_budget_max = max_budget
    project.project_code = projectcode
    #project.finance_account = finance_account
    project.save()
    if profundbudgetform.is_valid():
        total_budget = float(profundbudgetform.cleaned_data["total_budget"])
        if total_budget < 0:
            message = u"数据未填写完整或数据格式不对,保存失败"
        else:
            laborcosts_budget = float(profundbudgetform.cleaned_data["laborcosts_budget"])
            if laborcosts_budget <= total_budget * 0.3:
                if total_budget <= project.project_budget_max:
                    profundbudgetform.save()
                    copyBudgetToFundsummary(pid)
                    if is_submited:
                        if profundbudgetremarkmentform.is_valid():
                            profundbudgetremarkmentform.save()
                            flag = True
                            message=u"保存成功"
                            status_confirm(request,project)
                        else:
                            message="预算说明为必填项"
                    else:
                        message=u"保存成功"
                else:
                    message = u"经费预算表总结额应低于项目最大预算金额,请仔细核实"
            else:
                message = u"劳务费应低于总结额的30%,请仔细核实"
    else:
        loginfo(p=profundbudgetform.errors,label='profundbudgetform.errors')
        message = u"数据未填写完整或数据格式不对,保存失败"
    # table = refresh_fundsummary_table(request,profundsummaryform,pid)
    ret = {'message':message,'flag':flag,'project_code':project.project_code,'project_budget_max':project.project_budget_max,}
    return simplejson.dumps(ret)
def CourseInfo(request,filter_form,form,uid,page):
    if uid == 0:
        courseForm = CourseForm(deserialize_form(form))
    else:
        course = Course.objects.get(id=uid)
        courseForm = CourseForm(deserialize_form(form),instance=course)
    if courseForm.is_valid():
        courseForm.save()
        table=refresh_course_table(filter_form,page)
        courseForm = CourseForm()
        form_html = render_to_string("widgets/course/course_form.html",{'course_form':courseForm})
        return simplejson.dumps({ 'status':'1', 'message':u"课程信息添加成功",'table':table,'form':form_html})
    else:
        form_html = render_to_string("widgets/course/course_form.html",{'course_form':courseForm})
        return simplejson.dumps({ 'status':'0', 'message':u"输入有误",'form':form_html})
Ejemplo n.º 6
0
def saveObjectName(request, object, form):

    # print "save*****"
    # print object
    form = ObjectForm(deserialize_form(form))

    Object = getObject(object)

    context = {
        'status': 1 , # 1: OK
                      # 2: blank
                      # 3: repeated

        'objects_table': "",
    }
    if form.is_valid():
        if Object.objects.filter(name = form.cleaned_data['name']):
            context['status'] = 3
        else :
            context['objects_table'] = refreshObjectTable(request, object)
            p = Object(name = form.cleaned_data['name'])
            p.save()
    else :
        context['status'] = 2
    return simplejson.dumps(context)
Ejemplo n.º 7
0
def text_send_form(request, form):
	print 'in text send form'
	query_string 	= ''
	found_entries 	= None
	dajax 			= Dajax()
	form 			= Text_Search_Form(deserialize_form(form))

	print 'errors'
	print form.errors
	
	# must do this to clean the form
	if form.is_valid():
		print 'form is valid'
		text 			= form.cleaned_data['target_text']
		query_string 	= text
		entry_query 	= get_query(query_string, ['title', 'category',])
		print entry_query
		found_entries 	= Offer.objects.filter(entry_query)
		items 			= land_page_pagination(page=1, items=found_entries)
		render 			= render_to_string('./parts/pagination_page2.html', {'items': items})
		dajax 			= Dajax()
		dajax.assign('#respo', 'innerHTML', render)
		return dajax.json()

	else:
		dajax.alert('error in form validation')

	return dajax.json()
Ejemplo n.º 8
0
def send_form(request, form):
	print 'in send form'
	dajax = Dajax()
	form = Search_Form(deserialize_form(form))

	print 'errors'
	print form.errors
	
	# must do this to clean the form
	if form.is_valid():

		print 	'form is valid'
		cars 	= make_query(form)
		items 	= land_page_pagination(page=1, items=cars)
		render 	= render_to_string('./parts/pagination_page2.html', {'items': items})

		
		dajax 	= Dajax()

		dajax.assign('#respo', 'innerHTML', render)
		# print(dir(dajax.json()))
		return dajax.json()

	else:
		dajax.alert('error in form validation')

	return dajax.json()
Ejemplo n.º 9
0
def send_form(request, form):
    dajax = Dajax()
    form = FormFront(deserialize_form(form))
    if form.is_valid():
        dajax.remove_css_class('#message_show', 'hidden')
        dajax.assign('#status', 'value', form)
    else:
        dajax.remove_css_class('#my_form p', 'error')
        # dajax.remove_css_class('#my_form .loading', 'hidden')
        # dajax.remove_css_class('#my_form p', 'error')
        dajax.remove_css_class('#status', 'hidden')
        # result = u'Отправляем сообщение'
        # dajax.assign('#status', 'value', result)
        # name = form.cleaned_data.get('name')
        # phone = form.cleaned_data.get('phone')
        # subject = u'Заявка waymy.ru'
        # message = u'Телефон: %s \n Имя: %s' % (phone, name)
        # send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False)
        # dajax.remove_css_class('#status', 'hidden')
        # result = u'Сообщение отправлено'
        # dajax.assign('#status', 'value', result)
        # dajax.remove_css_class('#message_show', 'hidden')
        # dajax.script('closemodal()')
        # dajax.redirect('/', delay=2000)
        # dajax.code('$(".close").click()')
    # for error in form.errors:
    #     dajax.add_css_class('#id_%s' % error, 'error')
    # dajax.add_css_class('div .loading', 'hidden')
    # dajax.alert("Form is_valid(), your phone is: %s" % form.cleaned_data.get('phone'))
    return dajax.json()
Ejemplo n.º 10
0
def calc_delivery(request, form):
    dajax = Dajax()
    form = DeliveryForm(deserialize_form(form))

    if form.is_valid():
        # обновляем доставку и сохраняем в базу
        radio = form.cleaned_data.get('delivery')
        current_delivery = get_current_delivery(request)
        current_delivery.delivery_type = radio
        current_delivery.save()

        current_delivery = get_delivery(request)
        current_delivery.save()

        total = cart_total(request)

        # обновляем инфу без преезагрузки
        dajax.assign('#type_ajax', 'innerHTML',
                     '%s' % current_delivery.delivery_type)
        dajax.assign('#weight_ajax', 'innerHTML',
                     '%s гр.' % current_delivery.weight)
        dajax.assign('#price_ajax', 'innerHTML',
                     '%s руб.' % current_delivery.delivery_price)
        dajax.assign('#price', 'innerHTML', 'ИТОГО: %s руб.' % total)

    return dajax.json()
Ejemplo n.º 11
0
def print_field(request, message, patient_id):
    dajax = Dajax()

    patient = Patient.objects.get(pk=int(patient_id))
    form = PatientForm_lite(deserialize_form(message), instance=patient)

    if form.is_valid():
        dajax.remove_css_class('#patient div', 'has-error')
        form.save()
        print patient.clinical_data.lower()
        for tag in TagDictionary.objects.all():
            print tag.word, tag.tag
            if tag.word in patient.clinical_data.lower():
                print 1, tag.word, tag.tag
                patient.tags.add(tag.tag)
        dajax.script("""$('#patient_tags').html('<p> %s</p>')
					""" % (', '.join(patient.tags.names())))

    else:
        dajax.remove_css_class('#patient div', 'has-error')
        for er_field, er_text in form.errors.items():
            dajax.script(
                """$('#id_%s').parent().parent().addClass('has-error');""" %
                er_field)

    #dajax.alert(field)
    return dajax.json()
Ejemplo n.º 12
0
def addScore(request, form, matchId, which_team):
    form = ScoreAddForm(deserialize_form(form))
    context = {}
    if form.is_valid():
        form.save()
        number = int(form.cleaned_data["number"])
        match = SingleMatch.objects.get(id=matchId)
        if which_team == 'A': match.teamA_score += number
        if which_team == 'B': match.teamB_score += number
        match.save()
        scores = getScores(request, match)
        form = ScoreAddForm()
        match_score_table = render_to_string("result/widget/score_record.html",
                                             {
                                                 "match": match,
                                                 "scores": scores,
                                                 "form": form,
                                             })
        context["statu"] = SUCCESS
        context["html"] = match_score_table
    else:
        print form
        #print form.errors
        context["statu"] = ERROR
    return simplejson.dumps(context)
Ejemplo n.º 13
0
def datastaticsChange(request,form,datastaticsid,pid,is_submited):

    datastaticsform = ProjectDatastaticsForm(deserialize_form(form))
    projectsingle = ProjectSingle.objects.get(project_id = pid)
    finalsubmit = FinalSubmit.objects.get(project_id=projectsingle)
    message=""
    if datastaticsform.is_valid():
        statics_num = datastaticsform.cleaned_data["statics_num"]
        staticstype = datastaticsform.cleaned_data["staticstype"]
        staticstype = StaticsTypeDict.objects.get(staticstype=staticstype)
        staticsdatatype = datastaticsform.cleaned_data["staticsdatatype"]
        staticsdatatype = StaticsDataTypeDict.objects.get(staticsdatatype=staticsdatatype)
        if datastaticsid == 0:
            new_staticsdata = ProjectStatistics(statics_num=statics_num,staticsdatatype=staticsdatatype,
                staticstype=staticstype,project_id=projectsingle)
            new_staticsdata.save()
            message = u"新的统计数据添加成功"
        else:
            old_staticsdata = ProjectStatistics.objects.get(content_id=datastaticsid)
            old_staticsdata.statics_num = statics_num
            old_staticsdata.staticstype = staticstype
            old_staticsdata.staticsdatatype = staticsdatatype
            old_staticsdata.save()
            message = u"修改成功"
    else:
        logger.info("datastaticsform Valid Failed"+"**"*10)
        logger.info(datastaticsform.errors)
        message = u"数据没有填完整,请重新填写"
    table = refresh_datastatics_table(request,pid,is_submited) 
    ret={'table':table,'message':message,}
    return simplejson.dumps(ret)
Ejemplo n.º 14
0
def get_filter_data(filter_form):
    course_filter_form = CourseFilterForm(deserialize_form(filter_form))
    if course_filter_form.is_valid():
        classes = course_filter_form.cleaned_data['classes']
        terms = course_filter_form.cleaned_data['terms']
        grades = course_filter_form.cleaned_data['grades']
        years = course_filter_form.cleaned_data['years']
        if classes == '-1':
            classes = ''
        if terms == '-1':
            terms = ''
        if grades == '-1':
            grades = ''
        if years == '-1':
            years = ''
        q0 = (classes
              and Q(course_id__course_practice__nick_name=classes)) or None
        q1 = (terms and Q(course_id__course_term=terms)) or None
        q2 = (grades and Q(course_id__course_grade=grades)) or None
        q3 = (years and Q(start_year=years)) or None
        qset = filter(lambda x: x != None, [q0, q1, q2, q3])
        if qset:
            qset = reduce(lambda x, y: x & y, qset)
            course_list = Course.objects.filter(qset)
        else:
            course_list = Course.objects.all()
        return course_list
    course_list = Course.objects.all()
    return course_list
Ejemplo n.º 15
0
def EditTeacher(request, form, teacherid):
    editform = TeacherAddForm(deserialize_form(form))
    if editform.is_valid():
        data = editform.cleaned_data
        teacher = TeacherProfile.objects.get(teacher_id=teacherid)
        # teacher.teacher_id=data['baseinfo_teacherid']
        teacher.teacher_name = data['baseinfo_name']
        smallclass = SmallClass.objects.get(id=data['small_class'])
        teacher.small_class = smallclass
        teacher.teacher_email = data['teacher_email']
        teacher.teacher_telephone = data['teacher_telephone']
        teacher.office_phone = data['office_phone']
        teacher.office_address = data['office_address']
        teacher.save()
        message = "修改成功"
    else:
        print "---------------------------"
        print editform.errors
        message = "请正确输入信息"
    teacherlist = TeacherProfile.objects.all()
    teacherlist_html = render_to_string('widgets/teacherlist.html',
                                        {'teacherlist': teacherlist})
    context = {
        'message': message,
        'teacherlist_html': teacherlist_html,
    }
    return simplejson.dumps(context)
Ejemplo n.º 16
0
def schedule_form_data(request ,userauth="" ,form="",page=1,page2=1,search=0):
    ProjectJudge_form=ProjectJudgeForm()
    has_data = False
    schedule_form=ScheduleBaseForm(request=request)
    if search == 1:
        schedule_form = ScheduleBaseForm(deserialize_form(form))
        pro_list=get_search_data(request,schedule_form)
        default=False
    else:
        pro_list=get_project_list(request)
        default=True
    param=getParam(pro_list,userauth,default,page,page2)
    context ={ 'schedule_form':schedule_form,
               'has_data': has_data,
               'usercontext': userauth,
               'ProjectJudge_form':ProjectJudge_form,
               "approve":PROJECT_STATUS_APPLICATION_EXPERT_SUBJECT,
               "review":PROJECT_STATUS_FINAL_EXPERT_SUBJECT,
               "page":page,
               "page2":page2,
               'EXCELTYPE_DICT':EXCELTYPE_DICT_OBJECT(),
    }
    if  userauth['role']!="adminStaff":
        context.update({'show':1})
    context.update(param)
    return context
Ejemplo n.º 17
0
Archivo: ajax.py Proyecto: oosprey/ERP
def generateWorkOrder(request, pid, form):
    print "====="
    print pid
    print form
    product = Product.objects.get(id=pid)
    if product.manufacture_file_up and product.manufacture_file_up.is_approval == 0 and product.techdata_file_up and product.techdata_file_up.is_approval == 0 and product.purchasing_file_up and product.purchasing_file_up.is_approval == 0:
        form = WorkOrderGenerateForm(deserialize_form(form))
        if form.is_valid():
            workorder = form.save(commit=False)
            workorder.product_name = product.name
            workorder.save()

            techdataOrderInitialize(workorder)

            product.is_approval = 0
            product.save()
            return simplejson.dumps({"status": "ok"})
        else:
            context = {
                "form": form,
            }
            html = render_to_string("sell/widgets/workorderGenerate_form.html",
                                    context)
            return simplejson.dumps({"html": html, "status": "invalid"})
    else:
        return simplejson.dumps({"status": "err"})
Ejemplo n.º 18
0
def AddTeacher(request, form):
    teacher_form = TeacherAddForm(deserialize_form(form))
    if teacher_form.is_valid():
        data = teacher_form.cleaned_data
        name = data['baseinfo_name']
        teacherid = data['baseinfo_teacherid']
        smallclass = data['small_class']
        if not isteacherExist(teacherid.strip()):
            create_teacher(name, teacherid, smallclass)
            message = '人员添加成功'
            status = '1'
        else:
            print "hello"
            message = '教师已存在'
            status = '0'
        ret = {
            'status': status,
            'message': message,
        }
    else:
        return simplejson.dumps({
            'status': "2",
            'message': '输入有误,请重新输入',
            'error_id': teacher_form.errors.keys(),
        })
    return simplejson.dumps(ret)
Ejemplo n.º 19
0
def refresh_user_table(request,identity,search_form="",page=1):
    try:
        form = SearchForm(deserialize_form(search_form))
        if form.is_valid():
            name = form.cleaned_data['name']
    except:
        name = ""

    if identity == SCHOOL_USER:
        school_users = SchoolProfile.objects.filter(Q(userid__first_name__contains = name))
        context=getContext(school_users, page, "item")
        return render_to_string("widgets/dispatch/school_user_table.html",
                                context)
    elif identity == COLLEGE_USER:
        college_users = CollegeProfile.objects.filter(Q(userid__first_name__contains = name))
        context=getContext(college_users, page, "item2")
        return render_to_string("widgets/dispatch/college_user_table.html",
                                context)
    elif identity == TEACHER_USER:
         colleges = getCollege(request)
         qset = reduce(lambda x,y:x|y,[Q(college = _college) for _college in colleges])
         users = TeacherProfile.objects.filter(qset).filter(Q(userid__first_name__contains = name)).order_by('college')
         context=getContext(users, page, "item")
         return render_to_string("widgets/dispatch/teacher_user_table.html",
                                context)
    elif identity == EXPERT_USER:
        users = ExpertProfile.objects.filter(Q(userid__first_name__contains = name)).order_by('college')
        context=getContext(users, page, "item3")
        return render_to_string("widgets/dispatch/expert_user_table.html",
                                context)
Ejemplo n.º 20
0
def guardar_declaracion_transporte(request, formulario, transportePorDia, fechaPeriodoInicio, fechaPeriodoFin):# Método que recibe el formulario de endoso obtenido de endoso.html y lo deserializa para obtener la información de sus controles y lo valida con EndosoForm, si la información es valida guarda los datos y limpia los controles del formulario mediante una función de js.
    dajax = Dajax()
        
    if transportePorDia == '':
        list_transporte = ''
    else:        
        array_convertido_string = simplejson.dumps(transportePorDia, separators=('|',','))
        list_transporte = array_convertido_string.replace('[', '').replace(']', '').replace('"', '').split(';')
                      
    formulario_deserializado = deserialize_form(formulario)
    
    if formulario_deserializado.get('varIdDeclaracionTransporte') == '':
                 
        fechaDeclaracionTransporte = datetime.datetime.now()
        declaracionTransporteGuardar = DeclaracionTransporte(Fecha = fechaDeclaracionTransporte, PeriodoInicio = datetime.datetime.strptime(fechaPeriodoInicio,'%d/%m/%Y').strftime('%Y-%m-%d'),
                                PeriodoFin = datetime.datetime.strptime(fechaPeriodoFin,'%d/%m/%Y').strftime('%Y-%m-%d'), 
                                DescripcionBienAsegurado = formulario_deserializado.get('txtDescripcionBienAsegurado').upper(), Observaciones = formulario_deserializado.get('txtObservaciones').upper(),
                                Constancia_id = formulario_deserializado.get('varIdConstancia'), CierreMes = 0, DeclaracionNueva = 0, IdStatusDeclaracion = 1)
        
        declaracionTransporteGuardar.save()   
        
        Constancia.objects.filter(IdConstancia=formulario_deserializado.get('varIdConstancia')).update(UtilizadoDeclaracion=1)
        
        if str(formulario_deserializado.get('varIdDeclaracionTransporteAnterior')) != "":            
            DeclaracionTransporte.objects.filter(IdDeclaracionTransporte=formulario_deserializado.get('varIdDeclaracionTransporteAnterior')).update(DeclaracionNueva=1)        
                    
        if list_transporte != '':
            guardar_declaracion_transporte_por_dia(list_transporte, declaracionTransporteGuardar.IdDeclaracionTransporte)     
                
        dajax.add_data(declaracionTransporteGuardar.IdDeclaracionTransporte, 'mensajeDeclaracionTransporte')
    
    else:
        actualizar_declaracion_transporte(formulario_deserializado, list_transporte, fechaPeriodoInicio, fechaPeriodoFin) 
         
    return dajax.json()
Ejemplo n.º 21
0
def save_tree(request, treeform):
    dajax = Dajax()
    form_dic = deserialize_form(treeform)
    topic_id_list=[]
    root = request.user.user_root.root_topic
        
    for key, value in form_dic.iteritems():     
        if 'root' in key:
            if value=='1':
                abstract_root = Topic.objects.get(pk = int(key[4:]))
                # prevent error
                if abstract_root.is_reserved():
                    branch_root = Topic.objects.create(name=abstract_root.name,encode=abstract_root.encode,weight=abstract_root.weight,related_topic=abstract_root)
                    # Add branch root to the course root
                    branch_root.parent_topic.add(root)
                    branch_root.root_topic.add(root)
                    branch_root.save()
            else:
                dajax.alert('Nothing is picked')
                return dajax.json()   
        if 'topic' in key and value=='1':
            topic_id_list.append(int(key[5:]))      
            progress, created = ProgressMeasurement.objects.get_or_create(user = request.user, topic_id = int(key[5:]))  
    if len(topic_id_list) and (not abstract_root.is_leaf()):
        parent_child_relation(abstract_root, branch_root, topic_id_list)    
    
    dajax.redirect('/qb/myprogress/', delay=2000)   
    
    return dajax.json() 
Ejemplo n.º 22
0
def ajax_comment(request,form,pk):
    if request.method =='POST':
        form=BKCommentForm(deserialize_form(form))
        bookmark = get_object_or_404(Bookmark, pk=pk)
        if form.is_valid():
            c = form.save(commit=False)
            c.bookmark = bookmark
            c.created_by = request.user
            c.save()
            bookmark.update_num_replies()
            num_replies=bookmark.num_replies
            return simplejson.dumps({'status':'Success','message':[bookmark.pk,num_replies]})
        else:
            #dajax.remove_css_class('#signin_form input', 'error')
            #for error in form.errors:
            #    dajax.add_css_class('#id_%s' % error, 'error')
            html = render(request, 'authapi/comment.html', {'form':form,'bk':bookmark})
            return simplejson.dumps({'status':'Error','message':html.content})
    
    if request.method == 'GET':
        if request.user.is_authenticated():
            bookmark = get_object_or_404(Bookmark, pk=pk)
            form = BKCommentForm()
            html = render(request, 'authapi/comment.html', {'form':form,'bk':bookmark})
            return simplejson.dumps({'message':html.content})    
        else:
            request.session['Tip']=u'   you are anonymous,Please login!'
            return ajax_login(request,form)
Ejemplo n.º 23
0
def MemberChangeInfo(request, form, origin):
    loginfo(p=origin, label="origin")
    try:
        project = ProjectSingle.objects.get(student__user_id=request.user)
    except:
        raise Http404
    stugroup_form = StudentGroupInfoForm(deserialize_form(form))
    loginfo(p=stugroup_form, label="stugroup_form")
    if not stugroup_form.is_valid():
        ret = {'status': '1', 'message': u"输入有误,请重新输入"}
    else:
        email = stugroup_form.cleaned_data["email"]
        telephone = stugroup_form.cleaned_data["telephone"]
        classInfo = stugroup_form.cleaned_data["classInfo"]
        student_id = stugroup_form.cleaned_data["student_id"]
        group = project.student_group_set
        for student in group.all():
            if student.studentId == origin:
                print "save successfully"
                student.email = email
                student.telephone = telephone
                student.classInfo = classInfo
                student.studentId = student_id
                student.save()
                table = refresh_member_table(request)
                ret = {'status': '0', 'message': u"人员变更成功", 'table': table}
                break
        else:
            ret = {'status': '1', 'message': u"该成员不存在,请刷新页面"}
    return simplejson.dumps(ret)
Ejemplo n.º 24
0
def send_daemon_form(request, form):
    dajax = Dajax()
    form = DaemonControlsForm(deserialize_form(form))
    if form.is_valid():
        for field in form.fields:
            dajax.assign('#%s_error' % field, 'innerHTML', '')
        daemon_temp = Daemon(60, 'ERROR')
        if daemon_temp.status() == 1:
            daemon_temp.stop()
            dajax.remove_css_class('#daemon_status', 'running')
            dajax.add_css_class('#daemon_status', 'stopped')
            dajax.assign("#daemon_status", "innerHTML", "Not running")
        else:
            dajax.remove_css_class('#daemon_status', 'stopped')
            dajax.add_css_class('#daemon_status', 'running')
            dajax.assign("#daemon_status", "innerHTML", "Running")
            timeout = form.cleaned_data['timeout']
            loglevel = form.cleaned_data['loglevel']
            output_dir = form.cleaned_data['output_dir']
            cmd = './loaderd.py start -t %s -o %s --loglevel %s' % (
                timeout, output_dir, loglevel
            )
            subprocess.Popen(cmd.split(), cwd=DAEMON_PATH)
    else:
        for error in form.errors.items():
            dajax.assign('#%s_error' % error[0], 'innerHTML', error[1])
    return dajax.json()
Ejemplo n.º 25
0
def add_new_words(request, form):
    user = get_user(request)
#     dajax=Dajax()
    form = JapaneseWordForm(deserialize_form(form))
    if form.is_valid():
        word = form.save(commit=False)
        if len(JapaneseWord.objects.filter(source=word.source, mean=word.mean )):
            # TODO show error
            return None
        word.user = user
        word.temp = True
        word.save()
        add_word_session, created = AddWordSession.objects.get_or_create(current=True, active=True, user=user)
        if created:
            add_word_session.save()
        add_word_session.japanese_words.add(word)
        return render(request, 'japanstudy/new-word-ajax.html', {'word':word, })
#         dajax.remove_css_class('#addJPWords', 'success')
        # TODO
    else:
#         dajax.remove_css_class('#addJPWords', 'error')
        for error in form.errors:
            # TODO
            pass
#             dajax.add_css_class('#%s' % error, 'error')
        return None
Ejemplo n.º 26
0
def print_field(request, message, patient_id):
    dajax = Dajax()

    patient = Patient.objects.get(pk=int(patient_id))
    form = PatientForm_lite(deserialize_form(message),
                            instance=patient)

    if form.is_valid():
        dajax.remove_css_class('#patient div', 'has-error')
        form.save()
        print patient.clinical_data.lower()
        for tag in TagDictionary.objects.all():
            print tag.word, tag.tag
            if tag.word in patient.clinical_data.lower():
                print 1, tag.word, tag.tag
                patient.tags.add(tag.tag)
        dajax.script("""$('#patient_tags').html('<p> %s</p>')
					""" % (', '.join(patient.tags.names())))

    else:
        dajax.remove_css_class('#patient div', 'has-error')
        for er_field, er_text in form.errors.items():
            dajax.script("""$('#id_%s').parent().parent().addClass('has-error');"""
                         % er_field)





    #dajax.alert(field)
    return dajax.json()
Ejemplo n.º 27
0
def bug_form_submit(request, form):
    dajax = Dajax()
    form = BugForm(deserialize_form(form))
    if form.is_valid():
        dajax.remove_css_class('#bug-form input', 'error')
        dajax.remove_css_class('#bug-form select', 'error')
        dajax.remove_css_class('#bug-form textarea', 'error')
        dajax.remove('.error-message')
        dajax.alert('Forms valid')
    else:
        dajax.remove_css_class('#bug-form input', 'error')
        dajax.remove_css_class('#bug-form select', 'error')
        dajax.remove_css_class('#bug-form textarea', 'error')
        dajax.remove('.error-message')
        for error in form.errors:
            dajax.add_css_class('#id_{0}'.format(error), 'error')
        for field in form:
            for error in field.errors:
                message = '<div class="error-message">* {0}</div>'.format(
                    error)
                dajax.append('#id_{0}_wrapper'.format(field.name), 'innerHTML',
                             message)
        # non field errors
        if form.non_field_errors():
            message = '<div class="error-message"><small>{0}</small></div>'.format(
                form.non_field_errors())
            dajax.append('#non-field-errors', 'innerHTML', message)
    return dajax.json()
Ejemplo n.º 28
0
def guardar_endoso(request, formulario, endoso):# Método que recibe el formulario de endoso obtenido de endosodeclaracion.html y lo deserializa para obtener la información de sus controles y lo valida con EndosoForm, si la información es valida guarda los datos y limpia los controles del formulario mediante una función de js.
    dajax = Dajax()
    
    if endoso == '':
        list_endoso = ''
    else:        
        array_convertido_string = simplejson.dumps(endoso, separators=('|',','))
        list_endoso = array_convertido_string.replace('[', '').replace(']', '').replace('"', '').split(';')
                      
    formulario_deserializado = deserialize_form(formulario)
    
    if list_endoso != '':
        
        endoso = list_endoso[0].split(',')
        endosoAGuardar = Endoso(BienesAsegurados = Decimal(endoso[0]), SumaAsegurada = Decimal(endoso[1]),
                                PorcentajeFondo = Decimal(endoso[2]), ImporteFondo = Decimal(endoso[3]),
                                PorcentajeReaseguro = Decimal(endoso[4]), ImporteReaseguro = Decimal(endoso[5]),
                                PorcentajeTotal = Decimal(endoso[6]), ImporteTotal = Decimal(endoso[7]), 
                                DeclaracionEndoso_id = formulario_deserializado.get('varIdDeclaracionEndoso'))
    
        endosoAGuardar.save()
        
        dajax.add_data(endosoAGuardar.IdEndoso, 'mensajeEndoso')
         
    return dajax.json()
Ejemplo n.º 29
0
def save_course_tree(request,tree_name, course_id,treeform):
    dajax = Dajax()
    form_dic = deserialize_form(treeform)
    topic_id_list=[]
    try:
        course = Course.objects.get(id = course_id)
        if not request.user.is_staff:
            dajax.alert('Sorry, you do not have the permission to do the action')
            return dajax.json()
        for key, value in form_dic.iteritems():     
            if 'root' in key:
                if value=='1':
                    abstract_root = Topic.objects.get(pk = int(key[4:]))
                    # prevent error
                    if abstract_root.is_reserved():
                        branch_root = Topic.objects.create(name=abstract_root.name,encode=abstract_root.encode,weight=abstract_root.weight,related_topic=abstract_root)
                        # Add branch root to the course root
                        branch_root.parent_topic.add(course.knowledge_tree_root)
                        branch_root.root_topic.add(course.knowledge_tree_root)
                        branch_root.save()
                else:
                    dajax.alert('Nothing is picked')
                    return dajax.json()   
            if 'topic' in key and value=='1':
                topic_id_list.append(int(key[5:]))        
        if len(topic_id_list) and (not abstract_root.is_leaf()):
            parent_child_relation(abstract_root, branch_root, topic_id_list)    
        dajax.redirect('/qb/view/'+str(course.knowledge_tree_root.id)+'/', delay=2000)   
    except Course.DoesNotExist:
        dajax.alert('Some Error')
    
    return dajax.json()  
Ejemplo n.º 30
0
def signin_form(request, form):
    dajax = Dajax()
    form = AuthenticationForm(deserialize_form(form))
    form_id = 'aform'

    try:
        dajax.remove_css_class('#'+form_id+' input', 'error')
        dajax.script('form_errors(false,"{0}");'.format(form_id))
        if not form.is_valid():
            raise Exception('Error')

        identification, password, remember_me = (form.cleaned_data['identification'],
                                                 form.cleaned_data['password'],
                                                 form.cleaned_data['remember_me'])
        user = authenticate(identification=identification, password=password)
        if user.is_active:
            login(request, user)
            if remember_me:
                request.session.set_expiry(userena_settings.USERENA_REMEMBER_ME_DAYS[1] * 86400)
            else:
                request.session.set_expiry(0)

            dajax.script('update_sign_in({0},"{1}");'.format(user.id,user.username))
    except Exception as e:
        dajax.remove_css_class('#'+form_id+' input', 'error')
        print e
        dajax.script("form_errors(true,'{0}','{1}<br>{2}');".format(form_id,e.message,form.errors))
        for error in form.errors:
            dajax.add_css_class('#'+form_id+' #id_%s' % error, 'error')

    return dajax.json()
Ejemplo n.º 31
0
def AllocEmail(request,form,param):
    form = EmailForm(deserialize_form(form),request=request)
    if form.is_valid():
        try:
            if param in TYPE_ALLOC:
                proj_list = ProjectSingle.objects.filter(Q(project_special=form.cleaned_data['special']) & Q(project_status__status = PROJECT_STATUS_APPLICATION_EXPERT_SUBJECT))
            elif param in TYPE_FINAL_ALLOC:
                proj_list = ProjectSingle.objects.filter(Q(project_special=form.cleaned_data['special']) & Q(project_status__status = PROJECT_STATUS_FINAL_EXPERT_SUBJECT))
            else:
                raise ValueError('')
        except:
            return simplejson.dumps({ 'status':'2', 'message':u"发送失败"})
        if 1:
            recipient_list=[]
            expert_group=[]
            for project in proj_list:
                print project
                p_e_group=Re_Project_Expert.objects.filter(project=project)
                expert_group.extend([item.expert for item in p_e_group])
            loginfo(len(expert_group))
            expert_group=list(set(expert_group))
            loginfo(len(expert_group))
            recipient_list.extend([item.userid.email for item in expert_group])
            send_mail(form.cleaned_data["mail_title"],form.cleaned_data["mail_content"],settings.DEFAULT_FROM_EMAIL,recipient_list)
            return simplejson.dumps({ 'status':'1', 'message':u"专家发送完成"})
    else:
        return simplejson.dumps({ 'status':'0', 'message':u"发送失败",'table':refresh_alloc_email_form(form)})
Ejemplo n.º 32
0
def achivementChange(request,form,achivementid,pid,is_submited):

    achivementform = ProjectAchivementForm(deserialize_form(form))
    projectsingle = ProjectSingle.objects.get(project_id=pid)
    finalsubmit = FinalSubmit.objects.get(project_id = projectsingle)
    message=""
    if achivementform.is_valid():
        achivementtitle = achivementform.cleaned_data["achivementtitle"]
        mainmember = achivementform.cleaned_data["mainmember"]
        introduction = achivementform.cleaned_data["introduction"]
        remarks = achivementform.cleaned_data["remarks"]
        achivementtype = achivementform.cleaned_data["achivementtype"]
        achivementtype=AchivementTypeDict.objects.get(achivementtype=achivementtype)
        if achivementid == 0:
            new_achivement = ProjectAchivement(achivementtitle=achivementtitle,mainmember=achivementtitle,introduction=introduction,remarks=remarks,
                achivementtype=achivementtype,project_id=projectsingle)
            new_achivement.save()
            message = u"新的研究成果添加成功"
            loginfo(p=achivementtitle,label="achivementtitle")
        else:
            old_achivement = ProjectAchivement.objects.get(content_id=achivementid)
            old_achivement.achivementtitle = achivementtitle
            old_achivement.mainmember = mainmember
            old_achivement.introduction = introduction
            old_achivement.remarks = remarks
            old_achivement.achivementtype = achivementtype
            old_achivement.save()
            message = u"修改成功"
    else:
        logger.info("achivementform Valid Failed"+"**"*10)
        logger.info(achivementform.errors)
        message = u"数据没有填完整,请重新填写"
    table = refresh_achivement_table(request,pid,is_submited) 
    ret={'table':table,'message':message,}
    return simplejson.dumps(ret)
Ejemplo n.º 33
0
def edit_event(request,event_name,edit_event_form):
	message="Your form has the following errors <br>"
	event_object=Event.objects.get(name=event_name)
	edit_event_form = AddEventForm(deserialize_form(edit_event_form), instance=event_object)
	if edit_event_form.is_valid():
		#event_object.name=edit_event_form.cleaned_data['name']
		#event_object.short_description=edit_event_form.cleaned_data['short_description']
		#event_object.event_type=edit_event_form.cleaned_data['event_type']
		#event_object.category =edit_event_form.cleaned_data['category']
		#event_object.has_tdp=edit_event_form.cleaned_data['has_tdp']
		#event_object.team_size_min=edit_event_form.cleaned_data['team_size_min']
		#event_object.team_size_max=edit_event_form.cleaned_data['team_size_max']
		#event_object.registration_starts=edit_event_form.cleaned_data['registration_starts']
		#event_object.google_group=edit_event_form.cleaned_data['google_group']
		#event_object.email=edit_event_form.cleaned_data['email']
		#event_object.coords=edit_event_form.cleaned_data['coords']
		#event_object.save()	
                edit_event_form.save()
		temp=1
		message="successfully added event"
	else:
		temp=0
		for field in edit_event_form:
			for error in field.errors:
				message=message+field.html_name+" : "+error+"<br>"


	return json.dumps({'message': message,'temp':temp})
Ejemplo n.º 34
0
def schedule_form_data(request ,userauth="" ,form="",page=1,page2=1,search=0):
    ProjectJudge_form=ProjectJudgeForm()
    has_data = False
    schedule_form=ScheduleBaseForm(request=request)
    if search == 1:
        schedule_form = ScheduleBaseForm(deserialize_form(form))
        pro_list=get_search_data(request,schedule_form)
        default=False
    else:
        pro_list=get_project_list(request)
        default=True
    param=getParam(pro_list,userauth,default,page,page2)
    context ={ 'schedule_form':schedule_form,
               'has_data': has_data,
               'usercontext': userauth,
               'ProjectJudge_form':ProjectJudge_form,
               "approve":PROJECT_STATUS_APPLICATION_EXPERT_SUBJECT,
               "review":PROJECT_STATUS_FINAL_EXPERT_SUBJECT,
               "page":page,
               "page2":page2,
               'EXCELTYPE_DICT':EXCELTYPE_DICT_OBJECT(),
    }
    if userauth['role']!="college" and userauth['role']!="adminStaff":
        context.update({'show':1})
    context.update(param)
    return context
Ejemplo n.º 35
0
def save_qs(request, form, raw):  
    user = request.user
    form_dic = deserialize_form(form)
    try:
        sub_set = QuestionSubSet.objects.get(id = form_dic['subset'])
    except QuestionSubSet.DoesNotExist:
        return simplejson.dumps({'message':'Some errors occurred, we cannot find the set'})
    
    if raw !='-1':
        try:
            questionraw = QuestionRaw.objects.get(id = int(raw))
        except:
            return simplejson.dumps({'message':'Some errors occurred, we cannot find the question'})
    
    saved = 0
    for key, value in form_dic.iteritems():
        if 'answer' in key:
            q_instance = QuestionInstance.objects.get(pk = key[6:])
            if (raw !='-1' and q_instance.question.raw == questionraw) or (raw =='-1'):           
                user_progress, created = Progress.objects.get_or_create(user=user, instance = q_instance, question = q_instance.question, from_set = sub_set)
                if not user_progress.marked:
                    if user_progress.solution != value:
                        user_progress.solution = value
                        user_progress.save()
                        saved +=1
    if saved:
        return simplejson.dumps({'message':'save'})
    else:
        return simplejson.dumps({'message':'No Changes Made'})
Ejemplo n.º 36
0
def get_device_stat_detail(request, form, offset, length):
    user = cast_staff(request.user)
    form = deserialize_form(form)

    filter_form = DeviceStatForm(form)
    if not filter_form.is_valid():
        logger.warn("form is invalid")
        logger.warn(filter_form.errors)
        return _invalid_data_json

    results = stat_device(user, filter_form, True)
    total = results.count()
    lst = [i['did'] for i in results if i['did']]
    brands = len(set(lst))
    capacity = count_device(user, filter_form)
    results = results[offset: offset + length]
    logger.debug(results)
    dict_list = []
    for result in results:
        dict_list.append(device_record_to_dict(result))

    return simplejson.dumps({
        'ret_code': 0,
        'logs': dict_list,
        'total': total,
        'capacity': capacity,
        'brands': brands
    })
Ejemplo n.º 37
0
def filter_org_statistics(request, form, offset, length, mode, level):
    user = cast_staff(request.user)
    form = deserialize_form(form)

    filter_form = OrganizationStatForm(form)
    if not filter_form.is_valid():
        logger.warn("form is invalid")
        logger.warn(filter_form.errors)
        return _invalid_data_json

    logs = filter_org_logs(filter_form, mode)
    aggregate_result = logs.aggregate(capacity=Sum('appCount'))
    logger.debug(aggregate_result)
    capacity = aggregate_result['capacity'] or 0
    levels = available_levels(mode, level)
    keys = [l if l != 'emp' else 'uid' for l in levels]
    records = logs.values(*keys).annotate(total_device_count=Count('did', distinct=True),
                                       total_popularize_count=Sum('popularizeAppCount'),
                                       total_app_count=Sum('appCount'))
    total = records.count()
    brands = sum([i['total_device_count'] for i in records])
    records = records[offset: offset + length]
    items = []
    for record in records:
        items.append(org_record_to_dict(record, mode, level))
    #print [i['total_device_count'] for i in items]
    return simplejson.dumps({
        'ret_code': 0,
        'logs': items,
        'total': total,
        'capacity': capacity,
        'brands': brands
    })
Ejemplo n.º 38
0
def send_workset_form(request, form, form_id):
    dajax = Dajax()
    form = CreateWorksetForm(deserialize_form(form))

    user = request.user
    if request.user.is_anonymous():
        user = guardian.utils.get_anonymous_user()

    if form.is_valid():  # All validation rules pass
        dajax.remove_css_class(form_id+' input', 'error')
        dajax.script('form_errors(false,"{0}");'.format(form_id))

        wsid, msg = CollectionManager().workset_from_collection(
            user,
            form.cleaned_data.get('name'),
            form.cleaned_data.get('description'),
            form.cleaned_data.get('ispublic') == "true",
            int(form.cleaned_data.get('c_id')),
            int(form.cleaned_data.get('n')),
            form.cleaned_data.get('method')
        )

        if wsid is None: wsid = "null"
        dajax.script('refresh_worksets({0},"{1}");'.format(wsid,msg))

    else:
        dajax.remove_css_class(form_id+' input', 'error')
        dajax.script('form_errors(true,"{0}");'.format(form_id))
        for error in form.errors:
            dajax.add_css_class(form_id+' #id_%s' % error, 'error')

    return dajax.json()
Ejemplo n.º 39
0
def requisito_form(request, form, form_id):
    dajax = Dajax()
    #pdb.set_trace()
    f = deserialize_form(form)
    if Requisito.objects.filter(mansione=f['mansione'],tipo_turno=f['tipo_turno']).exists():
        r = Requisito.objects.get(mansione=f['mansione'],tipo_turno=f['tipo_turno'])
        form = RequisitoForm(f,instance=r)
    else:
        form = RequisitoForm(f)
    dajax.remove_css_class(str(form_id)+ ' #id_operatore', 'ui-state-error')
    dajax.remove_css_class(str(form_id)+ ' #id_valore', 'ui-state-error')
    if form.data.get('operatore')=='NULL' and Requisito.objects.filter(mansione=f['mansione'],tipo_turno=f['tipo_turno']).exists():
        r=Requisito.objects.get(mansione=form.data.get('mansione'),tipo_turno=form.data.get('tipo_turno'))
        turni=Turno.objects.filter(tipo=form.data.get('tipo_turno'))
        for t in turni:
             for d in Disponibilita.objects.filter(turno=t, mansione=form.data.get('mansione')):
                d.mansione=None
                d.save()
        r.delete()
        dajax.script('$("#applica-'+str(form.data.get('mansione'))+'-'+str(form.data.get('tipo_turno'))+'").hide();')
        dajax.assign(str(form_id)+ ' input', 'value','')
    elif form.is_valid():
        form.save()
        dajax.script('$("#applica-'+str(form.data.get('mansione'))+'-'+str(form.data.get('tipo_turno'))+'").hide();')
	dajax.script('noty({"text":"Modifiche apportate con successo","layout":"bottomRight","type":"success","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":500,"timeout":5000,"closeButton":true,"closeOnSelfClick":true,"closeOnSelfOver":false});')
    else:
        for error in form.errors:
            dajax.add_css_class('%(form)s #id_%(error)s' % {"form": form_id, "error": error}, 'ui-state-error')
    return dajax.json()
Ejemplo n.º 40
0
def read_category_form(form):
    CategoryForm = forms.category_form_factory()
    form = CategoryForm(deserialize_form(form))
    if form.is_valid():
        print 'valid form'
    else:
        print 'invalid form'

    categories = ["cycling",
                  "cover",
                  "castle",
                  "decorative papers",
                  "ship",
                  "technology",
                  "sciencefiction",
                  "children's book illustration",
                  "letter",
                  "decoration",
                  "map",
                  "fashion",
                  "portrait",
                  "christmas"]
    for cat in categories:
        if cat in form.cleaned_data:
            print cat
Ejemplo n.º 41
0
def send_form(request, form):
    dajax = Dajax()
    form = FormFront(deserialize_form(form))
    if form.is_valid():
        dajax.remove_css_class('#message_show', 'hidden')
        dajax.assign('#status', 'value', form)
    else:
        dajax.remove_css_class('#my_form p', 'error')
    # dajax.remove_css_class('#my_form .loading', 'hidden')
        # dajax.remove_css_class('#my_form p', 'error')
        dajax.remove_css_class('#status', 'hidden')
        # result = u'Отправляем сообщение'
        # dajax.assign('#status', 'value', result)
        # name = form.cleaned_data.get('name')
        # phone = form.cleaned_data.get('phone')
        # subject = u'Заявка waymy.ru'
        # message = u'Телефон: %s \n Имя: %s' % (phone, name)
        # send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False)
        # dajax.remove_css_class('#status', 'hidden')
        # result = u'Сообщение отправлено'
        # dajax.assign('#status', 'value', result)
        # dajax.remove_css_class('#message_show', 'hidden')
        # dajax.script('closemodal()')
        # dajax.redirect('/', delay=2000)
        # dajax.code('$(".close").click()')
    # for error in form.errors:
    #     dajax.add_css_class('#id_%s' % error, 'error')
    # dajax.add_css_class('div .loading', 'hidden')
    # dajax.alert("Form is_valid(), your phone is: %s" % form.cleaned_data.get('phone'))
    return dajax.json()
Ejemplo n.º 42
0
def order(request, form):
    dajax = Dajax()
    q = deserialize_form(form)
    ttype = ''
    if not q.get('buy-amount', None) is None: ttype = 'buy'
    if not q.get('sale-amount', None) is None: ttype = 'sale'
    form = OrdersForm(prefix=ttype, data=q)
    if form.is_valid():
        c = form.cleaned_data
        user = request.user
        if user.is_authenticated() and user.is_active:
            pair, amount, rate = c.get('pair'), c.get('amount'), c.get('rate')
            total, commission, pos = pair.calc(amount, rate, ttype)
            if ttype == 'buy': pos = pair.right
            if ttype == 'sale': pos = pair.left
            valuta = pos.value
            balance = user.orders_balance(valuta)
            if ttype == 'buy': _sum = balance - total
            if ttype == 'sale': _sum = balance - amount
            if _sum >= 0:
                _ret = getattr(pair, "order_%s" % ttype)(user, amount, rate)
                dajax.remove_css_class(
                    '#{type}_form input'.format(**{"type": ttype}), 'error')
                dajax.script("location.reload();")
            else:
                text = "Сумма сделки превышает ваш баланс на {sum} {valuta}".format(
                    **{
                        "sum": floatformat(-_sum, -8),
                        "valuta": pos
                    })
                dajax.script(
                    "$('#info_{type}').text('{text}');".format(**{
                        "type": ttype,
                        "text": text,
                    }))
        else:
            pair, amount, rate = c.get('pair'), c.get('amount'), c.get('rate')
            total, commission, pos = pair.calc(amount, rate, ttype)
            if ttype == 'buy': _sum = total
            if ttype == 'sale': _sum = amount
            text = "Сумма сделки превышает ваш баланс на {sum} {valuta}".format(
                **{
                    "sum": floatformat(-_sum, -8),
                    "valuta": pos
                })
            dajax.script(
                "$('#info_{type}').text('{text}');".format(**{
                    "type": ttype,
                    "text": text,
                }))
    else:
        dajax.script("$('#info_{type}').text('{text}');".format(
            **{
                "type": ttype,
                "text": "Неправильно заполнено одно из полей.",
            }))
        for error in form.errors:
            dajax.add_css_class('#id_%s-%s' % (ttype, error), 'error')
    return dajax.json()
Ejemplo n.º 43
0
def fundSummary(request, form, remarkmentform, pid, finance_account,
                is_submited):
    profundsummary = ProjectFundSummary.objects.get(project_id=pid)
    profundsummaryform = ProFundSummaryForm(deserialize_form(form),
                                            instance=profundsummary)
    profundsummaryremarkmentform = ProFundSummaryRemarkmentForm(
        deserialize_form(remarkmentform), instance=profundsummary)
    project = ProjectSingle.objects.get(project_id=pid)
    flag = False
    if profundsummaryform.is_valid() and finance_account:
        total_budget = float(profundsummaryform.cleaned_data["total_budget"])
        total_expenditure = float(
            profundsummaryform.cleaned_data["total_expenditure"])
        if total_budget < 0 or total_expenditure < 0:
            message = u"数据未填写完整或数据格式不对,保存失败"
        else:
            laborcosts_budget = float(
                profundsummaryform.cleaned_data["laborcosts_budget"])
            if laborcosts_budget <= total_budget * 0.3:
                if total_budget <= project.project_budget_max:
                    profundsummaryform.save()
                    #copyFundsummaryToBudget(pid)
                    project.finance_account = finance_account
                    project.save()
                    if is_submited:
                        if profundsummaryremarkmentform.is_valid():
                            profundsummaryremarkmentform.save()
                            message = u"保存成功"
                            flag = True
                            status_confirm(request, project)
                        else:
                            message = u"决算说明为必填项"
                    else:
                        message = u"保存成功"
                else:
                    message = u"经费决算表总结额应低于项目最大预算金额,请仔细核实"
            else:
                message = u"劳务费应低于总结额的30%,请仔细核实"
    else:
        loginfo(p=profundsummaryform.errors, label='profundsummaryform.errors')
        message = u"数据未填写完整或数据格式不对,保存失败"

    # table = refresh_fundsummary_table(request,profundsummaryform,pid)
    ret = {'message': message, 'flag': flag}
    return simplejson.dumps(ret)
Ejemplo n.º 44
0
def AddClassRoom(request, form):
    classroom = classRoomAddForm(deserialize_form(form))
    if classroom.is_valid():  #在这里已判断是否已经存在这个教室
        name = classroom.cleaned_data['room_name']
        create_classroom(name)
        ret = {'message': '添加成功'}
    else:
        ret = {'message': '教室已存在'}
    return simplejson.dumps(ret)
Ejemplo n.º 45
0
def signin_form_test(request, form, success_url=None):
    logger.debug("signin_form")
    dajax = Dajax()
    form = AuthenticationForm(deserialize_form(form))
    if form.is_valid():
        identification, password, remember_me = (
            form.cleaned_data['identification'], form.cleaned_data['password'],
            form.cleaned_data['remember_me'])
        user = authenticate(identification=identification, password=password)
        if user.is_active:
            login(request, user)
            if remember_me:
                request.session.set_expiry(
                    userena_settings.USERENA_REMEMBER_ME_DAYS[1] * 86400)
            else:
                request.session.set_expiry(0)

            # TODO: добавить сообщения
            if userena_settings.USERENA_USE_MESSAGES:
                logger.debug(u"Message: {0}".format(
                    _('You have been signed in.')))
                messages.success(request,
                                 _('You have been signed in.'),
                                 fail_silently=True)

            # TODO: изменить переадресацию после регистрации
            #redirect_to = signin_redirect(REDIRECT_FIELD_NAME, user)
            redirect_to = reverse('userena_profile_detail',
                                  kwargs={'username': user.username})
            logger.debug("Redirect: {0}".format(redirect_to))
        else:
            redirect_to = reverse('userena_disabled',
                                  kwargs={'username': user.username})
            logger.debug("Redirect: {0}".format(redirect_to))

        dajax.remove_css_class('#signin_form div', 'error')
        dajax.clear('#signin_form .help-inline', 'innerHTML')
        dajax.redirect(redirect_to, delay=10)
    else:
        dajax.remove_css_class('#signin_form div', 'error')
        dajax.clear('#signin_form .help-inline', 'innerHTML')
        dajax.add_css_class('#signin_form div.alert-error', 'hide')
        try:
            if form.errors['__all__'] is not None:
                dajax.remove_css_class('#signin_form div.alert-error', 'hide')
                dajax.assign(
                    '#signin_form .alert-error', 'innerHTML',
                    "<button type='button' class='close' data-dismiss='alert'>×</button>{0}"
                    .format(form.errors['__all__']))
        except Exception, e:
            pass
        for error in form.errors:
            dajax.add_css_class('#signin_form #gr_id_%s' % error, 'error')
            #dajax.remove_css_class('#signin_form #e_id_%s' % error, 'hide')
            dajax.assign('#signin_form #e_id_%s' % error, 'innerHTML',
                         form.errors[error][0])
Ejemplo n.º 46
0
Archivo: ajax.py Proyecto: oosprey/ERP
def saveProdUserModify(request, form, produserid):
    prod_user_obj = ProductionUser.objects.get(id=produserid)
    prod_user_form = ProductionUserForm(deserialize_form(form),
                                        instance=prod_user_obj)
    if prod_user_form.is_valid():
        prod_user_form.save()
        message = u"修改成功"
    else:
        message = u"修改失败"
    return message
Ejemplo n.º 47
0
def updateUserInfo(request, user_form):
    user_form = userInfoForm(deserialize_form(user_form),
                             instance=request.user.userinfo)
    if user_form.is_valid():
        user_form.save()
        log = "save success"
    else:
        log = "form error"
    print user_form.errors
    return log
Ejemplo n.º 48
0
Archivo: ajax.py Proyecto: oosprey/ERP
def ledgerSearch(request, form):
    search_form = LedgerSearchForm(deserialize_form(form))
    if search_form.is_valid():
        materiel_list = SubMateriel.objects.filter(
            getQ(search_form.cleaned_data))
        html = render_to_string("production/widgets/designBOM_table_list.html",
                                {"BOM": materiel_list})
    else:
        print search_form.errors
    return simplejson.dumps({"html": html})
Ejemplo n.º 49
0
def ExportExcel(request, form, category):
    schedule_form = ScheduleBaseForm(deserialize_form(form))
    pro_list = get_search_data(request, schedule_form)
    if category == EXCELTYPE_INFO_FUNDBUDGET:
        path = get_xls_path(request, category, pro_list)
    elif category == EXCELTYPE_INFO_FUNDSUMMARY:
        path = get_xls_path(request, category, pro_list)
    else:
        return simplejson.dumps({"status": "0"})
    return simplejson.dumps({"status": "ok", "path": path})
Ejemplo n.º 50
0
def revision_form_submit(request, form, code):
    dajax = Dajax()
    form = RevisionForm(deserialize_form(form))

    dajax.remove_css_class('#revision-form textarea', 'error')
    dajax.remove('.error-message')

    if form.is_valid():

        commit_message = form.cleaned_data['commit_message']
        username, email = request.user.username, request.user.email

        # push changes to temp repo
        # update_file returns True if the push is success.
        commit_sha = utils.update_file(
            request.session['filepath'],
            commit_message,
            base64.b64encode(code),
            [username, email],
            main_repo=False,
        )

        if commit_sha is not None:
            # everything is fine

            # save the revision info in database
            rev = TextbookCompanionRevision(
                example_file_id=request.session['example_file_id'],
                commit_sha=commit_sha,
                commit_message=commit_message,
                committer_name=username,
                committer_email=email,
            )
            rev.save(using='scilab')

            dajax.alert(
                'submitted successfully! \nYour changes will be visible after review.'
            )
            dajax.script('$("#submit-revision-wrapper").trigger("close")')
    else:
        for error in form.errors:
            dajax.add_css_class('#id_{0}'.format(error), 'error')
        for field in form:
            for error in field.errors:
                message = '<div class="error-message">* {0}</div>'.format(
                    error)
                dajax.append('#id_{0}_wrapper'.format(field.name), 'innerHTML',
                             message)
        # non field errors
        if form.non_field_errors():
            message = '<div class="error-message"><small>{0}</small></div>'.format(
                form.non_field_errors())
            dajax.append('#non-field-errors', 'innerHTML', message)

    return dajax.json()
Ejemplo n.º 51
0
def ExportAchievementInfoExcel(request, form):
    schedule_form = ScheduleBaseForm(deserialize_form(form))
    year = schedule_form.data["conclude_year"]
    if year == u"-1" or year == u"None":

        return simplejson.dumps({"status": "fail"})

    else:
        projects = ProjectSingle.objects.filter(conclude_year=year)
        path = get_xls_path(request, "achievementInfo", projects, year=year)
        return simplejson.dumps({"status": "ok", "path": path})
Ejemplo n.º 52
0
def create_comment(request, post_id, data):
    """
        Creates a new comment on a Post
    """
    # Initial validations
    try:
        post_id = int(post_id)
    except ValueError:
        post_id = None
    if not (type(post_id) is int):
        raise InvalidArgumentTypeException(
            "argument `post_id` should be of type integer")

    # Create a new comment
    append_string = ""
    data = deserialize_form(data).dict()

    # Attempt to get the post for the comment
    post = get_object_or_None(Post, id=int(post_id))
    comment_text = data['comment']
    if not post:
        raise InvalidArgumentValueException(
            "No Post with id `post_id` was found in the database")

    comment_text, notification_list = parse_atwho(comment_text)

    rendered_comment_text = Template('''
            {%load markdown_tags%}
            {%autoescape off%}
                {{ comment_text|markdown }}
            {%endautoescape%}
        ''').render(RequestContext(request, {'comment_text': comment_text}))
    new_comment = Comment.objects.create(description=rendered_comment_text,
                                         by=request.user)
    post.comments.add(new_comment)

    post.add_notifications(notification_list)
    post_wall = post.wall
    if post_wall.parent:
        post.add_notifications([post_wall.parent,
                                request.user])  # add to and from

    new_comment.send_notif(
    )  # Send notifs now, as all notif personnel are added

    # Render the new comment
    local_context = {'comment': new_comment, 'post': post}
    append_string = render_to_string('modules/comment.html',
                                     local_context,
                                     context_instance=global_context(
                                         request, token_info=False))

    local_context = {'append_string': append_string, 'post_id': post_id}
    return json.dumps(local_context)
Ejemplo n.º 53
0
def fundSummaryRemarkment(request, form, pid):
    profundsummary = ProjectFundSummary.objects.get(project_id=pid)
    profundsummaryremarkmentform = ProFundSummaryRemarkmentForm(
        deserialize_form(form), instance=profundsummary)
    if profundsummaryremarkmentform.is_valid():
        profundsummaryremarkmentform.save()
        message = u"保存成功"
    else:
        message = u"决算说明为必填项"
    ret = {'message': message}
    return simplejson.dumps(ret)
Ejemplo n.º 54
0
Archivo: ajax.py Proyecto: oosprey/ERP
def getUser(request, form):
    """
    Lei
    """
    user_choose_form = UserChooseForm(deserialize_form(form))
    if user_choose_form.is_valid():
        user_list = UserInfo.objects.filter(getQ(
            user_choose_form.cleaned_data)).order_by("productionuser")
    html = render_to_string("production/widgets/user_table.html",
                            {"user_list": user_list})
    return html
Ejemplo n.º 55
0
def add_tab(request,username,add_tab_form):
    add_tab_form=deserialize_form(add_tab_form)
    message=""    
    if add_tab_form['tab_name']!='' and  add_tab_form['tab_name'][0]!=' ':
		event_tab=EventTab()
		event_tab.name=add_tab_form['tab_name']
		event_tab.content=add_tab_form['tab_description']
		event_tab.event=Event.objects.get(name=add_tab_form['event_name'])
		event_tab.save()
		message="The " + add_tab_form['tab_name'] + " tab has been successfully added to the " + add_tab_form['event_name'] + " event"
    return json.dumps({'message': message,'username':username,'event_name':add_tab_form['event_name']})
Ejemplo n.º 56
0
def saveChangeClass(request, form):
    form = studentchangeclassForm(deserialize_form(form))
    if form.is_valid():
        message = '转班成功'
        stuid = trip_str(form.cleaned_data["studentid"])
        student = StudentProfile.objects.get(baseinfo_studentid=stuid)
        student.small_class = SmallClass.objects.get(
            id=form.cleaned_data["receiveclass"])
        student.save()
    else:
        message = '转班失败'
    return simplejson.dumps({'message': message})
Ejemplo n.º 57
0
def ResetSchoolPassword(request, form):
    resetSchoolPassword_form = ResetSchoolPasswordForm(deserialize_form(form))
    if resetSchoolPassword_form.is_valid():
        password = resetSchoolPassword_form.cleaned_data["reset_password"]
        for register in SchoolProfile.objects.all():
            user = User.objects.get(username__exact=register.userid.username)
            if user:
                user.set_password(password)
                user.save()
        return simplejson.dumps({'status': '1', 'message': u"重置密码成功"})
    else:
        return simplejson.dumps({'status': '1', 'message': u"密码不能为空"})
Ejemplo n.º 58
0
Archivo: ajax.py Proyecto: oosprey/ERP
def getProductionUser(request, form):
    """
    Lei
    """
    production_user_search_form = ProductionUserSearchForm(
        deserialize_form(form))
    if production_user_search_form.is_valid():
        production_user_list = ProductionUser.objects.filter(
            getQ(production_user_search_form.cleaned_data))
    html = render_to_string("production/widgets/production_user_table.html",
                            {"production_user_list": production_user_list})
    return html
Ejemplo n.º 59
0
Archivo: ajax.py Proyecto: oosprey/ERP
def materialuseSearch(request, form):
    search_form = MaterielCopyForm(deserialize_form(form))
    if search_form.is_valid():
        materiel_list = MaterielCopy.objects.filter(
            getQ(search_form.cleaned_data))
        print materiel_list.count()
        html = render_to_string(
            "production/table/materiel_use_select_table.html",
            {"items": materiel_list})
    else:
        print search_form.errors
    return simplejson.dumps({"html": html})
Ejemplo n.º 60
0
def add_event(request,event_form):
	message="Your form has the following errors <br>"
	event_form = AddEventForm(deserialize_form(event_form))
	if event_form.is_valid():
		event_form.save()
		message="successfully added event"
	else:
		for field in event_form:
			for error in field.errors:
				message=message+field.html_name+" : "+error+"<br>"
				
	return json.dumps({'message': message})