def transcode_beaufort( request, container, message="", passphrase="", keyword=None, primer=0, use_digits=False, lower=False, should_filter=False, chunk=0, ): tc = BeaufortTranscoder() result = tc.transcode( message=message, passphrase=passphrase, keyword=keyword, primer=int(primer), use_digits=bool(use_digits), lower=bool(lower), should_filter=bool(should_filter), chunk=int(chunk), ) dajax = Dajax() dajax.assign(container + " .field-target", "value", smart_unicode(result)) return dajax.json()
def _transcode_vigenere( request, container, message="", passphrase="", autoclave=False, keyword=None, primer=0, use_digits=False, lower=False, should_filter=False, chunk=0, encode=True, ): tc = VigenereTranscoder() result = tc.transcode( message=message, passphrase=passphrase, autoclave=bool(autoclave), keyword=keyword, use_digits=bool(use_digits), lower=bool(lower), should_filter=bool(should_filter), chunk=int(chunk), encode=bool(encode), ) dajax = Dajax() dajax.assign(container + " .field-target", "value", smart_unicode(result)) return dajax.json()
def obtener_descripcion_bienes_constancia(req, id_constancia): # Método que obtiene los bienes de la constancia seleccionada, si la constancia ya tiene un aumento o disminucion los toma de la tabla DescripcionBienEndosoAD. dajax = Dajax() datos = list() tieneAumento = False try: descripcionBienAD = DescripcionBienEndosoAD.objects.filter(Constancia_id = id_constancia, Utilizado = 1) if descripcionBienAD: tieneAumento = True for descripcion in descripcionBienAD: sumaBien = descripcion.Cantidad * descripcion.ValorUnitario datos.append({'IdDescripcion':descripcion.IdDescripcionBienEndosoAD,'NombreEquipo':descripcion.NombreEquipo,'Cantidad':str(descripcion.Cantidad),'ValorUnitario':str(descripcion.ValorUnitario),'SumaBien':str(sumaBien)}) else: constancia = Constancia.objects.filter(IdConstancia = id_constancia)[0] relacionAnexaActaVerificacion = RelacionAnexaActaVerificacion.objects.filter(Solicitud_id = constancia.Solicitud_id)[0] descripcionAnexaActaVerificacion = DescripcionBienActaVerificacion.objects.filter(RelacionAnexaActaVerificacion_id = relacionAnexaActaVerificacion.IdRelacionAnexaActaVerificacion) for descripcion in descripcionAnexaActaVerificacion: sumaBien = descripcion.Cantidad * descripcion.ValorUnitario datos.append({'IdDescripcion':descripcion.IdDescripcionBienActaVerificacion,'NombreEquipo':descripcion.NombreEquipo,'Cantidad':str(descripcion.Cantidad),'ValorUnitario':str(descripcion.ValorUnitario),'SumaBien':str(sumaBien)}) except: return dajax.json() return simplejson.dumps({'descripcionBienes':datos, 'tieneAumento':tieneAumento})
def insertElementSequence(request, typeID, xpath, typeName): dajax = Dajax() defaultPrefix = request.session["defaultPrefixCompose"] namespace = request.session["namespacesCompose"][defaultPrefix] xmlString = request.session["newXmlTemplateCompose"] dom = etree.parse(BytesIO(xmlString.encode("utf-8"))) # get the type to add includedType = Type.objects.get(pk=typeID) typeTree = etree.fromstring(includedType.content) elementType = typeTree.find("{http://www.w3.org/2001/XMLSchema}complexType") if elementType is None: elementType = typeTree.find("{http://www.w3.org/2001/XMLSchema}simpleType") type = elementType.attrib["name"] # set the element namespace xpath = xpath.replace(defaultPrefix + ":", namespace) # add the element to the sequence dom.find(xpath).append(etree.Element(namespace + "element", attrib={"type": type, "name": typeName})) includeURL = getSchemaLocation(request, str(typeID)) # add the id of the type if not already present if includeURL not in request.session["includedTypesCompose"]: request.session["includedTypesCompose"].append(includeURL) dom.getroot().insert(0, etree.Element(namespace + "include", attrib={"schemaLocation": includeURL})) # save the tree in the session request.session["newXmlTemplateCompose"] = etree.tostring(dom) print etree.tostring(dom) return dajax.json()
def confirm_edit_section(request, section_code, thread_code, form): dajax = Dajax() try: form_dict={} for obj in form: form_dict[obj['name']]=obj['value'] form = ThreadSectionForm(form_dict) thread_section = ThreadSection.objects.get(code=section_code, thread__code=thread_code) if form.is_valid(): new_section_name = form.cleaned_data.get('section_name') new_section_code = form.cleaned_data.get('section_code') thread_section.name = new_section_name thread_section.code = new_section_code thread_section.save() dajax.assign('#thread_contents', 'innerHTML', \ thread_section.thread.render_html_edit_string()) # if form is not valid else: dajax.assign('#%s_section_name_errors' % section_code, 'innerHTML', form['section_name'].errors) dajax.assign('#%s_section_code_errors' % section_code, 'innerHTML', form['section_code'].errors) except Exception as e: dajax.alert("something wrong: %s" % e) return dajax.json()
def actualizar_aviso(formulario, horaAviso, horaSiniestro, bienesAfectados, tieneAumento, causaSiniestro, idCotizadorCobertura, deducible, participacionAPerdida):# Metodo que nos permite actualizar los datos del aviso de siniestro pasando el formulario y las horas de siniestro y aviso. dajax = Dajax() fechaAviso = formulario.get('dtpFechaAviso'); fechaSiniestro = formulario.get('dtpFechaSiniestro'); if formulario.get('varIdPersonaAvisa') == '' or formulario.get('varIdPersonaAvisa') == 'None': idPersonaAvisa = None else: idPersonaAvisa = formulario.get('varIdPersonaAvisa') if formulario.get('txtOtros') == '': viaAviso = formulario.get('cmbViaAviso') otravia = False else: viaAviso = formulario.get('txtOtros') otravia = True AvisoSiniestro.objects.filter(IdAvisoSiniestro = formulario.get('varIdAvisoSiniestro')).update(Constancia = int(formulario.get('varIdConstancia')), FechaAviso = datetime.datetime.strptime(fechaAviso,'%d/%m/%Y').strftime('%Y-%m-%d'), FechaSiniestro = datetime.datetime.strptime(fechaSiniestro,'%d/%m/%Y').strftime('%Y-%m-%d'), PersonaAvisa = idPersonaAvisa, NombreAvisa = formulario.get('txtQuienAvisa').upper(), ViaAviso = viaAviso.upper(), DescripcionBienAfectado = formulario.get('txtBien').upper(), PersonaTecnico = formulario.get('varIdTecnico'), HoraAviso = str(horaAviso), HoraSiniestro = str(horaSiniestro), OtraVia = otravia, TipoAviso = formulario.get('cmbTipoAviso'), CausaSiniestro = str(causaSiniestro.upper()), IdStatusAvisoSiniestro = int(formulario.get('varStatusAviso')), CausaAgravante = str(formulario.get('txtCausaAgravante').upper()), CotizadorCobertura = idCotizadorCobertura, Deducible = deducible, ParticipacionAPerdida = participacionAPerdida) actualizar_bienes_afectados(bienesAfectados, formulario.get('varIdAvisoSiniestro'), tieneAumento) return dajax.json()
def actualizar_bienes_afectados(bienesAfectados, id_aviso, tieneAumento): # Metodo que nos permite actualizar los bienes afectado en la base de datos. dajax = Dajax() bienesAfectadosGuardado = BienAfectadoAviosoSiniestro.objects.filter(AvisoSiniestro_id = id_aviso) for bienPorDiaEliminar in bienesAfectadosGuardado: encontradoAEliminar = 1 for bienABuscar in bienesAfectados: list_bien = bienABuscar.split(',') if list_bien[0] != '': if int(list_bien[0]) == bienPorDiaEliminar.IdBienAfectado: encontradoAEliminar = 0 break if encontradoAEliminar == 1: eliminar_bien_afectado(bienPorDiaEliminar.IdBienAfectado) for bien in bienesAfectados: list_bien = bien.split(',') if list_bien[0] == '': guardar_bienes_afectados(id_aviso, bien, tieneAumento) else: actualizar_bien_afectado(list_bien) return dajax.json()
def buscar_programas_ejercicio_actual(req, buscarPrograma, tipoSolicitud): # Función que busca todos los programas con cotizador ingresados a la base de datos para mostrarlos en el listado de programas. dajax = Dajax() try: datos = list() year = datetime.datetime.now().year programasFiltrados = TipoSeguro.objects.using('catalogos').filter(Q(DescripcionTipoSeguro__contains = buscarPrograma)) listaProgramas = Programa.objects.filter(Ejercicio = year, Utilizado=1) for programaFiltrado in programasFiltrados: for programa in listaProgramas: # tipoSolicitud = 1 ANUAL, tipoSolicitud = 2 A DECLARACION # ANUAL solo muestra los programas PATRIMONIAL y MAQUINARIA # A DECLARACION muestra programas PATRIMONIAL (BODEGAS, SILOS Y CONTENIDOS), TRANSPORTE Y RIESGOS ALGODONEROS if programaFiltrado.IdTipoSeguro == int(programa.IdTipoSeguro) and (((programaFiltrado.IdTipoSeguro == 1 or programaFiltrado.IdTipoSeguro == 3) and tipoSolicitud==1) or ((programaFiltrado.IdTipoSeguro == 1 or programaFiltrado.IdTipoSeguro == 2 or programaFiltrado.IdTipoSeguro == 4) and tipoSolicitud==2)): tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0] subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0] contrato = ContratoFondo.objects.filter(IdContratoFondo = programa.IdContratoFondo)[0] descripcionMoneda = Moneda.objects.using('catalogos').filter(IdMoneda = programa.IdTipoMoneda)[0] datos.append({'IdPrograma':programa.IdPrograma,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro, 'Ejercicio':programa.Ejercicio,'IdTipoSeguro':programa.IdTipoSeguro,'IdSubTipoSeguro':programa.IdSubTipoSeguro, 'DescripcionMoneda':descripcionMoneda.Nombre, 'IdTipoMoneda':programa.IdTipoMoneda,'Observaciones':programa.Observaciones, 'NumeroContrato':contrato.NumeroContrato,'FolioPrograma':programa.FolioPrograma}) except: return dajax.json() return simplejson.dumps({'programas':datos})
def save_editted_tab(request, form, tab_id): # validates the tab details that were submitted while editing an existing tab tab = Tab.objects.get(id = tab_id) f = TabAddForm(form, instance = tab) if f.is_valid(): event = request.user.get_profile().is_coord_of unsaved_tab = f.save(commit = False) unsaved_tab.event = event unsaved_tab.save() tab = unsaved_tab tabs = get_tabs(event) template = loader.get_template('ajax/events/tab_list.html') t1 = template.render(RequestContext(request,locals())) template2 = loader.get_template('ajax/events/tab_detail.html') t2 = template2.render(RequestContext(request,locals())) dajax = Dajax() dajax.assign('#tabs','innerHTML', t1) dajax.assign('#detail', 'innerHTML', t2) return dajax.json() else: template = loader.get_template('ajax/events/tab_edit_form.html') t = template.render(RequestContext(request,locals())) dajax = Dajax() dajax.assign('#detail', 'innerHTML', t) return dajax.json()
def actualizar_coberturas(coberturas, idPrograma): # Método que permite actualizar las coberturas en la base de datos. dajax = Dajax() coberturasGuardadas = CoberturaPrograma.objects.filter(Programa_id = idPrograma) encontradoAElimiar = 1 for coberturaAEliminar in coberturasGuardadas: for coberturaABuscar in coberturas: if coberturaABuscar == coberturaAEliminar.IdCobertura: encontradoAElimiar = 0 break if encontradoAElimiar == 1: eliminar_cobertura(coberturaAEliminar.IdCoberturaPrograma) coberturaAGuardar = 1 for cobertura in coberturas: for coberturaEncontrada in coberturasGuardadas: if coberturaEncontrada.IdCobertura == cobertura: coberturaAGuardar = 0 break if coberturaAGuardar == 1: guardarCoberturas(cobertura, idPrograma) return dajax.json()
def obtener_programas(req): # Función que busca todos los programas ingresados a la base de datos para mostrarlos en el listado de programas. dajax = Dajax() try: datos = list() listaProgramas = Programa.objects.all().order_by("-IdPrograma") tieneCotizador = 0 for programa in listaProgramas: tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0] subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0] contrato = ContratoFondo.objects.filter(IdContratoFondo = programa.IdContratoFondo)[0] cotizadores = Cotizador.objects.filter(Programa_id = programa.IdPrograma) if cotizadores: tieneCotizador = 1 datos.append({'IdPrograma':programa.IdPrograma,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro, 'Ejercicio':programa.Ejercicio,'IdTipoSeguro':programa.IdTipoSeguro,'IdSubTipoSeguro':programa.IdSubTipoSeguro, 'IdTipoMoneda':programa.IdTipoMoneda,'Observaciones':programa.Observaciones,'NumeroContrato':contrato.NumeroContrato,'FolioPrograma':programa.FolioPrograma, 'Utilizado':programa.Utilizado, 'TieneCotizador':int(tieneCotizador)}) except: return dajax.json() return simplejson.dumps({'programas':datos})
def guardarCoberturas(cobertura, idPrograma): # Método que permite guardar las coberturas en la base de datos pasando el id del programa para enlazar. dajax = Dajax() cuberturaAGuardar = CoberturaPrograma(Programa_id = idPrograma, IdCobertura = cobertura) cuberturaAGuardar.save() return dajax.json()
def guardarAreaInfluencia(area, idPrograma): # Método que permite guardar el área de influencia de un programa. dajax = Dajax() areaInfluenciaAGuardar = AreaInfluenciaPrograma(Programa_id = idPrograma, IdAreaInfluencia = area) areaInfluenciaAGuardar.save() return dajax.json()
def add_trip(request,agent_id,country_ids): dajax = Dajax() dajax.assign('#meeage-alert', 'innerHTML', '') if agent_id and len(country_ids)!= '': agent = Agent.objects.get(id=agent_id) for x in range(0, len(country_ids)): trip = Trip() trip.agent = agent trip.country = Country_Detail.objects.get(id=country_ids[x]) trip.save() print "suceeeesssssssssssss" dajax.append('#meeage-alert','innerHTML', ''' <div class="alert alert-success"> <strong>Success!</strong>Suceefully added new trip </div>''') dajax.script("LocatonReload();") else: dajax.append('#meeage-alert','innerHTML', '''<div class="alert alert-danger"><strong>Danger!</strong> Something went wrong </div>''') return dajax.json()
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()
def update_files(request, value, project_id): """ """ dajax = Dajax() try : p = Project.objects.get(pk=project_id) except Project.DoesNotExist: return dajax.json() out = [] for f in Function.objects.filter(name__contains=value, project=p): fmt_str = "<option value='{0}'>{1} in {2}:{3}</option>" line = f.line if f.line is not None else 0 filename = f.file.name if f.file is not None else "Unknown" funcname = f.name args = [serializers.serialize("xml", [f,]), ] args+= [ escape(x) for x in [funcname, filename, line] ] line = fmt_str.format( *args ) out.append(line) dajax.assign('#function_files', 'innerHTML', '\n'.join(out)) return dajax.json()
def attachment(request, object_id, update_id=None): dajax = Dajax() try: if object_id: attachments = Attachment.objects.filter( attached_object__id=object_id) template = 'core/tags/attachments_block' object_markup = render_to_string(template, {'object_id': object_id, 'attachments': attachments}, context_instance=RequestContext( request), response_format='html') dajax.add_data( {'target': 'div.attachment-block[object="%s"]' % object_id, 'content': object_markup}, 'treeio.add_data') if update_id: attachments = Attachment.objects.filter( attached_record__id=update_id) template = 'core/tags/attachments_record_block' update_markup = render_to_string(template, {'update_id': update_id, 'attachments': attachments}, context_instance=RequestContext( request), response_format='html') dajax.add_data( {'target': 'div.attachment-record-block[object="%s"]' % update_id, 'content': update_markup}, 'treeio.add_data') except Exception, e: print e
def elenco_cerca_persone(request,cerca): #pdb.set_trace() dajax=Dajax() persone=Persona.objects.filter(Q(nome__icontains=cerca) | Q(cognome__icontains=cerca)) html_persona=render_to_string( 'persone/tabella_persone.html', { 'persone': persone, 'stati':STATI, 'request':request } ) dajax.assign("div#tabella_persone", "innerHTML", html_persona) return dajax.json()
def multiply(request): a = int(request.POST['a']) b = int(request.POST['b']) c = a * b dajax = Dajax() dajax.assign('#result', 'value', str(c)) return dajax.calls
def persona_stato(request,stato,persona): dajax=Dajax() per=Persona.objects.get(id=persona) per.stato=stato per.save() 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});') return dajax.json()
def submit_new_tags(request, form, image_id): print request.POST dajax = Dajax() # TODO start here dajax.script('add_categories();') return dajax.json()
def submit_creation_techniques(request, form, image_id): read_category_form(form) print request.POST dajax = Dajax() dajax.script('add_description();') return dajax.json()
def add_form(request,value): dajax = Dajax() import sorl.thumbnail import PIL if value==1: advertform = AdvertForm( initial = {'user':request.user}, # error_class=DivErrorList, ) if value ==2: advertform = AdvertForm2( initial = {'user':request.user}, # error_class=DivErrorList, ) contactform = ContactInfoForm( # error_class=DivErrorList, ) FormSet = PhotoFormSet(queryset=Photo.objects.none()) # render = render_to_string('new_house.html') c={'form':advertform, 'contactform':contactform,'formset':FormSet} c.update(csrf(request)) if value==1: id = 'in1' render = render_to_string('advert/add_tab21.html',c ) if value==2: id = 'in2' render = render_to_string('advert/add_tab22.html',c) dajax.assign('#'+id, 'innerHTML', render) return dajax.json()
def edit_add_form(request,adid): dajax = Dajax() #print "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA" adv = Advert.objects.get(pk=adid) contact = ContactInfo.objects.get(pk=adv.contact.id) pictures = Photo.objects.filter(advert=adid) value = adv.realtype.subtype_id #countryarea = CountryArea.objects.get(pk=adv.city.area.id) #adv.countryarea = CountryArea.objects.filter(pk=adv.city.area.id) value = int(value) if value==1: advertform = AdvertFormEdit(instance=adv) if value ==2: advertform = AdvertForm2Edit(instance=adv) contactform = ContactInfoForm(instance=contact) FormSet = PhotoFormSet2(queryset=Photo.objects.filter(advert=adid)) #advertform.id = adid # render = render_to_string('new_house.html') c={'form':advertform, 'contactform':contactform,'formset':FormSet,'pictures':pictures,'advert_id':adid} c.update(csrf(request)) if value==1: id = 'in1' render = render_to_string('advert/edit_add_tab21.html',c ) if value==2: id = 'in2' render = render_to_string('advert/edit_add_tab22.html',c) dajax.assign('#'+id, 'innerHTML', render) return dajax.json()
def move_content_down(request, threadcontent_id): dajax = Dajax() try: thread_content=ThreadContent.objects.get(id=threadcontent_id) this_section = thread_content.section # if next content in section, switch order next_content = thread_content.find_next_in_section() if next_content: this_sort_order = thread_content.sort_order next_sort_order = next_content.sort_order # if sort_orders are the same, # redo all sort orders before continuing if this_sort_order==next_sort_order: for (i,tc) in enumerate(thread_content.section.threadcontent_set.all()): tc.sort_order=i tc.save() thread_content = ThreadContent.objects.get(id=threadcontent_id) next_content = thread_content.find_next_in_section() this_sort_order = thread_content.sort_order next_sort_order = next_content.sort_order thread_content.sort_order = next_sort_order next_content.sort_order = this_sort_order thread_content.save() next_content.save() # rewrite just thread content of section dajax.assign('#threadcontent_%s' % this_section.code, \ 'innerHTML', \ this_section.return_content_html_string(edit=True)) # if content is last in section, move to beginning of next section else: next_section = thread_content.section.find_next_section() if next_section: other_content=next_section.threadcontent_set.all() if other_content: first_sort_order=other_content[0].sort_order new_sort_order = first_sort_order-1 else: new_sort_order = 0 thread_content.section = next_section thread_content.sort_order = new_sort_order thread_content.save() # rewrite just thread content of section and next_section dajax.assign('#threadcontent_%s' % this_section.code, \ 'innerHTML', \ this_section.return_content_html_string(edit=True)) dajax.assign('#threadcontent_%s' % next_section.code, \ 'innerHTML', \ next_section.return_content_html_string(edit=True)) except Exception as e: dajax.alert("something wrong: %s" % e) return dajax.json()
def updateJobs(req): dajax = Dajax() out = render_to_string("jobs.html", dict(jobs=Job.objects.all().order_by('-started'))) dajax.assign('#jobsHole','innerHTML', out) return dajax.json()
def move_section_down(request, section_code, thread_code): dajax = Dajax() try: thread_section = ThreadSection.objects.get(code=section_code, thread__code=thread_code) next_section = thread_section.find_next_section() if next_section: this_sort_order=thread_section.sort_order next_sort_order=next_section.sort_order # if sort_orders are the same, # redo all sort orders before continuing if this_sort_order==next_sort_order: for (i,ts) in enumerate(thread_section.thread.thread_sections.all()): ts.sort_order=i ts.save() thread_section = ThreadSection.objects.get(code=section_code, thread__code=thread_code) next_section = thread_section.find_next_section() this_sort_order=thread_section.sort_order next_sort_order=next_section.sort_order thread_section.sort_order = next_sort_order next_section.sort_order = this_sort_order thread_section.save() next_section.save() dajax.assign('#thread_contents', 'innerHTML', \ thread_section.thread.render_html_edit_string()) except: pass return dajax.json()
def setCurrentTemplate(request, templateFilename, templateID): print "BEGIN def setCurrentTemplate(request)" request.session["currentComposeTemplate"] = templateFilename request.session["currentComposeTemplateID"] = templateID request.session.modified = True print ">>>>" + templateFilename + " set as current template in session" dajax = Dajax() if templateID != "new": templateObject = Template.objects.get(pk=templateID) if templateID in MetaSchema.objects.all().values_list("schemaId"): meta = MetaSchema.objects.get(schemaId=templateID) xmlDocData = meta.api_content else: xmlDocData = templateObject.content request.session["xmlTemplateCompose"] = xmlDocData request.session["newXmlTemplateCompose"] = xmlDocData else: base_template_path = os.path.join(settings.SITE_ROOT, "static/resources/xsd/new_base_template.xsd") base_template_file = open(base_template_path, "r") base_template_content = base_template_file.read() request.session["xmlTemplateCompose"] = base_template_content request.session["newXmlTemplateCompose"] = base_template_content print "END def setCurrentTemplate(request)" return dajax.json()
def refreshInGameStats(request, game_id, player_id): players = Player.objects.filter(game=game_id).order_by('-succesful_sneaks') dajax = Dajax() render = render_to_string('pamplesneak/ingamestats.html', {'players': players}) dajax.assign('#ingame_stats', 'innerHTML', render) return dajax.json()
def buscar_usuarios2(request, pagina, criterio, cargo_usuario, proyecto_id): dajax = Dajax() if request.user.is_authenticated(): request.session.set_expiry(600) proyecto = Proyecto.objects.get(id=proyecto_id) #Se asigna la variable guardada en la session personas_seleccionadas = request.session['personas_seleccionadas'] qry = "SELECT * FROM inverboy_usuario u, auth_user au WHERE u.user_ptr_id=au.id AND au.is_active=1" criterio = criterio.strip() if criterio != "": if criterio != '': criterio = criterio.replace("'",'"') try: criterio = int(criterio) qry = qry + " AND identificacion="+str(criterio) except: qry = qry + " AND (CONCAT(first_name, ' ', last_name) LIKE '%%" + criterio + "%%' OR username LIKE '%%"+criterio+"%%')" if(cargo_usuario!="0"): qry = qry + " AND cargo='" + cargo_usuario + "'" usuarios = Usuario.objects.raw(qry) lista_usuarios = [] for usuario in usuarios: lista_usuarios.append(usuario) pag = Paginador(request, lista_usuarios, 20, pagina) user = request.user render = render_to_string('ajax/personassearchproyecto.html', {'user': user, 'lista_usuarios': pag, 'criterio': criterio, 'cargo_usuario': cargo_usuario, 'personas_seleccionadas': personas_seleccionadas, 'proyecto': proyecto }) dajax.assign('#light','innerHTML', render) dajax.script("document.getElementById('light').style.display='block';") dajax.script("document.getElementById('fade').style.display='block';") else: dajax.redirect('/inverboy/') return dajax.json()
def siteLogout(request): dajax = Dajax() logout(request) dajax.script("location.reload();") return dajax.json()
def rateResource(request, type, id, rating): dajax = Dajax() if type == "a": resource = Activity.objects.get(pk=id) elif type == "p": resource = Project.objects.get(pk=id) if request.user.is_authenticated(): resource.rating.add(rating, request.user, request.META['REMOTE_ADDR']) else: resource.rating.add(rating, None, request.META['REMOTE_ADDR']) dajax.script("$('#starRead').raty('readOnly', false);") scriptStr = "$('#starRead').raty('score', " + str( resource.rating.get_real_rating()) + ");" dajax.script(scriptStr) dajax.script("$('#starRead').raty('readOnly', true);") dajax.script("$('#star').raty('readOnly', true);") dajax.assign('#numVotes', 'innerHTML', "(" + str(resource.rating.votes) + ")") return dajax.json()
def addComment(request, type, id, comment): dajax = Dajax() if type == "a": resource = Activity.objects.get(pk=id) elif type == "p": resource = Project.objects.get(pk=id) c = resource.comment_set.create(user=request.user, comment=comment) commentCode = '<li class="media"><div class="media-body"><h5 class="media-heading">' + c.user.name + '</h5>' + comment + '</div></li>' dajax.append('#commentsList', 'innerHTML', commentCode) noOfComments = resource.comment_set.count() if noOfComments == 1: dajax.assign('#noOfComments', 'innerHTML', '<h5>1 Comment</h5>') else: dajax.assign('#noOfComments', 'innerHTML', '<h5>' + str(noOfComments) + ' Comments</h5>') dajax.assign('#commentBox', 'value', '') return dajax.json()
def gradeResFind(request, id): dajax = Dajax() grade = Grade.objects.get(pk=id) htmlStr = "" for s in grade.subject_set.all(): tempStr = "<li class='dropText' onClick='selSubject(%d, this)'> %s <" % ( s.id, s.title) htmlStr += tempStr #dajax.assign('#graSelection','innerHTML',grade.title) dajax.assign('#subSelection', 'innerHTML', "Select Subject") dajax.assign('#drop3', 'innerHTML', htmlStr) if big: dajax.assign( '#findButton', 'innerHTML', "<a class='btn btn-large btn-danger disabled'>Find Resources</a>") else: dajax.assign( '#findButton', 'innerHTML', "<a class='btn btn-small btn-danger disabled'>Find Resources</a>") return dajax.json()
def siteLogin(request, email, password): dajax = Dajax() user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) dajax.script("location.reload();") else: dajax.assign('#loginResult', 'innerHTML', "Invalid email/password") dajax.script("$('#loginResult').css('display', 'block');") dajax.assign('#passwordInput', 'value', "") return dajax.json()
def add_edit_coord(request,form="",id=0): """ This function calls the AddCoordForm from forms.py If a new coord is being created, a blank form is displayed and the core can fill in necessary details. If an existing coord's details is being edited, the same form is displayed populated with current coord details for all fields """ dajax = Dajax() if form == "" : if id: template = loader.get_template('ajax/core/editcoord.html') coord=User.objects.get(id=id) coord_form = AddCoordForm(instance=coord,initial={'event':coord.get_profile().is_coord_of_id,}) html=template.render(RequestContext(request,locals())) else: template = loader.get_template('ajax/core/addcoord.html') coord_form = AddCoordForm() html=template.render(RequestContext(request,locals())) dajax.assign('#space', 'innerHTML', html) return dajax.json() if id: coord_form = AddCoordForm(form, instance=User.objects.get(id=id)) if coord_form.is_valid(): coord=coord_form.save() coord_profile=coord.get_profile() coord_profile.is_coord_of_id=form['event'] coord_profile.save() dajax.assign("#space",'innerHTML',"") else: template = loader.get_template('ajax/core/editcoord.html') html=template.render(RequestContext(request,locals())) dajax.assign("#space",'innerHTML',html) else: coord_form = AddCoordForm(form) if coord_form.is_valid(): coord=coord_form.save() coord.set_password("default") coord.groups.add(request.user.groups.get_query_set()[1]) coord.save() coord_profile = UserProfile(user=coord, is_coord_of_id=form['event']) coord_profile.save() dajax.assign("#space",'innerHTML',"") else: template = loader.get_template('ajax/core/addcoord.html') html=template.render(RequestContext(request,locals())) dajax.assign("#space",'innerHTML',html) dajax.script("updateSummary();") return dajax.json()
def editUser(request, form, user_id): dajax = Dajax() form = deserialize_form(form) user = KittyUser.objects.get(id=user_id) user_form = KittyUserForm(form, instance=user) if user_form.is_valid(): dajax.remove_css_class('.form-group', 'has-error') # create new item in DB user = user_form.save() dajax.script("$('#editUserModal').modal('hide');") dajax.script("location.reload();") else: dajax.remove_css_class('.form-group', 'has-error') for error in user_form.errors: dajax.script( "$('#id_%s').parent().parent().addClass('has-error')" % error) return dajax.json()
def editItem(request, form, item_id): dajax = Dajax() form = deserialize_form(form) item = Item.objects.get(id=item_id) item_form = ItemForm(form, instance=item) if item_form.is_valid(): dajax.remove_css_class('.form-group', 'has-error') # create new item in DB item = item_form.save() dajax.script("$('#editItemModal').modal('hide');") dajax.script("location.reload();") else: dajax.remove_css_class('.form-group', 'has-error') for error in item_form.errors: dajax.script( "$('#id_%s').parent().parent().addClass('has-error')" % error) return dajax.json()
def decItem(request, item_id): dajax = Dajax() user_item = UserItem.objects.get(id=item_id) # dec item count user_item.quantity -= 1 # giv back money to user user = user_item.user user.money += user_item.item.price # save both user_item.save() user.save() item = user_item.item item_quantity = item.useritem_set.all().aggregate(Sum('quantity')) # change frontend to new value dajax.assign('#id_user_item_%s' % item_id, 'innerHTML', user_item.quantity) dajax.assign('#id_user_name_%s' % user.id, 'innerHTML', '%s (%s EUR)' % (user.name, user.money)) dajax.assign('#id_item_quantity_consumed_%s' % item.id, 'innerHTML', item_quantity['quantity__sum']) dajax.assign('#id_item_quantity_available_%s' % item.id, 'innerHTML', item.quantity - item_quantity['quantity__sum']) brodcastUpdateUserItem(user_item) return dajax.json()
def custom_field(request): data = {} requestProcessor = HttpRequestProcessor(request) dajax = Dajax() ajax = requestProcessor.getParameter('ajax') if (ajax != None): if (ajax == 'create_custom_field'): data['form_id'] = 'create_custom_field' data['field_title'] = requestProcessor.getParameter('field_title') data['field_value'] = requestProcessor.getParameter('field_value') data['jurisdiction_id'] = requestProcessor.getParameter( 'jurisdiction_id') data['category_id'] = requestProcessor.getParameter('category_id') data['current_category'] = requestProcessor.getParameter( 'current_category') data['current_questions'] = requestProcessor.getParameter( 'current_questions') if data['field_title'] == None: data['field_title'] = '' if data['field_value'] == None: data['field_value'] = '' data['jurisdiction'] = Jurisdiction.objects.get( id=data['jurisdiction_id']) body = requestProcessor.decode_jinga_template( request, 'website/blocks/create_custom_field.html', data, '') dajax.assign('#fancyboxformDiv', 'innerHTML', body) script = requestProcessor.decode_jinga_template( request, 'website/blocks/create_custom_field.js', data, '') dajax.script(script) dajax.script('controller.showModalDialog("#fancyboxformDiv");') return HttpResponse(dajax.json()) if (ajax == 'create_custom_field_submit'): data = {} data['form_id'] = 'create_custom_field' data['field_title'] = requestProcessor.getParameter('field_title') data['field_value'] = requestProcessor.getParameter('field_value') data['jurisdiction_id'] = requestProcessor.getParameter( 'jurisdiction_id') data['category_id'] = requestProcessor.getParameter('category_id') current_category = requestProcessor.getParameter( 'current_category') current_questions = requestProcessor.getParameter( 'current_questions') error_message = {} error_message = validate_create_custom_field_form_data( data, data['form_id']) if len(error_message) == 0: msg_key = data['form_id'] + '_fail_reason' try: jurisdiction = Jurisdiction.objects.get( id=data['jurisdiction_id']) # look up template CF for this jurisdiction templates = Template.objects.filter( jurisdiction=jurisdiction, template_type__iexact='CF') if len(templates) > 0: template = templates[0] else: template = Template() template.template_type = 'CF' template.name = 'Jurisdiction Custom Field Template' template.jurisdiction_id = data['jurisdiction_id'] #template.create_datetime = datetime.datetime.now() template.save() # create the question category_obj = QuestionCategory.objects.get( id=data['category_id']) ''' questions = Question.objects.filter(category=category_obj, accepted=1).order_by('-display_order') last_question = questions[0] if last_question.display_order == None or last_question.display_order == '': display_order = 0 else: display_order = last_question.display_order ''' highest_display_order_obj = Question.objects.filter( category=category_obj, accepted=1).aggregate(Max('display_order')) #print highest_display_order_obj if highest_display_order_obj == None: highest_display_order = 0 else: highest_display_order = highest_display_order_obj[ 'display_order__max'] question_obj = Question() question_obj.category_id = data['category_id'] question_obj.question = data['field_title'] question_obj.label = data['field_title'] question_obj.form_type = 'CF' question_obj.qtemplate_id = template.id question_obj.accepted = 1 question_obj.display_order = int(highest_display_order) + 5 #question_obj.create_datetime = datetime.datetime.now() question_obj.creator_id = request.user.id question_obj.save() template_question = TemplateQuestion() template_question.template_id = template.id template_question.question_id = question_obj.id #template_question.create_datetime = datetime.datetime.now() template_question.save() # save the answer data_answer = {} data_answer['value'] = data['field_value'] answer = json.dumps(data_answer) # to convert to json is_callout = 0 answer_reference_class_obj = AnswerReference() #action_category_objs = ActionCategory.objects.filter(name__iexact='AddRequirement') #action_category_obj = action_category_objs[0] validation_util_obj = FieldValidationCycleUtil() arcf = validation_util_obj.save_answer( question_obj, answer, jurisdiction, 'AddRequirement', request.user, is_callout) except Exception, e: data[msg_key] = e.message print e.message #else: if len(error_message) > 0: for msg_key in error_message.keys(): data[msg_key] = error_message.get(msg_key) body = requestProcessor.decode_jinga_template( request, 'website/blocks/create_custom_fields.html', data, '') dajax.assign('#fancyboxformDiv', 'innerHTML', body) script = requestProcessor.decode_jinga_template( request, 'website/blocks/create_custom_fields.js', data, '') dajax.script(script) else: data_cf = {} jurisdiction = Jurisdiction.objects.get( id=data['jurisdiction_id']) data_cf['jurisdiction'] = jurisdiction ''' question_category_obj = QuestionCategory.objects.get(id=data['category_id']) data['question_categories'] = QuestionCategory.objects.filter(id=data['category_id']) question_class_obj = Question() custom_questions = question_class_obj.get_custom_fields_by_jurisdiction_by_category(jurisdiction, data['category_id']) print custom_questions validation_util_obj = FieldValidationCycleUtil() data['action'] = 'refresh_ahj_qa' if custom_questions != None and len(custom_questions) > 0: for question in custom_questions: data['question_content'][question_category_obj.id][question.id] = validation_util_obj.get_AHJ_question_data(request, jurisdiction, question, data) ''' ''' validation_util_obj = FieldValidationCycleUtil() data_cf['this_question'] = question_obj question_content = validation_util_obj.get_AHJ_question_data(request, jurisdiction, question_obj, data_cf) for key in question_content.keys(): data_cf[key] = question_content.get(key) body = requestProcessor.decode_jinga_template(request,'website/jurisdictions/AHJ_question_content_authenticated.html', data_cf, '') dajax.assign('#div_custom_question_content_'+str(category_obj.id),'innerHTML', body) script = requestProcessor.decode_jinga_template(request,'website/jurisdictions/AHJ_question_content.js', data, '') dajax.script(script) ''' template_obj = Template() jurisdiction_templates = template_obj.get_jurisdiction_question_templates( jurisdiction) data_cf['action'] = '/jurisdiction_id/' + str( jurisdiction.id) + '/' + current_category + '/' current_questions = current_questions.split(',') data_cf['custom_questions'] = Question.objects.filter( category=category_obj, accepted=1, qtemplate__in=jurisdiction_templates).exclude( id__in=(current_questions)) body = requestProcessor.decode_jinga_template( request, 'website/jurisdictions/AHJ_question_content_ajax_call.html', data_cf, '') dajax.assign( '#div_custom_question_content_' + str(category_obj.id), 'innerHTML', body) script = requestProcessor.decode_jinga_template( request, 'website/jurisdictions/AHJ_question_content_ajax_call.js', data_cf, '') dajax.script(script) ###################################################### #data['custom_questions'] = custom_questions #data['custom_questions'] = {} #data['custom_questions'][question_category_obj.id] = custom_questions #body = requestProcessor.decode_jinga_template(request,'website/blocks/custom_fields.html', data, '') #dajax.assign('#custom_fields_'+str(question_category_obj.id),'innerHTML', body) dajax.script('jQuery.fancybox.close();') dajax.script( "controller.showMessage('Custom field created.', 'success')" ) dajax.script( 'controller.updateUrlAnchor("#create_custom_field");') if current_category == 'all_info': question_categories = QuestionCategory.objects.filter( accepted=1) data['category'] = 'All categories' else: question_categories = QuestionCategory.objects.filter( name__iexact=category_obj.name) data['category'] = category_obj.name #data['category'] = question_obj.category.name data['jurisdiction'] = jurisdiction validation_util_obj = FieldValidationCycleUtil() data[ 'top_contributors'] = validation_util_obj.get_top_contributors( jurisdiction, question_categories) body = requestProcessor.decode_jinga_template( request, 'website/blocks/top_contributors.html', data, '') dajax.assign('#top_contributors', 'innerHTML', body) return HttpResponse(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 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 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 compareFromReport(request, cloudItem, tokenID): """ 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.compareFromReport() table = render_to_string("dashboard/comparator/comparatorCompare.html", {'files': res}) dajax.assign("#comparator", "innerHTML", table) dajax.assign("#comparatorError", "innerHTML", "") dajax.remove_css_class("#comparatorError", ['alert', 'alert-danger']) except Exception as e: dajax.assign("#comparatorError", "innerHTML", formatException(e)) dajax.add_css_class("#comparator", ['alert', 'alert-danger']) return dajax.json()
def ingresar(sesion, act, estado, contrato): dajax = Dajax() scripting = None if act.tipoDeSolicitud.id == 1: scripting = ingresarServicioNuevo(sesion, contrato) elif act.tipoDeSolicitud.id == 13: scripting = ingresarCambioDeMedidor(sesion, contrato) elif act.tipoDeSolicitud.id == 11: scripting = ingresarCambioDeMaterial(sesion, contrato) if scripting is not None: scripting = scripting.elegirPunto(estado, act) print scripting if scripting['estado']: if str(scripting['estado']) == '13': dajax.script("$('#cargandoForm').addClass('hidden');") dajax.script("newUrl('/ingreso/" + str(act.id) + "');") else: dajax.assign('id_numeroDeSolicitud', 'value', scripting['solicitud']) dajax.script("$('#lblEspera').html('" + str(scripting['mensaje']) + "');") dajax.script("continuarIngresoSico('/continuaringreso/" + str(act.id) + "');") else: dajax.script("$('#cargandoForm').addClass('hidden');") dajax = mostraError(dajax, {'Error': scripting['mensaje']}, '#err') else: dajax.script("$('#cargandoForm').addClass('hidden');") dajax = mostraError(dajax, {'Error': 'No se pudo completar la accion...'}, '#err') return dajax.calls
def node(request, key): dajax = Dajax() data = render_to_string("website/templates/node-{0}.html".format(key)) dajax.assign('#databox', 'innerHTML', data) return dajax.json()
def guardarIngreso(request): if request.method == 'POST': print request.POST dajax = Dajax() dajax.script("$('#cargandoForm').addClass('hidden');") form = ingresoForm( data=QueryDict(request.POST.urlencode(), mutable=True)) if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data ts = form.data['tipoDeSolicitud'] #if ts == '11' or ts == '13': #en caso de ser un nuevo guardado... med = medidor() cli = cliente() if form.data['id'] != '0': act = actividad.objects.get(id=int(form.data['id'])) cli = act.cliente print 'Se obtuvo el id del cliente nuevo a actualizar' try: med = medidor.objects.get(actividad=act, contrato=None) med.lectura = str(form.data['lecturaRev']) print 'medidor revisado' except: pass if len(form.data['cedula']) == 13: t = 'J' print u'Es persona jurídica' else: t = 'N' print u'Es persona natural' cli.ci_ruc = form.data['cedula'] cli.nombre = form.data['nombreDeCliente'] cli.tipo = t cli.telefono = form.data['telefono'] print 'se generó el cliente nuevo' try: if ts == '1': cliref = request.session['clienteRef'] cliref.ubicacionGeografica.calle.descripcion1 = form.data[ 'direccionRef'] medref = request.session['medidorRef'] print 'es s/N (1)' else: cli = request.session['cliente'] cli.tipo = t cli.telefono = form.data['telefono'] med = request.session['medidor'] med.instance.lectura = str(form.data['lecturaRev']) print 'NO es s/N' except: try: #en caso de ser actualizacion cli = cliente.objects.get( id=cli.id, cuenta=(form.data['codigoDeCliente']).strip(), ci_ruc=(form.data['cedula']).strip()) cli.nombre = form.data['nombreDeCliente'] cli.tipo = t cli.telefono = form.data['telefono'] print 'cliente a actualizar' cli.save(force_update=True) if ts != '1': med.save(force_update=True) enlace = detalleClienteMedidor.objects.get(cliente=cli, medidor=med) print enlace else: if med.id > 0: med.delete() ref = detalleClienteReferencia.objects.get( cliente=cli).referencia call = ref.ubicacionGeografica.calle call.descripcion1 = form.data['direccionRef'] call.save(force_update=True) #actualizar id = form.save(request.session['contrato'], cliente=cli) dajax.script("GuardadoCorrectamenteAjax('/ingreso/" + str(id) + "');") return dajax.calls except: dajax = mostraError( dajax, {'Error': 'Datos invalidos para guardar...'}, '#err') return dajax.calls #guardar por primera vez cli.save() if ts == '1': cliref.save() medref.instance.save() fi = formatFechas(medref.fields['fi'].initial) fd = formatFechas(medref.fields['fd'].initial) d = detalleClienteMedidor( cliente=cliref, medidor=medref.instance, lectura_instalacion=float(medref.fields['li'].initial), lectura_desinstalacion=float(medref.fields['ld'].initial), fecha_instalacion=fi, fecha_desinstalacion=fd, ) d.save() dcr = detalleClienteReferencia( ubicacion=cliref.ubicacionGeografica, cliente=cli, referencia=cliref, medidorDeReferencia=medref.instance.fabrica) dcr.save() if med.id: med.delete() else: med.instance.save() fi = formatFechas(med.fields['fi'].initial) fd = formatFechas(med.fields['fd'].initial) d = detalleClienteMedidor( cliente=cli, medidor=med.instance, lectura_instalacion=float(med.fields['li'].initial), lectura_desinstalacion=float(med.fields['ld'].initial), fecha_instalacion=fi, fecha_desinstalacion=fd, ) d.save() print 'Correcto...' id = form.save(request.session['contrato'], cliente=cli) dajax.script("GuardadoCorrectamenteAjax('/ingreso/" + str(id) + "');") #dajax.script("window.setTimeout(\"newUrl('/ingreso/" + str(id) + "')\",5000);") else: print dict(form.errors) dajax = mostraError(dajax, form.errors, '#err') try: del request.session['clienteRef'] del request.session['medidorRef'] del request.session['cliente'] del request.session['medidor'] except: pass return dajax.calls else: return None
def eliminarIngreso(request, pk): if request.method == 'POST': print request.POST dajax = Dajax() dajax.script("$('#cargandoForm').addClass('hidden');") form = ingresoForm( data=QueryDict(request.POST.urlencode(), mutable=True)) if form.is_valid(): act = actividad.objects.get(id=int(pk)) if int(form.data['id']) == act.id: #borrando detalles de existir #de medidores... for m in list(medidor.objects.filter(actividad__id=act.id)): try: m.actividad = None if m.contrato: m.est = True m.save(force_update=True) except: pass #de sellos for s in list(sello.objects.filter(utilizado__id=act.id)): try: s.utilizado = None s.ubicacion = 'N/A' s.save(force_update=True) except: pass #de rubros for r in list( detalleDeActividad.objects.filter( actividad__id=act.id)): try: r.delete() except: pass #de materiales for m in list( materialDeActividad.objects.filter(actividad=act)): #mat = detalleMaterialContrato.objects.get(id=m.material.id) #mat.stock += m.cantidad #mat.save(force_update=True) m.delete() #deFotos for fot in list(foto.objects.filter(actividad=act)): fot.delete() for p in act.posicion_set.all(): p.actividad = None p.save(force_update=True) act.delete() dajax.script("newUrl('/listadeingresos');") return dajax.calls dajax = mostraError( dajax, { 'Error': 'Datos inconsistentes para proceder a eliminacion de actividad...' }, '#err') return dajax.calls else: return None
def buscarReferencia(request): if request.method == 'POST': dato = request.POST['dato'] print dato print request.user dajax = Dajax() try: #validando ando usuario = request.user #usuario = User.objects.first() bucqModel = vitacoraBusquedas(tipoBusq='2', consulta=dato, usuario=usuario, estadoRetorno=True) form = BusquedaForm( { 'usuario': usuario.id, 'estadoRetorno': True, 'tipoBusq': '2', 'consulta': dato }, instance=bucqModel) if form.is_valid(): buscando = b(usuario.sesion_sico) data = buscando.busquedaDeTipo('2', dato, paraIngreso=True) request.session['clienteRef'] = data['formCliente'].instance request.session['medidorRef'] = data['cMedidores'][0] #data = MedidorBuscado('marca','tecnologia', 'tension', 'amp', 'fi', 'fd', 'li', 'ld', #instance=medidor.objects.first()) if data is not None: dajax.assign( '#id_cuentaAnteriror', 'value', '' + str(data['formCliente'].instance.cuenta) + '') dajax.script("$('#id_serieAnteriror').val('" + str(data['cMedidores'][0].instance.serie) + "');") dajax.assign( '#id_marcaAnteriror', 'value', '' + str(data['cMedidores'][0].fields['marc'].initial) + '') else: dajax = mostraError(dajax, {'Referencia': 'No Encontrada'}, '#errRef') else: print form.errors dajax = mostraError(dajax, {'': dict(form.errors)['__all__']}, '#errRef') except: dajax = mostraError(dajax, {'Error': 'No se pudo Buscar'}, '#errRef') dajax.add_css_class('#cargandoRef', 'hidden') return dajax.calls else: return None
def buscarMedidor(request): if request.method == 'POST': idMedidor = request.POST['medidor'] print idMedidor dajax = Dajax() try: med = medidor.objects.get(id=int(idMedidor)) dajax.assign('#id_fabricaInst', 'value', '' + str(med.fabrica) + '') dajax.assign('#id_marcaInst', 'value', '' + str(med.marca) + '') dajax.script("$('#id_serieInst').val('" + str(med.serie) + "').change();") dajax.assign('#id_tipoDeMedidor', 'value', '' + str(med.tipo) + '') dajax.assign('#id_lecturaInst', 'value', '' + str(med.lectura) + '') dajax.script("$('#id_serieInst').change();") except: dajax.assign('#id_fabricaInst', 'value', '') dajax.assign('#id_marcaInst', 'value', '') dajax.assign('#id_serieInst', 'value', '') dajax.assign('#id_tipoDeMedidor', 'value', '') dajax.assign('#id_lecturaInst', 'value', '') return dajax.calls else: return None
def delete_tasks(request, selected): dajax = Dajax() tasks = Task.objects.filter(id__in=map(int, selected)).delete() runs = Run.objects.filter(task__in=map(int, selected)).delete() dajax.redirect('/tasks/') 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 send_form(request, form): dajax = Dajax() form = RegistrationFormFranchisee(deserialize_form(form)) if request.method == 'POST': if form.is_valid(): # instantiating object UserRegistration formf = UserRegistration(form) # JSON for form data data = formf.cleanData() # validation data: Franchisee code, email, Franchisee validFranchisee = formf.validDataFranchisee() print validFranchisee #checking fields not in use if (validFranchisee['franchisee'] == True and validFranchisee['email'] == True and validFranchisee['franchiseeCode']['flag'] == True and validFranchisee['franchiseeCode']['id'] >= 0): formf.saveUser() formf.activationKey() formf.newUserProfile() # change in the respective fields successful color for field in form.fields: # removing the entry fields dajax.remove('#id_%s' % field) # adding fields not editable dajax.append( '#f_%s' % field, 'innerHTML', '<span id="id_%s" class="input-medium uneditable-input">No puede Modificar</span>' % field) dajax.remove_css_class('#label_%s' % field, 'label label-important') dajax.add_css_class('#label_%s' % field, 'label label-success') dajax.remove_css_class('#f_%s' % field, 'control-group error') dajax.add_css_class('#f_%s' % field, 'control-group success') dajax.remove('#label_%s' % field) dajax.append( '#f_%s' % field, 'innerHTML', '<span id="label_%s" class="label label-success">Correcto</span>' % field) # Change other fields with successful Color dajax.remove_css_class('#errors', 'alert alert-info') dajax.remove_css_class('#errors', 'alert alert-error') dajax.add_css_class('#errors', 'alert alert-success') # adding button unmodifiable dajax.remove('#buttonSend') dajax.append( '#my_form', 'innerHTML', '<a class="btn btn-primary disabled">Resgistrarme!</a>') dajax.add_css_class('#buttonSend', 'btn btn-primary disabled') dajax.assign( '#errors', 'innerHTML', '<b>Muchas Gracias te Registraste con exito!</b>') message_correct = """ <h5>Para tener en cuenta:</h5><span class="badge badge-inverse">1</span> Revisa tu correo electronico <span class="label label-info">%s</span> """ dajax.assign('#modalBody', 'innerHTML', message_correct % data['email']) # Modal with info subcriptor dajax.script("$('#myModal').modal('show')") # send email formf.send_mails('*****@*****.**') # return data return dajax.json() # If the user or user code already exists or use else: message_errors = """<h5><i class="icon-warning-sign"></i> Verificar los posibles <span class="label label-important">ERRORES</span> en tu Registro como Franquiciado:</h5><br /> <span class="badge badge-important">1</span> <b>La identificación o Documento ya existen en el sistema</b><br /> <span class="badge badge-important">2</span> <b>Cuenta de correo electrónico ya existen en el sistema</b><br /> <span class="badge badge-important">3</span> <b>Las contraseñas no concuerdan o son de menos de 6 digitos</b><br /> <span class="badge badge-important">4</span> <b>El Código de referencia ya esta en uso por otro Franquiciado</b><br /> <span class="badge badge-important">5</span> <b>El Código de referencia indicado No existe en el sistema</b> """ dajax.assign('#modalBody', 'innerHTML', message_errors) dajax.script("$('#myModal').modal('show')") else: dajax.remove_css_class('#errors', 'alert-info') dajax.add_css_class('#errors', 'alert alert-error') dajax.assign( '#errors', 'innerHTML', 'Los Campos en color <b>Rojo</b> deben ser ingresados o Corregidos:' ) for error in form.errors: dajax.remove_css_class('#f_%s' % error, 'control-group success') dajax.add_css_class('#f_%s' % error, 'control-group error') dajax.remove('#label_%s' % error) dajax.append( '#f_%s' % error, 'innerHTML', '<span id="label_%s" class="label label-important">Corregir este Campo</span>' % error) return dajax.json() else: return dajax.json()
def rerun_tasks(request, selected): dajax = Dajax() runs = Run.objects.filter(id__in=map(int, selected)).update(rerun=True) dajax.redirect('/results/') return dajax.json()
def adddata_test(request): dajax = Dajax() dajax.add_data(range(0, 10), 'my_callback') dajax.append('#console', 'innerHTML', "dajax.add_data(range(0,10),'my_callback')<br/>") return dajax.json()
def param_test(request, what): dajax = Dajax() dajax.alert("You search = %s" % what) dajax.append('#console', 'innerHTML', "dajax.alert(\'You search = %s\' % what)<br/>") return dajax.json()
def script_test(request): dajax = Dajax() dajax.script('alert("Alert from script!")') dajax.append('#console', 'innerHTML', "dajax.script('alert(\'Alert from script!\')')<br/>") return dajax.json()
def remove_test(request): dajax = Dajax() dajax.remove('#block10 .row') dajax.append('#console', 'innerHTML', "dajax.remove('#block10 .row')<br/>") return dajax.json()
def addUser(request, form): dajax = Dajax() form = deserialize_form(form) k_id = form['kitty_id'] user_form = KittyUserForm(form) if user_form.is_valid(): dajax.remove_css_class('.form-group', 'has-error') user = user_form.save(commit=False) user.kitty_id = k_id user.save() # create item <-> User Connection for item in Item.objects.filter(kitty_id=k_id): if not user.useritem_set.filter(item=item).exists(): UserItem.objects.create(item=item, quantity=0, user=user) dajax.script("$('#newUserModal').modal('hide');") dajax.script("location.reload();") brodcastNewUser(user) else: dajax.remove_css_class('.form-group', 'has-error') for error in user_form.errors: dajax.script( "$('#id_%s').parent().parent().addClass('has-error')" % error) return dajax.json()
def redirect_test(request): dajax = Dajax() dajax.redirect('http://djangoproject.com', 2000) dajax.append('#console', 'innerHTML', "dajax.redirect('http://djangoproject.com',2000)<br/>") return dajax.json()