def notifiche(request,option,url): dajax = Dajax() #pdb.set_trace() i=0 dajax.assign('#sele','value','') for not_id in url.rsplit('_'): i += 1 selector='#not-'+not_id m = Notifica.objects.get(id=not_id) if (option == 'letto'): m.letto=True m.save() dajax.remove_css_class(selector,'warning') if (option == 'nonletto'): m.letto=False m.save() dajax.add_css_class(selector,'warning') if (option == 'cancella'): m.delete() dajax.remove(selector) dajax.remove('#not-inv-'+not_id) #dajax.alert(request.user.get_profile().nonletti()) try: non=request.user.get_profile().notifiche_non_lette() if non >0: dajax.assign('#notifiche-badge','innerHTML',non) else: dajax.assign('#notifiche-badge','innerHTML','') except: pass dajax.clear('.ch','checked') dajax.script("$('#loading').addClass('hidden');") return dajax.json()
def notifiche(request,option,url): dajax = Dajax() #pdb.set_trace() i=0 dajax.assign('#sele','value','') for not_id in url.rsplit('_'): i += 1 selector='#not-'+not_id m = Notifica.objects.get(id=not_id) if (option == 'letto'): m.letto=True m.save() dajax.remove_css_class(selector,'warning') if (option == 'nonletto'): m.letto=False m.save() dajax.add_css_class(selector,'warning') if (option == 'cancella'): m.delete() dajax.remove(selector) dajax.remove('#not-inv-'+not_id) #dajax.alert(request.user.get_profile().nonletti()) try: non=request.user.pers_user.notifiche_non_lette() if non >0: dajax.assign('#notifiche-badge','innerHTML',non) else: dajax.assign('#notifiche-badge','innerHTML','') except: pass dajax.clear('.ch','checked') dajax.script("$('#loading').addClass('hidden');") return dajax.json()
def add_edit_contact_people(request, form): dajax = Dajax() form = AddEditContactPeopleForm(deserialize_form(form)) if form.is_valid(): if form.cleaned_data.get('id'): contactPeople = ContactPeople.objects.filter(id=form.cleaned_data.get('id'))[0] contactPeople.contact_item = form.cleaned_data.get('contact_item') contactPeople.name = form.cleaned_data.get('name') contactPeople.qq = form.cleaned_data.get('qq') contactPeople.email = form.cleaned_data.get('email') contactPeople.phone = form.cleaned_data.get('phone') contactPeople.save() else: contact_item=form.cleaned_data.get('contact_item') max_pos = contact_item.contactpeople_set.all().aggregate(Max('position')) position = int(max_pos['position__max'] or 0) + 1 ContactPeople.objects.create(contact_item=contact_item, name=form.cleaned_data.get('name'), qq=form.cleaned_data.get('qq'), phone=form.cleaned_data.get('phone'), email=form.cleaned_data.get('email'),position=position) dajax.remove_css_class('#add_edit_contact_people_form.control-group', 'error') dajax.add_data({ 'ret_code' : 0, 'ret_msg' : 'success' }, 'addEditContactPeopleCallback') dajax.redirect(form.cleaned_data.get('tab_id')) else: dajax.remove_css_class('#add_edit_contact_people_form .control-group', 'error') for error in form.errors: dajax.add_css_class('#%s' % error, 'error') dajax.add_data({ 'ret_code' : 1000, 'ret_msg' : 'error' }, 'addEditContactPeopleCallback') return dajax.json()
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()
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()
def delete_content(request, threadcontent_id): dajax = Dajax() try: thread_content=ThreadContent.objects.get(id=threadcontent_id) delete_prompt = '<h5>Confirm Delete</h5><p>Are you sure you want to delete this thread content: %s?</p>' % thread_content.get_title() course_thread_content = thread_content.coursethreadcontent_set.all() if course_thread_content: delete_prompt += '<p>Deleting will also delete content from the following courses:</p><ul>' for content in course_thread_content: delete_prompt += '<li>%s</li>' % content.course.name delete_prompt += '</ul>' click_command_base = thread_content.get_click_command_base() click_command = click_command_base % 'confirm_delete_content' delete_prompt += '<p><input type="button" value="Yes" onclick="%s;">' % click_command click_command = click_command_base % 'cancel_delete_content' delete_prompt += '<input type="button" value="No" onclick="%s;" style="margin-left: 3px;"></p>' % click_command dajax.assign('#%s_content_insert_below_content' % threadcontent_id, \ 'innerHTML', delete_prompt) dajax.add_css_class('#%s_content_insert_below_content' % threadcontent_id, 'thread_info_box') except Exception as e: dajax.alert("something wrong: %s" % e) return dajax.json()
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()
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()
def add_edit_join_item(request, form): dajax = Dajax() form = JoinItemForm(deserialize_form(form)) if form.is_valid(): if form.cleaned_data.get('id'): joinItem = JoinItem.objects.filter(id=form.cleaned_data.get('id'))[0] joinItem.publish = form.cleaned_data.get('publish') joinItem.job_title = form.cleaned_data.get('job_title') joinItem.number = form.cleaned_data.get('number') joinItem.content1 = form.cleaned_data.get('content1') joinItem.content2 = form.cleaned_data.get('content2') joinItem.content3 = form.cleaned_data.get('content3') joinItem.content4 = form.cleaned_data.get('content4') joinItem.require1 = form.cleaned_data.get('require1') joinItem.require2 = form.cleaned_data.get('require2') joinItem.require3 = form.cleaned_data.get('require3') joinItem.require4 = form.cleaned_data.get('require4') joinItem.save() else: join_id=form.cleaned_data.get('tab_id') joinapp = JoinApp.objects.get(pk=join_id) max_pos = joinapp.joinitem_set.all().aggregate(Max('position')) position = int(max_pos['position__max'] or 0) + 1 JoinItem.objects.create(join_id=join_id, publish=form.cleaned_data.get('publish'), job_title=form.cleaned_data.get('job_title'), number=form.cleaned_data.get('number'), content1=form.cleaned_data.get('content1'), content2=form.cleaned_data.get('content2'), content3=form.cleaned_data.get('content3'), content4=form.cleaned_data.get('content4'), require1=form.cleaned_data.get('require1'), require2=form.cleaned_data.get('require2'), require3=form.cleaned_data.get('require3'), require4=form.cleaned_data.get('require4'), position=position) dajax.remove_css_class('#add_edit_join_item_form.control-group', 'error') dajax.add_data({ 'ret_code' : 0, 'ret_msg' : 'success' }, 'addEditJoinItemCallback') dajax.redirect(form.cleaned_data.get('tab_id')) else: dajax.remove_css_class('#add_edit_join_item_form .control-group', 'error') for error in form.errors: dajax.add_css_class('#%s' % error, 'error') dajax.add_data({ 'ret_code' : 1000, 'ret_msg' : 'error' }, 'addEditJoinItemCallback') return dajax.json()
def date_check_new(request,option,end_hour,end_min,start_hour,start_min): dajax = Dajax() end_hour=int(end_hour) end_min=int(end_min) start_hour = int(start_hour) start_min = int(start_min) now=datetime.now().date() date = datetime.strptime(option,"%Y-%m-%d").date() status = [] if now < date: dajax.add_css_class('#seld-error', 'hide') dajax.add_css_class('#errorList', 'hide') if start_hour!=0 and end_hour!=0 and end_min!=60 and start_min!=60: status.append('<button onclick="Dajaxice.dashboard.single_booking_check(Dajax.process, {\'end_min\':document.getElementById(\'emin\').value,\'end_hour\':document.getElementById(\'ehr\').value,\'start_hour\':document.getElementById(\'shr\').value,\'start_min\':document.getElementById(\'smin\').value,\'option\':document.getElementById(\'datepicker\').value,\'res_id\':document.getElementById(\'combo2\').value})" type="button" >Click here to check status</button>') dajax.assign('#status', 'innerHTML',''.join(status)) dajax.add_css_class('#errorList', 'hide') dajax.add_css_class('.alert-error', 'hide') else: dajax.clear('#status','innerHTML') if start_hour==0 or start_min==60: dajax.remove_css_class('#startt-error', 'hide') else: dajax.remove_css_class('#endt-error', 'hide') dajax.add_css_class('#startt-error', 'hide') else: dajax.assign('#errorList .showMessage','innerHTML','You can not book for the past or today. Kindly select some other date') dajax.clear('#status','innerHTML') dajax.remove_css_class('#errorList', 'hide') dajax.remove_css_class('#seld-error', 'hide') return dajax.json()
def category_subcategory(request, option): dajax = Dajax() out = [] if option == "---------": dajax.add_css_class('.ad-subcategory', ' area_none') dajax.assign('._ad-subcategory-td', 'innerHTML', ''.join(out)) else: category = AdCategory.objects.get(name=option) sub_category = AdSubCategory.objects.filter(category=category) column_sizes = columnize(len(sub_category), 3) columns = [] for column_size in column_sizes: columns.append(sub_category[:column_size]) sub_category = sub_category[column_size:] for column in columns: out.append(u'<ul>') for sub in column: out.append(u"<li><label for='id_subcategory_" + str(get_pk(sub.pk)) + u"'><input id='id_subcategory_" + str(get_pk(sub.pk)) + u"' name='subcategory' type='checkbox' value='" + str(sub.pk) + u"'>" + u" " + sub.name + u"</label></li>") out.append(u'</ul>') dajax.assign('._ad-subcategory-td', 'innerHTML', ''.join(out)) dajax.remove_css_class('.ad-subcategory', ' area_none') return dajax.json()
def add_product_class(request, form): dajax = Dajax() form = AddProductClassForm(deserialize_form(form)) if form.is_valid(): if len(ProductClass.objects.filter(product_app_id=form.cleaned_data.get('tab_id'))) >= 4: dajax.remove_css_class('#add_product_class_form .control-group', 'error') for error in form.errors: dajax.add_css_class('#%s' % error, 'error') dajax.add_data({ 'ret_code' : 1000, 'ret_msg' : '最多只能添加4个分类!' }, 'addProductClassCallback') else: product_app_id=form.cleaned_data.get('tab_id') productapp = ProductApp.objects.get(pk=product_app_id) max_pos = productapp.productclass_set.all().aggregate(Max('position')) position = int(max_pos['position__max'] or 0) + 1 ProductClass.objects.create(name=form.cleaned_data.get('name'), product_app_id=product_app_id, pub_time=datetime.datetime.now(), position=position) dajax.remove_css_class('#add_product_class_form .control-group', 'error') dajax.add_data({ 'ret_code' : 0, 'ret_msg' : u'分类已成功添加!' }, 'addProductClassCallback') dajax.redirect(form.cleaned_data.get('tab_id')) else: dajax.remove_css_class('#add_product_class_form .control-group', 'error') for error in form.errors: dajax.add_css_class('#%s' % error, 'error') dajax.add_data({ 'ret_code' : 1000, 'ret_msg' : '该分类已添加过!' }, 'addProductClassCallback') return dajax.json()
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()
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()
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()
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()
def _get_person(p): dajax = Dajax() dajax.add_css_class('#idError', 'hideIt') dajax.assign('#idName', 'innerHTML', p.name) dajax.assign('#idDay', 'innerHTML', p.birthday.strftime("%B %d")) gift = 'Yes' if p.gift_bought else '<a href="#" onclick="Dajaxice.testDajax.bought_gift(Dajax.process, {\'pk\':_cur_person});">No</a>' dajax.assign('#idGift', 'innerHTML', gift) dajax.script("_cur_person = %d;" % p.pk) return dajax.json()
def add(request, animation): dajax = Dajax() dajax.remove_css_class('#movie-inspector label', 'error') animation = json.loads(animation) animation.update({ 'type': 'm', 'user': request.user is None and '' or request.user.id, }) if int(animation['max_duration']) > 60: animation['max_duration'] = 60 movie_duration = 0 for frame in animation['data']: frame['duration'] = int(frame['duration']) if frame['duration'] > 2000: frame['duration'] = 2000 movie_duration += frame['duration'] if movie_duration > 60000: dajax.script('MessageWidget.msg("Animation darf insgesamt nicht laenger als 60 Sekunden sein! Bitte Frames loeschen oder kuerzer anzeigen lassen!")') return dajax.json() form = AnimationForm(animation) if form.is_valid(): a = form.save() p = Playlist( title = 'stub \'%s\' playlist' % form.cleaned_data['title'], user = User.objects.all()[0] ) p.save() ai = AnimationInstance( playlist = p, animation = a ) ai.save() # queue playlist sj = SpoolJob( playlist = p, priority = 2, added = datetime.now() ) sj.save() dajax.script('MessageWidget.msg("Great success! Animootion mit ID %s gespeichert!")' % p.id) else: for error in form.errors: dajax.add_css_class('#movie-inspector label[for="%s"]' % error, 'error') dajax.script('MessageWidget.msg("Bitte fehlende Felder ausfuellen.")') return dajax.json()
def buscarCliente(request): if request.method == 'POST': tipo = request.POST['tipo'] dato = request.POST['dato'] print tipo print dato print request.user dajax = Dajax() try: #validando ando usuario = request.user #usuario = User.objects.first() bucqModel = vitacoraBusquedas(tipoBusq=tipo, consulta=dato, usuario=usuario, estadoRetorno=True) form = BusquedaForm( {'usuario': usuario.id, 'estadoRetorno': True, 'tipoBusq': tipo, 'consulta': dato}, instance=bucqModel ) if form.is_valid(): buscando = b(usuario.sesion_sico) data = buscando.busquedaDeTipo(tipo, dato, paraIngreso=True) #data = MedidorBuscado('marca','tecnologia', 'tension', 'amp', 'fi', 'fd', 'li', 'ld', #instance=medidor.objects.first()) if data != None: dajax.assign('#id_codigoDeCliente', 'value', '' + str(data['formCliente'].instance.cuenta) + '') dajax.assign('#id_nombreDeCliente', 'value', '' + str(data['formCliente'].instance.nombre) + '') dajax.assign('#id_cedula', 'value', '' + str(data['formCliente'].instance.ci_ruc) + '') dajax.assign('#id_estadoCli', 'value', '' + str(data['formCliente'].instance.estado) + '') dajax.assign('#id_lugar', 'value', '' + str(data['formCliente'].fields['parroquia'].initial) + '') dajax.assign('#id_calle', 'value', '' + str(data['formCliente'].fields['direccion'].initial) + '') dajax.assign('#id_geocodigo', 'value', '' + str(data['formCliente'].fields['geo'].initial) + '') dajax.assign('#id_fabricaRev', 'value', '' + str(data['cMedidores'][0].instance.fabrica) + '') dajax.script("$('#id_serieRev').val('" + str(data['cMedidores'][0].instance.serie) + "').change();") dajax.assign('#id_marcaRev', 'value', '' + str(data['cMedidores'][0].fields['marc'].initial) + '') dajax.assign('#id_lecturaRev', 'value', '' + str(data['cMedidores'][0].instance.lectura) + '') request.session['cliente'] = data['formCliente'].instance request.session['medidor'] = data['cMedidores'][0] else: dajax = mostraError(dajax, {'Cliente': 'No Encontrato'}, '#err') else: print form.errors dajax = mostraError(dajax, {'': dict(form.errors)['__all__']}, '#err') except: dajax = mostraError(dajax, {'Error': 'No se pudo Buscar Cliente...'}, '#err') dajax.add_css_class('#cargando', 'hidden') return dajax.calls else: return None
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])
def _get_giftcard(gc): dajax = Dajax() dajax.add_css_class('#idError', 'hideIt') dajax.assign('#idName', 'innerHTML', gc.title_text) emailSent = 'Yes' if gc.initial_email_sent else '<a href="#" onclick="Dajaxice.snaview.sent_email(Dajax.process, {\'pk\':cur});">No</a>' dajax.assign('#idEmailSent', 'innerHTML', emailSent) dajax.script("cur = %d;" % gc.pk) return dajax.json()
def djax_views(request, items, model): dajax = Dajax() res = Vote.objects.get_scores_in_bulk(items, model) for r in res: dajax.assign('#num_votes{0}'.format(r['object_id']), 'innerHTML', r['num_votes']) dajax.assign('#score{0}'.format(r['object_id']), 'innerHTML', r['score']) viewDisable = Vote.objects.filter(object_id__in=items, model_view=model, sessions_hash=request.session) for v in viewDisable: dajax.add_css_class('#vote-{0}'.format(v.pk), 'disabled') return HttpResponse(dajax.json(), mimetype="application/json")
def change_ui_tabs(request,activate_li=None,deactivate_lis=None): dajax = Dajax() if not activate_li or not deactivate_lis: return dajax.json() for li in deactivate_lis: dajax.remove_css_class(li,'ui-state-active') dajax.remove_css_class(li,'ui-tabs-selected') dajax.add_css_class(activate_li,'ui-tabs-selected') dajax.add_css_class(activate_li,'ui-state-active') return dajax.json()
def get_daemon_status(request): dajax = Dajax() status = Daemon(60, 'ERROR').status() if status == 'Running': dajax.remove_css_class('#daemon_status', 'stopped') dajax.add_css_class("#daemon_status", 'running') else: dajax.remove_css_class('#daemon_status', 'running') dajax.add_css_class('#daemon_status', 'stopped') return simplejson.dumps({'status': status})
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()
def generateSchedule(request, form): dajax = Dajax() selectedCourses = Course.objects.none() timesUnavailable = [] # Get the data numClasses = int(form['numClasses']) if 'byCourse' in request.session: for courseTuple in request.session['byCourse']: selectedCourses = selectedCourses | Course.objects.filter(subject=courseTuple[0], number=courseTuple[1]) if 'byProf' in request.session: for profTuple in request.session['byProf']: selectedCourses = selectedCourses | Instructor.objects.get(userid=profTuple[1]).course.filter(subject=profTuple[0], number=profTuple[2]) if 'byId' in request.session: for idTuple in request.session['byId']: selectedCourses = selectedCourses | Course.objects.filter(id=idTuple[0]) if 'timesUnavailable' in request.session: for time in request.session['timesUnavailable']: timesUnavailable.append(time) if not selectedCourses: dajax.alert("Please select at least one class") dajax.script('$(\'#scheduleViewDiv\').activity(false);') dajax.remove_css_class('#scheduleViewDiv', 'emptySchedule'); return dajax.json() if numClasses > len(selectedCourses): dajax.alert("Only %i class(es) meet your course selection. Please specify more classes" % len(selectedCourses)) dajax.script('$(\'#scheduleViewDiv\').activity(false);') dajax.remove_css_class('#scheduleViewDiv', 'emptySchedule'); return dajax.json() # Process the data processedCourses = createOptimalSchedule(numClasses, selectedCourses, timesUnavailable) optimalCourses = list(set(processedCourses[1])) optimalInstructors = list(set(Instructor.objects.filter(course__in = optimalCourses))) optimalMeetingTimes = list(set(processedCourses[0])) optimalExamTimes = list(set(MeetingTime.objects.filter(course__in = optimalCourses).filter(Q(type="EXAM") | Q(type="MIDT")))) rejectedCourses = list(set(processedCourses[3])) rejectedInstructors = list(set(Instructor.objects.filter(course__in = rejectedCourses))) rejectedMeetingTimes = list(set(processedCourses[2])) processedData = {'optimalCourses': optimalCourses, 'optimalInstructors': optimalInstructors, 'optimalMeetingTimes': optimalMeetingTimes, 'optimalExamTimes': optimalExamTimes, 'rejectedCourses': rejectedCourses, 'rejectedInstructors': rejectedInstructors, 'rejectedMeetingTimes': rejectedMeetingTimes} request.session['processedData'] = processedData processedData['scheduledHTML'] = weeklySchedule(optimalMeetingTimes) # Serve the data dajax.assign('#scheduleViewDiv', 'innerHTML', render_to_response('schedulerSchedule.html', processedData).content) dajax.script('$(\'#scheduleViewDiv\').activity(false);') dajax.script('$(document).ready(jQueryEffects());') dajax.remove_css_class('#scheduleViewDiv', 'emptySchedule'); dajax.add_css_class('#scheduleViewDiv', 'fullSchedule'); dajax.clear('#warningDiv', 'innerHTML') return dajax.json()
def dash(request): dajax = Dajax() dajax.add_css_class('#item_dash', 'active') dajax.add_css_class('#topbar_dash', 'active') html_content = render_to_string('mailer/home.html', {}, RequestContext(request)) if html_content: dajax.assign("#content", "innerHTML", html_content) return dajax.json()
def add_to_compare(request, person_id): person_id = int(person_id) person = get_object_or_404(models.Person, id=person_id) compare_set = request.session.get(common.COMPARE_LIST_SESSION_KEY, set()) dajax = Dajax() if person_id not in compare_set: compare_set.add(person_id) request.session[common.COMPARE_LIST_SESSION_KEY] = compare_set dajax.append("#compare-list-body", "innerHTML", person_compare_row(person)) dajax.add_css_class("#add-to-compare-person-%s-button" % person_id, "hide") dajax.remove_css_class("#compare-persons-block", "hide") return dajax.json()
def submit_form(request, form_id, form, gigbargainband): dajax = Dajax() if form.is_valid(): dajax.remove_css_class('%s input' % form_id, 'error') dajax.script("$('%s').submit()" % form_id) else: dajax.remove_css_class('%s input' % form_id, 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json()
def wall_message(request, data_id): dajax = Dajax() dajax.add_data(data_id, 'scroll') wallmsgs = WallMsg.objects.filter(pk=data_id) if not len(wallmsgs) == 0: for wallmsg in wallmsgs: if wallmsg.flag_on == 1: dajax.remove_css_class('div[data-id=%s]' % data_id, 'waiting') dajax.assign('div[data-id=%s] .state_wait' % data_id, 'innerHTML', '<span class="icon-white icon-ok flag"></span>已上墙') dajax.add_css_class('div[data-id=%s] .state_wait' % data_id, 'state') dajax.remove_css_class('div[data-id=%s] .state_wait' % data_id, 'state_wait') return dajax.json()
def add(request, animation): dajax = Dajax() dajax.remove_css_class('#movie-inspector label', 'error') animation = json.loads(animation) animation.update({ 'type': 'm', 'user': request.user is None and '' or request.user.id, }) if int(animation['max_duration']) > 60: animation['max_duration'] = 60 movie_duration = 0 for frame in animation['data']: frame['duration'] = int(frame['duration']) if frame['duration'] > 2000: frame['duration'] = 2000 movie_duration += frame['duration'] if movie_duration > 60000: dajax.script( 'MessageWidget.msg("Animation darf insgesamt nicht laenger als 60 Sekunden sein! Bitte Frames loeschen oder kuerzer anzeigen lassen!")' ) return dajax.json() form = AnimationForm(animation) if form.is_valid(): a = form.save() p = Playlist(title='stub \'%s\' playlist' % form.cleaned_data['title'], user=User.objects.all()[0]) p.save() ai = AnimationInstance(playlist=p, animation=a) ai.save() # queue playlist sj = SpoolJob(playlist=p, priority=2, added=datetime.now()) sj.save() dajax.script( 'MessageWidget.msg("Great success! Animootion mit ID %s gespeichert!")' % p.id) else: for error in form.errors: dajax.add_css_class('#movie-inspector label[for="%s"]' % error, 'error') dajax.script('MessageWidget.msg("Bitte fehlende Felder ausfuellen.")') return dajax.json()
def survey_question_sort(request, id, sort_order): dajax = Dajax() try: survey_question = SurveyQuestion.objects.get(pk=int(id)) survey_question.order = sort_order survey_question.save() #dajax.alert("(%s) has been successfully sorted !!" % (survey_question.question)) except: #dajax.alert("%s is not exist !!" % (id)) for error in form.errors: dajax.add_css_class('#id_%s' % error,'error') return dajax.json()
def test(request, form): form = PlotForm(form) dajax = Dajax() if form.is_valid(): dajax.remove_css_class('#form input,select','error-field') my_plot = Plot(form.cleaned_data) filename = my_plot.to_disk() dajax.assign('#image', 'src', filename) else: dajax.remove_css_class('#form input,select','error-field') for error in form.errors: dajax.add_css_class('#id_%s' % error,'error-field') return dajax.json()
def approval_list(request): dajax=Dajax() mails=MailLog.objects.filter(needs_approval=True).filter(is_approved=False) dajax.remove_css_class('#item_dash', 'active') dajax.remove_css_class('#item_events', 'active') dajax.add_css_class('#item_approval', 'active') to_return ={ 'mails': mails, } html_content = render_to_string('mailer/approval_list.html', to_return, RequestContext(request)) if html_content: dajax.assign("#content", "innerHTML", html_content) return dajax.json()
def assign_test(request,latest_act_id): dajax = Dajax() if latest_act_id is None: latest_act_id=0 action_list = list(Action.objects.user_stream_latest(request.user,latest_act_id)) size = len(action_list) if(size>0): dajax.clear('span.newentry', 'innerHTML') dajax.assign('span.newentry', 'innerHTML', simplejson.dumps(size)+" new activity recorded, refresh page to see details") dajax.remove_css_class('div.newentry', 'hidden') dajax.add_css_class('div.newentry', 'active') return dajax.json()
def send_form(request, form): dajax = Dajax() form = forms.LoginForm(deserialize_form(form)) if form.is_valid(): dajax.remove_css_class('#my_form input', 'error') dajax.alert("Form is_valid(), your username is: %s" % form.cleaned_data.get('username')) else: dajax.remove_css_class('#my_form input', 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json()
def survey_question_sort(request, id, sort_order): dajax = Dajax() try: survey_question = SurveyQuestion.objects.get(pk=int(id)) survey_question.order = sort_order survey_question.save() #dajax.alert("(%s) has been successfully sorted !!" % (survey_question.question)) except: #dajax.alert("%s is not exist !!" % (id)) for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json()
def send_form(request, form): dajax = Dajax() form = ProductOneClickForm(deserialize_form(form)) # dajax.remove_css_class('#my_form .loading', 'hidden') if form.is_valid(): dajax.remove_css_class('#my_form input', 'error') # dajax.remove_css_class('#status', 'hidden') # result = u'Отправляем сообщение' # dajax.assign('#status', 'value', result) phone = form.cleaned_data.get('phone') product_name = form.cleaned_data.get('product_name') subject = u'Заявка в 1 клик' message = u'Телефон: %s \n Товар: %s' % (phone, product_name) send_mail(subject, message, '*****@*****.**', ['*****@*****.**'], fail_silently=False) order = OrderOneClick(phone=phone, product_name=product_name) order.save() # 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()') else: dajax.remove_css_class('#my_form input', 'error') # dajax.remove_css_class('#status', 'hidden') # result = u'Введите данные' # dajax.assign('#status', 'value', result) 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() # def load_form(request, form): # dajax = Dajax() # dajax.alert("Form is_valid(), your phone is: %s" % form.cleaned_data.get('phone')) # # return dajax.json()
def survey_response_delete(request, id): """Method to delete responses""" dajax = Dajax() try: survey_response = SurveyResponse.objects.get(pk=int(id)) key = survey_response.key keyvalue = survey_response.keyvalue survey_response.delete() #dajax.alert("(%s - %s) is successfully deleted !!" % (key, keyvalue)) except: dajax.alert("%s is not exist !!" % (id)) for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json()
def tipo_turno_form(request, form): dajax = Dajax() form = TipoTurnoForm(deserialize_form(form)) if form.is_valid(): f=form.save() tipo_turno=TipoTurno.objects.get(id=f.id) mansioni=Mansione.objectsGet.all() html_dettagli = render_to_string( 'elenco_tipo_turno/dettagli.html', { 'tipo_turno': tipo_turno, 'mansioni': mansioni } ) dajax.append('#elenco', 'innerHTML', html_dettagli) dajax.script('$("#form_tipo_turno" ).dialog("close"); $( "div#tipo_turno-'+str(f.id)+'.riga a").button(); $( ".dettagli_requisito").hide();') else: dajax.remove_css_class('#form_tipo_turno input', 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'ui-state-error') return dajax.json()
def send_form(request, form): from forms import ExampleForm dajax = Dajax() form = ExampleForm(form) if form.is_valid(): dajax.remove_css_class('#my_form input', 'error') dajax.alert("This form is_valid(), your username is: %s" % form.cleaned_data.get('username')) else: dajax.remove_css_class('#my_form input', 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json()
def verifyFile(request, cloudItem, tokenID, form): """ Verify file and metadata """ dajax = Dajax() try: t = parseAjaxParam(tokenID) ci = checkCloudItem(cloudItem, request.user.id) tkn = checkAccessToken(t, ci) f = VerifyForm(deserialize_form(form)) if f.is_valid(): verType = parseAjaxParam(f.cleaned_data['verificationType']) metaVerification = None downVerification = None dtaVerification = None v = Verifier(tkn) if verType == constConfig.VERIFY_CHOICE_METADATA: metaVerification = v.verifyMetadata() elif verType == constConfig.VERIFY_CHOICE_FILES or verType == constConfig.VERIFY_CHOICE_FILESHISTORY: downVerification = v.verifyFileDownload(verType) elif verType == constConfig.VERIFY_CHOICE_DTA_SIGNATURE: dtaVerification = v.verifyZIP() else: raise Exception("Invalid Verification Type") table = render_to_string( "dashboard/comparator/comparatorVerify.html", { "meta": metaVerification, 'file': downVerification, 'dta': dtaVerification }) dajax.assign("#verifyer", "innerHTML", table) dajax.assign("#verifyerError", "innerHTML", "") dajax.remove_css_class("#verifyerError", ['alert', 'alert-danger']) else: dajax.assign("#verifyer", "innerHTML", "") dajax.assign("#verifyerError", "innerHTML", "Invalid Form") dajax.add_css_class("#verifyerError", ['alert', 'alert-danger']) except Exception as e: dajax.assign("#verifyerError", "innerHTML", formatException(e)) dajax.add_css_class("#verifyerError", ['alert', 'alert-danger']) return dajax.json()
def signup_form(request, form, success_url=None): logger.debug("signup_form") dajax = Dajax() signup_form = SignupForm if userena_settings.USERENA_WITHOUT_USERNAMES: signup_form = SignupFormOnlyEmail form = signup_form(deserialize_form(form)) if form.is_valid(): user = form.save() # Send the signup complete signal userena_signals.signup_complete.send(sender=None, user=user) if success_url: redirect_to = success_url else: redirect_to = reverse('userena_signup_complete', kwargs={'username': user.username}) # A new signed user should logout the old one. if request.user.is_authenticated(): logout(request) dajax.remove_css_class('#sigup_form div', 'error') dajax.clear('#sigup_form .help-inline', 'innerHTML') dajax.redirect(redirect_to, delay=10) #dajax.alert("Form is_valid(), your username is: %s" % form.cleaned_data.get('username')) else: dajax.remove_css_class('#sigup_form div', 'error') dajax.clear('#sigup_form .help-inline', 'innerHTML') dajax.clear('#sigup_form .alert-error', 'innerHTML') dajax.add_css_class('#sigup_form div.alert-error', 'hide') try: if form.errors['__all__'] is not None: dajax.remove_css_class('#sigup_form div.alert-error', 'hide') logger.debug(">>>>>>>>>>>> %s" % form.errors['__all__']) dajax.assign( '#sigup_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('#sigup_form #gr_id_%s' % error, 'error') #dajax.remove_css_class('#sigup_form #e_id_%s' % error, 'hide') dajax.assign('#sigup_form #e_id_%s' % error, 'innerHTML', form.errors[error][0])
def registrosRapidosEditar(request, pk, detregid): dajax = Dajax() cabecera = get_object_or_404(DetallesRegistros, pk=detregid) auxiliar = { "etiqueta": "<strong>%s</strong>: %s" % (_(u"Registros"), cabecera.actividades), 'zona': "<strong>%s</strong>: %s" % (_(u"Zonas"), cabecera.zonas), 'equipos': "<strong>%s</strong>: %s" % (_(u"Equipos"), cabecera.equipos) } detalle = get_object_or_404(Registros, pk=pk) firmas = Firmas.objects.filter( empresa__in=Empresas.objects.filter(usuario__username=request.user), fechabaja=None) out = [] out.append('<option value="" selected="selected">---------</option>') for option in firmas: if option.id == detalle.firmas_id: out.append("<option selected='selected' value='%s'>%s</option>" % (option.id, option.personal.denominacion())) else: out.append("<option value='%s'>%s</option>" % (option.id, option.personal.denominacion())) dajax.assign('#registro', 'innerHTML', '<span> %s </span' % auxiliar['etiqueta']) dajax.assign('#zona', 'innerHTML', '<span> %s </span' % auxiliar['zona']) dajax.assign('#equipo', 'innerHTML', '<span> %s </span' % auxiliar['equipos']) dajax.remove_css_class("#div_id_valor", "control-group hidden") dajax.remove_css_class("#div_id_estado", "control-group hidden") if cabecera.actividades.tipo == 'C': dajax.add_css_class("#div_id_valor", "control-group hidden") dajax.add_css_class("#div_id_estado", "control-group") else: dajax.add_css_class("#div_id_estado", "control-group hidden") dajax.add_css_class("#div_id_valor", "control-group") limpiarRegistros(dajax, cabecera.actividades.tipo) dajax.assign('#id_registros-id', 'value', pk) dajax.assign('#id_registros-detreg_id', 'value', detregid) dajax.assign( '#id_registros-fechadesde', 'value', "%s/%s/%s" % (detalle.fechadesde.day, detalle.fechadesde.month, detalle.fechadesde.year)) dajax.assign('#id_registros-valor', 'value', detalle.valor) dajax.assign('#id_registros-estado', 'checked', detalle.estado) dajax.assign('#id_firmas', 'innerHTML', ''.join(out)) dajax.assign('#id_registros-observaciones', 'value', detalle.observaciones) dajax.script( " $('#myModal').modal('toggle').css({'width': '500px','margin-left': function () {return -($(this).width() / 2);}})" ) return dajax.json()
def createTemplate(request, checked_list, language, time): dajax = Dajax() dajax.add_css_class("#template_output", "brush: %s;" % language) try: extension = extension_dic[language] file_zip = zipfile.ZipFile(dir_download + "lighthouse_%s.zip" % time, "w") makeFile("temp_%s.%s" % (checked_list[0].lower(), extension)) with open(dir_download + '%s.%s' % (time, extension), 'w') as outfile: for item in checked_list: item = item.lower() if language == 'cpp': go = generateTemplate_C(item) else: go = generateTemplate(item) go.make_template() name = "./lighthouse/templateGen/lapack_le/%s/codeTemplates/temp_%s.%s" % ( language, item, extension) file_zip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED) with open(name, "r") as infile: outfile.write(infile.read()) ## display f_output, which contains all routines f_output = open(dir_download + "%s.%s" % (time, extension), "r") dajax.assign("#template_output", 'innerHTML', f_output.read()) dajax.script('SyntaxHighlighter.highlight()') f_output.close() ## write README into the zip file file_zip.write("./lighthouse/templateGen/lapack_le/README", os.path.basename(dir_download + "README"), zipfile.ZIP_DEFLATED) ## write makefile into the zip file file_zip.write(dir_download + "makefile", os.path.basename(dir_download + "makefile"), zipfile.ZIP_DEFLATED) file_zip.close() ## remove makefile from the download directory os.remove(dir_download + "makefile") except: dajax.assign("#template_output", 'innerHTML', 'Coming soon...') return dajax.json()
def assign_test(request, latest_act_id): dajax = Dajax() if latest_act_id is None: latest_act_id = 0 action_list = list( Action.objects.user_stream_latest(request.user, latest_act_id)) size = len(action_list) if (size > 0): dajax.clear('span.newentry', 'innerHTML') dajax.assign( 'span.newentry', 'innerHTML', simplejson.dumps(size) + " new activity recorded, refresh page to see details") dajax.remove_css_class('div.newentry', 'hidden') dajax.add_css_class('div.newentry', 'active') return dajax.json()
def survey_question_delete(request, id): """Method to delete the question & its responses""" dajax = Dajax() try: survey_question = SurveyQuestion.objects.get(pk=int(id)) que = survey_question.question survey_response_list = SurveyResponse.objects.filter( surveyquestion=survey_question) for survey_resp in survey_response_list: survey_resp.delete() survey_question.delete() #dajax.alert("(%s) is successfully deleted !!" % (que)) except: dajax.alert("%s is not exist !!" % (id)) for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json()
def mansione_form(request, form): dajax = Dajax() form = MansioneForm(deserialize_form(form)) if form.is_valid(): i = form.save() dajax.script('$("#form_mansione" ).dialog("close");') #pdb.set_trace() html = '<option value="' + str(i.id) + '">' + str(i.descrizione) + '</option>' dajax.append('#id_competenze', 'innerHTML', html) #dajax.alert("aggiunto!") else: dajax.remove_css_class('#form_tipo_turno input', 'error') for error in form.errors: # error il nome del campo dajax.add_css_class('#id_%s' % error, 'ui-state-error') dajax.script("$('#loading').addClass('hidden');") return dajax.json()
def showTokens(request, ci): """ Show the tokens """ dajax = Dajax() try: data = dict() cloudItemObj = checkCloudItem(ci, request.user.id) data['tknTable'] = DbInterface.getAccessTokenList(cloudItemObj) data['id'] = cloudItemObj.id table = render_to_string("dashboard/tokenTable.html", data) dajax.assign("#tokenTable", "innerHTML", table) dajax.assign("#tokenError", "innerHTML", "") dajax.add_css_class("#tokenError", []) except Exception as e: dajax.assign("#tokenError", "innerHTML", formatException(e)) dajax.add_css_class("#tokenError", ['alert', 'alert-danger']) return dajax.json()
def save_marking_period_average_comment(request, grade_pk, comment): dajax = Dajax() message = "" try: marking_period_average = Grade.objects.get(pk=grade_pk) authorized = False if request.user.is_superuser or request.user.groups.filter( name='registrar').count(): authorized = True else: teacher_course_sections = get_teacher_course_sections( request.user.username) if teacher_course_sections is not None and marking_period_average.course_section in teacher_course_sections: # regular folk can't touch inactive marking periods if marking_period_average.marking_period.active: authorized = True else: message = "You may not modify an inactive marking period." else: message = "You may not modify this course section." if not authorized: raise Exception(message) if marking_period_average.comment != comment: marking_period_average.comment = comment marking_period_average.full_clean() # save() doesn't do validation marking_period_average.save() dajax.add_css_class('#grade-comment{}'.format(grade_pk), 'success') else: # we did nothing dajax.remove_css_class('#grade-comment{}'.format(grade_pk), 'success') dajax.remove_css_class('#grade-comment{}'.format(grade_pk), 'danger') dajax.script('hideAttentionGetter();') except Exception as e: dajax.remove_css_class('#grade-comment{}'.format(grade_pk), 'success') dajax.add_css_class('#grade-comment{}'.format(grade_pk), 'danger') if hasattr(e, 'messages'): message = u'; '.join(e.messages) elif hasattr(e, 'message'): message = e.message dajax.script(u'showAttentionGetter("{}");'.format(message)) return dajax.json()
def order_form(request, form): dajax = Dajax() form = ContactForm(deserialize_form(form)) dajax.add_css_class('#id_phone', 'error') if form.is_valid(): dajax.remove_css_class('#order_form input', 'error') form.clean_phone() response = checkout.process(request) order_number = response.get('order_number', 0) order = response.get('order', 0) # получаем список заказынных товаров для передачи в письмо order_item = OrderItem.objects.filter(order_id=order.id) # test # dajax.assign('#id_email', 'value', errorText) items = '' for item in order_item: items = items + '%s \n' % item.name if order_number: request.session['order_number'] = order_number subject = u'7works заявка от %s' % request.POST['shipping_name'] message = u'Заказ №: %s \n Имя: %s \n телефон: %s \n почта: %s \n id: %s \n Товары: \n %s' % ( order_number, request.POST['shipping_name'], request.POST['phone'], request.POST['email'], order.id, items) send_mail(subject, message, '*****@*****.**', ['*****@*****.**'], fail_silently=False) else: dajax.remove_css_class('#my_form input', 'error') for error in form.errors: errorText = '' if error == 'phone': errorText = u'формат терефона: 89237775522' elif error == 'email': errorText = u'формат email: [email protected]' dajax.add_css_class('#id_%s' % error, 'error') dajax.assign('#id_%s' % error, 'placeholder', errorText) return dajax.json()
def change_atrs(request, option): dajax = Dajax() atrs = ProductVolume.objects.get(id=option) # обновляем инфу без преезагрузки dajax.assign('#volume', 'innerHTML', '%s' % atrs.volume ) dajax.assign('#weight', 'innerHTML', '%s гр.' % atrs.weight ) dajax.assign('#price', 'innerHTML', '%s руб.' % atrs.price ) dajax.assign('#price_old', 'innerHTML', 'Цена: %s руб.' % atrs.price ) dajax.assign('#new_price', 'innerHTML', 'Сейчас: %s руб.' % atrs.new_price ) if atrs.new_price > 0: dajax.remove_css_class('#super_price', 'hidden') dajax.add_css_class('#old_price', 'hidden') else: dajax.add_css_class('#super_price', 'hidden') dajax.remove_css_class('#old_price', 'hidden') dajax.assign('#atr_value', 'value', "%s" % option) return dajax.json()
def calc(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 pair, amount, rate = c.get('pair'), c.get('amount'), c.get('rate') total, commission, pos = pair.calc(amount, rate, ttype, totext=True) dajax.script( "$('#{type}_total_result').text('{total} {right}');".format( **{ "type": ttype, "total": total, "right": pair.right })) dajax.script( "$('#{type}_commission_result').text('{commission} {pos}');". format(**{ "type": ttype, "commission": commission, "pos": pos })) dajax.remove_css_class('#{type}_form input'.format(**{"type": ttype}), 'error') dajax.script("$('#info_{type}').text('{text}');".format(**{ "type": ttype, "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()
def displaySingle(request, cloudItem, tokenID, title, altName, downAltName, fileType): """ Compare files using the previously imported report """ dajax = Dajax() try: t = parseAjaxParam(tokenID) ci = checkCloudItem(cloudItem, request.user.id) tkn = checkAccessToken(t, ci) c = Comparator(tkn) res = c.displaySingle(title, altName, downAltName, fileType) res.update({'imgMimes': constConfig.ALLOWED_MIME_TYPE[1:-1]}) table = render_to_string("dashboard/timeliner/singleViewer.html", res) dajax.assign("#comparator", "innerHTML", table) dajax.assign("#comparatorError", "innerHTML", "") except Exception as e: dajax.assign("#comparatorError", "innerHTML", formatException(e)) dajax.add_css_class("#comparator", ['alert', 'alert-danger']) return dajax.json()
def playcolumn(request, column=None): board = request.session.get('board') player = board.turn if column is None: column = board.playcolumn(player, board.computermove(player)) else: board.playcolumn(player, column) request.session['board'] = board dajax = Dajax() data = { 'turn': board.turn, 'winner': board.winner, 'player': board.currentplayer } dajax.add_data(data, 'update_game_status') cell_selector = '#board tr td:nth-child(%s):not(.played):last' % str( column + 1) dajax.add_css_class(cell_selector, ['player%s' % player, 'played']) dajax.remove_css_class('#board td', ['hover', 'hover-target']) return dajax.json()
def registrosRapidosNuevo(request, pk, sfecha): ano, mes, dia = sfecha[:10].split('-') fecha = ("%s/%s/%s") % (dia, mes, ano) firmas = Firmas.objects.filter( empresa__in=Empresas.objects.filter(usuario__username=request.user), fechabaja=None) out = [] out.append('<option value="" selected="selected">---------</option>') for option in firmas: out.append("<option value='%s'>%s</option>" % (option.id, option.personal.denominacion())) dajax = Dajax() cabecera = get_object_or_404(DetallesRegistros, pk=pk) auxiliar = { "etiqueta": "<strong>%s</strong>: %s" % (_(u"Registros"), cabecera.actividades), 'zona': "<strong>%s</strong>: %s" % (_(u"Zonas"), cabecera.zonas), 'equipos': "<strong>%s</strong>: %s" % (_(u"Equipos"), cabecera.equipos) } dajax.remove_css_class("#div_id_valor", "control-group hidden") dajax.remove_css_class("#div_id_estado", "control-group hidden") if cabecera.actividades.tipo == 'C': dajax.add_css_class("#div_id_valor", "control-group hidden") dajax.add_css_class("#div_id_estado", "control-group") else: dajax.add_css_class("#div_id_estado", "control-group hidden") dajax.add_css_class("#div_id_valor", "control-group") limpiarRegistros(dajax, cabecera.actividades.tipo) dajax.assign('#id_registros-detreg_id', 'value', pk) dajax.assign('#id_registros-fechadesde', 'value', fecha) dajax.assign('#id_firmas', 'innerHTML', ''.join(out)) dajax.assign('#registro', 'innerHTML', '<span> %s </span' % auxiliar['etiqueta']) dajax.assign('#zona', 'innerHTML', '<span> %s </span' % auxiliar['zona']) dajax.assign('#equipo', 'innerHTML', '<span> %s </span' % auxiliar['equipos']) dajax.script( " $('#myModal').modal('toggle').css({'width': '500px','margin-left': function () {return -($(this).width() / 2);}}); " ) return dajax.json()
def formTimeliner(request, cloudItem, tokenID, form): dajax = Dajax() try: t = parseAjaxParam(tokenID) ci = checkCloudItem(cloudItem, request.user.id) tkn = checkAccessToken(t, ci) f = MetaSearch(deserialize_form(form)) if f.is_valid(): tc = TimelinerController(tkn) data = tc.formTimeLine( int(f.cleaned_data['formType'][0]), f.cleaned_data['email'], f.cleaned_data['filename'], f.cleaned_data['givenname'], int(f.cleaned_data['resType'][0]), f.cleaned_data['mimeType'], f.cleaned_data['startDate'], f.cleaned_data['endDate']) if len(data) > 0: if len(data) > 500: dajax.assign( "#formHistoryError", "innerHTML", "Your query returned more than 500 elements. Please refine your search to avoid performance problems with your browser." ) dajax.add_css_class("#formHistoryError", ["alert", "alert-danger"]) else: table = render_to_string( "dashboard/timeliner/historytimeline.html", {'events': data}) dajax.assign("#formHistory", "innerHTML", table) dajax.assign("#formHistoryError", "innerHTML", "") dajax.remove_css_class("#formHistoryError", ["alert", "alert-danger"]) else: dajax.assign("#formHistoryError", "innerHTML", "No data found.") dajax.add_css_class("#formHistoryError", ["alert", "alert-danger"]) else: dajax.assign("#formHistoryError", "innerHTML", "Invalid Form") dajax.add_css_class("#formHistoryError", ["alert", "alert-danger"]) except Exception as e: dajax.assign("#formHistoryError", "innerHTML", formatException(e)) dajax.add_css_class("#formHistoryError", ["alert", "alert-danger"]) return dajax.json()
def employee(request, carnet): dajax = Dajax() hoy = datetime.today() empleado = Empleados.objects.get(ci=carnet) q1 = contratacion.objects.filter(fecha_entrada__lte=hoy, fecha_salida__gte=hoy, estado='ACTIVO') q2 = q1.filter(empleado_id=empleado.id) if q2.count() > 0: dajax.remove_css_class('div #hola1', 'hola') dajax.add_css_class('.btn2', 'btn1') return dajax.json() else: dajax.add_css_class('div #hola1', 'hola') dajax.remove_css_class('.btn1', 'btn1') nombre = empleado.nombre paterno = empleado.paterno materno = empleado.materno direccion = empleado.direccion telefono = empleado.telefono email = empleado.email nac = empleado.fecha_nac civil = empleado.estado_civil sexo = empleado.sexo fecha_nac = nac.strftime("%d/%m/%Y") profe = empleado.profesion_id dajax.assign('#id_nombre', 'value', str(nombre)) dajax.assign('#id_paterno', 'value', str(paterno)) dajax.assign('#id_materno', 'value', str(materno)) dajax.assign('#id_direccion', 'value', str(direccion)) dajax.assign('#id_telefono', 'value', str(telefono)) dajax.assign('#id_email', 'value', str(email)) dajax.assign('#id_fecha_nac', 'value', str(fecha_nac)) data = [{'civil': civil, 'sexo': sexo, 'profesion': profe}] dajax.add_data(data, 'seleccionar') #dajax.add_data(sexo,'sexo') #dajax.assign('#id_nombre','value',str(nombre)) return dajax.json()