Exemple #1
0
def filter(request, username, station=0, type="all", time=0):
    dajax = Dajax()

    query = [Q(user__username=username)]

    if time != 0:
        query.append(
            Q(created__gt=datetime.datetime.now() -
              datetime.timedelta(days=time)))

    if type != "all":
        query.append(Q(content_type__name=type))

    accomplishments_all = Accomplishment.objects.filter(
        *query).order_by("-created")

    if station == 0:
        accomplishments = accomplishments_all
    else:
        accomplishments = []

        for accomplishment in accomplishments_all:
            if accomplishment.station is not None and accomplishment.station.id == station:
                accomplishments.append(accomplishment)

    data = serialize_accomplishments(accomplishments)
    dajax.add_data(data, "filter_callback")
    return dajax.json()
Exemple #2
0
def guardar_declaracion_transporte(request, formulario, transportePorDia, fechaPeriodoInicio, fechaPeriodoFin):# Método que recibe el formulario de endoso obtenido de endoso.html y lo deserializa para obtener la información de sus controles y lo valida con EndosoForm, si la información es valida guarda los datos y limpia los controles del formulario mediante una función de js.
    dajax = Dajax()
        
    if transportePorDia == '':
        list_transporte = ''
    else:        
        array_convertido_string = simplejson.dumps(transportePorDia, separators=('|',','))
        list_transporte = array_convertido_string.replace('[', '').replace(']', '').replace('"', '').split(';')
                      
    formulario_deserializado = deserialize_form(formulario)
    
    if formulario_deserializado.get('varIdDeclaracionTransporte') == '':
                 
        fechaDeclaracionTransporte = datetime.datetime.now()
        declaracionTransporteGuardar = DeclaracionTransporte(Fecha = fechaDeclaracionTransporte, PeriodoInicio = datetime.datetime.strptime(fechaPeriodoInicio,'%d/%m/%Y').strftime('%Y-%m-%d'),
                                PeriodoFin = datetime.datetime.strptime(fechaPeriodoFin,'%d/%m/%Y').strftime('%Y-%m-%d'), 
                                DescripcionBienAsegurado = formulario_deserializado.get('txtDescripcionBienAsegurado').upper(), Observaciones = formulario_deserializado.get('txtObservaciones').upper(),
                                Constancia_id = formulario_deserializado.get('varIdConstancia'), CierreMes = 0, DeclaracionNueva = 0, IdStatusDeclaracion = 1)
        
        declaracionTransporteGuardar.save()   
        
        Constancia.objects.filter(IdConstancia=formulario_deserializado.get('varIdConstancia')).update(UtilizadoDeclaracion=1)
        
        if str(formulario_deserializado.get('varIdDeclaracionTransporteAnterior')) != "":            
            DeclaracionTransporte.objects.filter(IdDeclaracionTransporte=formulario_deserializado.get('varIdDeclaracionTransporteAnterior')).update(DeclaracionNueva=1)        
                    
        if list_transporte != '':
            guardar_declaracion_transporte_por_dia(list_transporte, declaracionTransporteGuardar.IdDeclaracionTransporte)     
                
        dajax.add_data(declaracionTransporteGuardar.IdDeclaracionTransporte, 'mensajeDeclaracionTransporte')
    
    else:
        actualizar_declaracion_transporte(formulario_deserializado, list_transporte, fechaPeriodoInicio, fechaPeriodoFin) 
         
    return dajax.json()
Exemple #3
0
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()
Exemple #4
0
def guardar_endoso_ad(request,contenidos,datosEndoso):
    dajax = Dajax()
    #Guardar el endoso en la tabla ControlEndoso
    guardarControlEndoso = ControlEndoso(Constancia_id = datosEndoso["idConstancia"],FechaEndoso = datetime.datetime.now(),TipoEndoso = datosEndoso["TipoEndoso"],
                                         SumaAseguradaAnterior = datosEndoso["SumaAseguradaAnterior"],SumaAseguradaEndoso = datosEndoso["SumaAseguradaEndoso"],
                                         SumaAseguradaActual = datosEndoso["SumaAseguradaActual"],SolicitudEndoso_id= datosEndoso["idSolicitudEndoso"])
     
    guardarControlEndoso.save()
    #Se crea el Folio dependiendo del tipo
    folioEndoso = "E" + datosEndoso["TipoEndoso"][0] + "-" + str(guardarControlEndoso.IdControlEndoso)
    ControlEndoso.objects.filter(IdControlEndoso = guardarControlEndoso.IdControlEndoso).update(FolioEndoso = folioEndoso)
    informacionMensaje = [folioEndoso, guardarControlEndoso.IdControlEndoso]
    dajax.add_data(informacionMensaje, 'mensajeSolicitud')
    #Se pone ocupada la constancia para el endoso
    Constancia.objects.filter(IdConstancia = datosEndoso["idConstancia"]).update(Utilizado=True)
    array_convertido_string = simplejson.dumps(contenidos, separators=('|',','))
    list_Contenidos = array_convertido_string.replace('[', '').replace(']', '').replace('"', '').split(';')
    
    if list_Contenidos != '':
        #antes de guardar los nuevos bienes se berifica que los anteriores dejen de estar utilizados
        DescripcionBienEndosoAD.objects.filter(Constancia_id = datosEndoso["idConstancia"]).update(Utilizado=False)
        for contenidos in list_Contenidos:
            guardar_bienes_endoso_ad(contenidos, datosEndoso["idConstancia"],datosEndoso["idSolicitudEndoso"])
                
    return dajax.json()
Exemple #5
0
def fetch_multi_delete_tag(request, selected_mails, tag_id, url):
    dajax = Dajax()
    search_object = search.get_search_from_url(url)
    try:
        tag = Tag.objects.get(id=tag_id)
    except (Tag.DoesNotExist, Tag.MultipleObjectsReturned):
        tag = None
    else:
        for mail_id in selected_mails:
            try:
                mail = Mail.objects.get(id=mail_id)
            except (Mail.DoesNotExist, Mail.MultipleObjectsReturned):
                pass
            else:
                mail.tags.remove(tag)
    result = tags.mail_tags_multibar_html(search_object, selected_mails, True)
    dajax.add_data(
        {
            'tags_html': result,
            'tags_only': True,
            'tags_changed': True,
            'propagate': True
        }, 'update_multibar')
    update_tag_cloud(dajax, search_object)
    return dajax.json()
Exemple #6
0
def filter(request,username,station=0,type="all",time=0):
    dajax = Dajax()
    
    query = [Q(user__username=username)]

    if time != 0:
        query.append(Q(created__gt = datetime.datetime.now() - datetime.timedelta(days = time)))

    if type != "all":
        query.append(Q(content_type__name=type))

    accomplishments_all = Accomplishment.objects.filter(*query).order_by("-created")
        
    if station == 0:
        accomplishments = accomplishments_all
    else:
        accomplishments = []
        
        for accomplishment in accomplishments_all:
            if accomplishment.station is not None and accomplishment.station.id == station:
                accomplishments.append(accomplishment)    
        
    data = serialize_accomplishments(accomplishments)
    dajax.add_data(data, "filter_callback")
    return dajax.json()
Exemple #7
0
def clear_accomplishments(request,badge,username,data):
    dajax = Dajax()
    
    if request.user.is_authenticated():
        badge = Badge.objects.get(pk=badge)
        
        user = User.objects.get(username = username)
    
        for id in data:
            acc = Accomplishment.objects.get(pk=id)
            badge.accomplishments.remove(acc)
            reviews = Review.objects.filter(reviewer=request.user,accomplishment=acc)
            for review in reviews:
                review.delete()
    
        win = Win.objects.get(badge=badge,user=user)
        win.complete=False
        win.save()

        accomplishments = badge.accomplishments.filter(user__username = username).order_by("-created")
        
        a_data = serialize_accomplishments(accomplishments)
        
        dajax.add_data({'badge':badge.id,'a_data':a_data}, "badge_accomplishments_callback")

    return dajax.json()
Exemple #8
0
def upload_file(request, filename, file_data):
    dajax = Dajax()
    query = {
        "method" : "upload",
        "key": request.user.sessionkey,
        "params" : {
            "data" : {
                "filename": filename, 
                "filetype": "filetype"
                }
            }
        }

    content_dict = api_request(query)

    if content_dict.has_key('result'):
        upload_id = content_dict['result']['upload_id']
        upload_url = '/bioupload/' + upload_id
        dajax.add_data({'upload_url': upload_url, 'upload_id': upload_id}, 'upload_2_server')
    else:
        template_context = {'error_message': 'Query does not exist.'}
        render = render_to_string('components/alert_messages.html', template_context)
        dajax.assign('.extra-message-block', 'innerHTML', render)

    return dajax.json()
Exemple #9
0
def search_venues(request, form_data):
    dajax = Dajax()

    geosearch_form = VenueGeoSearchForm(form_data)

    if geosearch_form.is_valid():
        distance = geosearch_form.cleaned_data.get('distance')
        circle_x = geosearch_form.cleaned_data.get('circle_x')
        circle_y = geosearch_form.cleaned_data.get('circle_y')

        center_point = Point(circle_x, circle_y)
        venue_filter = search_venue_atomic(form_data, center_point, distance, form_data.get('ambiance') or [])
        
        render = render_to_string(template_name='venue/search_results.html',
                                  dictionary={'venue_filter': venue_filter},
                                  context_instance=RequestContext(request)
                                  )

    else:
        render = render_to_string(template_name='venue/search_results.html',
                                  dictionary={'venue_filter': []},
                                  context_instance=RequestContext(request)
                                  )
        

    # Add markers to put on map
    venue_markers = []
    for venue in venue_filter:
        venue_markers.append({'lat': venue.place.geom.y, 'lon': venue.place.geom.x, 'text': "<a href='#%s'>%s</a>" % (venue.slug, venue.name)})
    dajax.add_data(venue_markers, 'addMarkers')

    dajax.assign('#search-results-wrapper', 'innerHTML', render)

    return dajax.json()
Exemple #10
0
def guardar_constancia(request,frmConstancia,Coberturas,beneficiarioPorcentaje): #Recibe el formulario constancia, el porcentaje de los beneficiarios y las tarifas y cuotas de las coberturas
    dajax = Dajax()
    formulario_deserializado = deserialize_form(frmConstancia)
    fechaEmision = datetime.datetime.now()
    horaActual = datetime.datetime.strptime(fechaEmision.strftime('%H:%M:%S'),'%H:%M:%S').strftime('%H:%M:%S')
    folioConstancia = "C" + "-" + formulario_deserializado.get('varFolioSolicitud')

    arrayCoberturas_convertido_string = simplejson.dumps(Coberturas, separators=('|',','))
    list_Coberturas = arrayCoberturas_convertido_string.replace('[', '').replace(']', '').replace('"', '').split(';')

    arrayBeneficiariosPorcentaje_convertido_string = simplejson.dumps(beneficiarioPorcentaje, separators=('|',','))
    list_BeneficiariosPorcentaje = arrayBeneficiariosPorcentaje_convertido_string.replace('[', '').replace(']', '').replace('"', '').split(';')   
    
    constanciaGuardar = Constancia(Solicitud_id = formulario_deserializado.get('varIdSolicitud'), 
                                   VigenciaInicio = datetime.datetime.strptime(formulario_deserializado.get('VigenciaInicio')+' '+horaActual,'%d/%m/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S'),
                                   VigenciaFin = datetime.datetime.strptime(formulario_deserializado.get('VigenciaFinal')+' '+horaActual, '%d/%m/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S'),
                                   FechaEmision = fechaEmision, FolioConstancia = folioConstancia, SumaAsegurada = formulario_deserializado.get('SumaAseguradaTotal'),
                                   CuotaNeta = formulario_deserializado.get('CuotaNeta'),Utilizado=0)
    constanciaGuardar.save()
    
    for cobertura in list_Coberturas:
        guardar_cobertura_constancia(cobertura,constanciaGuardar.IdConstancia)

    for porcentajeBeneficiario in list_BeneficiariosPorcentaje:
        actualizar_porcentaje_beneficiario(porcentajeBeneficiario)
    
    datosConstancia = [folioConstancia,constanciaGuardar.IdConstancia]
    dajax.add_data(datosConstancia, 'mensajeConstancia')
    return dajax.json()
Exemple #11
0
def updatecombo(request,option):
    dajax = Dajax()
    out = ["<option value='0'>Select Resource...</option>"]
    if option != '0':
        re=Resource.objects.filter(type=option).values('name','id')
        res=re.filter(availability='true')
        dajax.remove_css_class('#combo2s', 'hide')
        for r in res:
            out.append("<option value='%s'>%s</option>" % (r['id'],r['name']))
    else:
        dajax.add_css_class('#combo2s', 'hide')
    dajax.assign('#combo2', 'innerHTML',''.join(out))
    
    dajax.clear('#status', 'innerHTML')
    dajax.add_css_class('#options', 'hide')
    dajax.add_css_class('.alert-error', 'hide')
    dajax.clear('#errorList .showMessage','innerHTML')
    dajax.add_css_class('#mul_date','hide')
    dajax.add_css_class('#sel_date','hide')
    dajax.add_css_class('#infos', 'hide')
    dajax.add_css_class('#st_time', 'hide')
    dajax.add_css_class('#en_time', 'hide')
    dajax.add_data('','$("input[name=optionsRadios]:checked").val')
    dajax.add_data('checked','$("input[name=optionsRadios]:checked").removeAttr')
    return dajax.json()
Exemple #12
0
def saved_checked(request,change):
	dajax = Dajax()
	usr = get_user(request)
	addrs = Address.objects.filter(owner=usr)
	options = UsersMarkerOptions.objects.get(user=usr)

	if int(change)==1:
		op = options.showSaved
		options.showShared = not options.showSaved
		options.save()
	else:
		op  = not options.showSaved

	if op==False:
		print "showing"	
		for i in addrs:
			mtitle = str(i.addr)
			marker_id = "saved_entry_"+str(i.id)
			points = {'lat':i.lat,'lng':i.lng,'mtitle':mtitle, 'marker_id' : marker_id } 
			dajax.add_data(points,'add_marker')

	else:
		print "hiding"
		for i in addrs:
			marker_id = "saved_entry_"+str(i.id)
			print marker_id
			points = {'marker_id' : marker_id } 
			dajax.add_data(points, 'remove_marker')


	if int(change)==1:
		options.showSaved = not options.showSaved
		options.save()
	return dajax.json()
Exemple #13
0
def update_players(request, option):
	"""Returns the players for both teams involved"""
	dajax = Dajax()
	if(option == '#'):
		dajax.add_data([], 'doNothing')
		return dajax.json()
	idx_v = option.find(" v ")	
	team1 = option[0:idx_v]
	team2 = option[idx_v+3:]

	out1 = EventsPz.objects.filter(fixture=option).exclude(player1name='NULL').values_list('player1name', flat=True).distinct()
	out2 = EventsPz.objects.filter(fixture=option).exclude(player2name='NULL').values_list('player2name', flat=True).distinct()

	out = list(out1) + list(out2)
	out = set(out)
	out_list = []
	out_list.append("<option value='#'>Select a Player</option>")
	for i in out:
		out_list.append("<option value='%s'>%s</option>" % (i,i))

	dajax.assign('#id_head_player', 'innerHTML', ''.join(out_list))
	dajax.assign('#id_tohead_player', 'innerHTML', ''.join(out_list))

	half1, half2 = find_half_time(EventsPz.objects.filter(fixture=option))
	total = int(half1+half2)/60 + 1
	#dajax.assign('#half_time_value', 'innerHTML', int(half1)/60)
	#dajax.assign('#full_time_value', 'innerHTML', total)
	dajax.script("$('#slider_range').slider( 'option' , { min: 0, max: %d } );" % total)
	dajax.script("$('#slider_range').slider( 'option',  'values', [0, %d]); " % total)
	dajax.script('$("#loader").hide()')
	dajax.script("$( '#time_range' ).val('0 mins - 90 + %d mins')" %(total-int(half1)/60-45));
	times = {'time1': int(half1)/60, 'time2': total-int(half1)/60}
	dajax.add_data(times, 'updateTimes')
	return dajax.json()
Exemple #14
0
def guardar_endoso(request, formulario, endoso):# Método que recibe el formulario de endoso obtenido de endosodeclaracion.html y lo deserializa para obtener la información de sus controles y lo valida con EndosoForm, si la información es valida guarda los datos y limpia los controles del formulario mediante una función de js.
    dajax = Dajax()
    
    if endoso == '':
        list_endoso = ''
    else:        
        array_convertido_string = simplejson.dumps(endoso, separators=('|',','))
        list_endoso = array_convertido_string.replace('[', '').replace(']', '').replace('"', '').split(';')
                      
    formulario_deserializado = deserialize_form(formulario)
    
    if list_endoso != '':
        
        endoso = list_endoso[0].split(',')
        endosoAGuardar = Endoso(BienesAsegurados = Decimal(endoso[0]), SumaAsegurada = Decimal(endoso[1]),
                                PorcentajeFondo = Decimal(endoso[2]), ImporteFondo = Decimal(endoso[3]),
                                PorcentajeReaseguro = Decimal(endoso[4]), ImporteReaseguro = Decimal(endoso[5]),
                                PorcentajeTotal = Decimal(endoso[6]), ImporteTotal = Decimal(endoso[7]), 
                                DeclaracionEndoso_id = formulario_deserializado.get('varIdDeclaracionEndoso'))
    
        endosoAGuardar.save()
        
        dajax.add_data(endosoAGuardar.IdEndoso, 'mensajeEndoso')
         
    return dajax.json()
Exemple #15
0
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
Exemple #16
0
def clear_accomplishments(request, badge, username, data):
    dajax = Dajax()

    if request.user.is_authenticated():
        badge = Badge.objects.get(pk=badge)

        user = User.objects.get(username=username)

        for id in data:
            acc = Accomplishment.objects.get(pk=id)
            badge.accomplishments.remove(acc)
            reviews = Review.objects.filter(reviewer=request.user,
                                            accomplishment=acc)
            for review in reviews:
                review.delete()

        win = Win.objects.get(badge=badge, user=user)
        win.complete = False
        win.save()

        accomplishments = badge.accomplishments.filter(
            user__username=username).order_by("-created")

        a_data = serialize_accomplishments(accomplishments)

        dajax.add_data({
            'badge': badge.id,
            'a_data': a_data
        }, "badge_accomplishments_callback")

    return dajax.json()
Exemple #17
0
def employee(request, carnet):
    dajax = Dajax()
    empleado = Empleados.objects.get(ci=carnet)
    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()
def college_register(request, form=""):
    if form == "" :
        template = loader.get_template('ajax/users/college_register.html')
        coll_form=AddCollegeForm()
        html=template.render(RequestContext(request,locals()))
        dajax = Dajax()
        dajax.assign('#reg', 'innerHTML', html)
        return dajax.json()
    dajax = Dajax()
    coll_form = AddCollegeForm(form)
    if coll_form.is_valid():
        college=coll_form.cleaned_data['name']
        if college.find('&')>=0:
            college = college.replace('&','and')
        city=coll_form.cleaned_data['city']
        state=coll_form.cleaned_data['state']
        
        if len(College.objects.filter(name=college, city=city, state=state))== 0 :
            college=College (name = college, city = city, state = state)
            college.save()
            data = college.name+","+college.city
            flag=1            
        else:
            flag=2
    else:
        flag=0
    dajax.add_data(flag, 'reg_done')
    return dajax.json()
Exemple #19
0
def deal(request, content,type):
    dajax = Dajax()
    jp = JsonProducer("http://10.21.31.91:7474/db/data/")
    graph = jp.parse(content,type)
    s = json.dumps(graph,ensure_ascii=False)
    dajax.add_data(s,'graphready')
    return dajax.json()
Exemple #20
0
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()
Exemple #21
0
def getobjects(request, userid, slug, sha):
    userid = int(userid)
    slug = escape(slug)
    obj = func.getRepoObjorNone(userid, slug)
    sha = escape(sha)
    if not obj:
        return

    dajax = Dajax()
    trees = func.getAllObjects(obj.get('repoObj'), "tree", sha)
    blobs = func.getAllObjects(obj.get('repoObj'), "blob", sha)
    icon = "<i class='icon-folder-close'></i>"
    tablerow = [
        "<tr><td id='%s' class='tree'>%s %s</td></tr>" %
        (obj["sha"], icon, obj["name"]) for obj in trees
    ]
    dajax.append("#filesbody", "innerHTML", ''.join(tablerow))
    icon = "<i class='icon-file'></i>"
    tablerow = [
        "<tr><td id='%s' class='blob'>%s %s</td></tr>" %
        (obj["sha"], icon, obj["name"]) for obj in blobs
    ]
    dajax.append("#filesbody", "innerHTML", ''.join(tablerow))
    dajax.add_data("", "setEvents")
    return dajax.json()
Exemple #22
0
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
Exemple #23
0
def get_new_messages_num(request, item_id):
    dajax = Dajax()
    wallitems = WallItem.objects.filter(pk=item_id)
    if not len(wallitems) == 0:#表示活动在
        wallitem = wallitems[0]
        now =datetime.datetime.now()
        flag_status = wallitem.flag_status
        if now < wallitem.begin_time:
            logger.info('活动还没有开始')
        elif now > wallitem.end_time:
            if flag_status == '进行中':
                wallitem.flag_status = '已结束' 
                finish_all_msgs(item_id)
                dajax.script("wall_item_tip()")
            else:
                logger.info('活动已结束')
        else:
            wallmsgs = WallMsg.objects.filter(flag_pass=0, flag_show=0, wall_item_id=item_id)
            new_messages_num = len(wallmsgs)
            if not new_messages_num == 0:
                dajax.assign('#newMsgNum','innerHTML',new_messages_num)
                dajax.add_data({'num':new_messages_num, 'event_name':wallitem.event_name} ,'changeTitle')
                dajax.remove_css_class('#new-message-num', 'noNews')
    else:
        dajax.script('itemDeleted()')
    return dajax.json()
Exemple #24
0
def save_location(request,addr,container):
	dajax = Dajax()
	usr = get_user(request)
	loc, (lat,lng) = get_coords(addr)	
	location = Address(owner =usr,
			lat = lat ,
			lng = lng,
			addr = addr)
	location.save()

	markers =UsersMarkerOptions.objects.get(user=usr)
	print markers.window
	if markers.window != 0:
		return dajax.json()


	location_entry = render_to_string('maps_app/saved_location_node.html',{'addr': location })

	options = UsersMarkerOptions.objects.get(user=usr)

	if options.showSaved==True:
		mtitle = str(location.addr)
		marker_id = "saved_entry_"+str(location.id)
		points = {'lat':location.lat,'lng':location.lng,'mtitle':mtitle, 'marker_id' : marker_id } 
		dajax.add_data(points,'add_marker')

			

	dajax.append('#'+str(container),'innerHTML',location_entry) 
	return dajax.json()
Exemple #25
0
def post_accomplishments(request, badge, username, data):
    dajax = Dajax()

    if request.user.is_authenticated():
        badge = Badge.objects.get(pk=badge)

        user = User.objects.get(username=username)

        for id in data:
            acc = Accomplishment.objects.get(pk=id)
            badge.accomplishments.add(acc)
            review = Review.objects.get_or_create(reviewer=request.user,
                                                  accomplishment=acc)[0]
            review.modified = datetime.datetime.now()
            review.save()

        win = Win.objects.get_or_create(badge=badge, user=user)[0]

        accomplishments = badge.accomplishments.filter(
            user__username=username).order_by("-created")

        a_data = serialize_accomplishments(accomplishments)

        dajax.add_data({
            'badge': badge.id,
            'a_data': a_data
        }, "badge_accomplishments_callback")

    return dajax.json()
Exemple #26
0
def search_heroes(request, search_request):
    if len(search_request) < 2:
        return None
    dajax = Dajax()
    result_set = Heroes.objects.filter(dota2_name__icontains=search_request)[:25]
    result_string = render_to_string('ajax/search_results_hero.html', dictionary=dict({'results': result_set}))    
    dajax.add_data(result_string, 'render_heroes')
    return dajax.json()
Exemple #27
0
def fetch_multibar(request, selected_mails, propagate, url):
    dajax = Dajax()
    search_object = search.get_search_from_url(url)
    result = tags.mail_tags_multibar_html(search_object, selected_mails)
    dajax.add_data(
        {"tags_html": result, "tags_only": False, "tags_changed": False, "propagate": propagate}, "update_multibar"
    )
    return dajax.json()
Exemple #28
0
def search_players(request, search_request):
    if len(search_request) < 2:
        return None
    dajax = Dajax()
    result_set = SteamPlayer.filter_by_name(name=search_request, profileurl=search_request, communityid=search_request)
    result_string = render_to_string('ajax/search_results_players.html', dictionary=dict({'results': result_set}))
    dajax.add_data(result_string, 'render_players')
    return dajax.json()
Exemple #29
0
def connect_friends(request):
	print "Connecting friends"
	dajax = Dajax()
	s = request.session
	user = s['fbuser']
	edges = user.get_friends_links()
	dajax.add_data(edges, 'grapher.add_edges')
	return dajax.json()
Exemple #30
0
def locate(request, country, city):
    """
    Locates a city input by the user.
    """
    dajax = Dajax()
    g = GeoNames(None, "veitheller")
    place, (lat, lon) = g.geocode(str(city) + ", " + str(country))
    dajax.add_data([lat, lon], 'addLocationMarker')
    return dajax.json()
Exemple #31
0
def fetch_mail_body(request, email_id, url):
    dajax = Dajax()
    search_object = search.get_search_from_url(url)
    email_body = "Error retrieving email"
    email = Mail.objects.get(pk=email_id)
    if email:
        email_body = get_expanded_html(email, search_object)
    dajax.add_data({"email_id": email_id, "email_body": email_body}, "update_mail_body")
    return dajax.json()
def variant_css(request):
    dajax = Dajax()
    this_variant = 1
    # all_elements = serializers.serialize('json', Element.objects.filter(variant=this_variant))
    all_declarations = serializers.serialize('json', Declaration.objects.filter(element__variant__id=this_variant),
                                             fields=('element', 'property', 'value'), use_natural_keys=True)

    dajax.add_data(json.loads(all_declarations), 'print_ajax')
    return dajax.json()
Exemple #33
0
def ste_update_alerts(request, ste_id='', antenna_id=''):
    """
    allows keep update the requests status for STEs configuration.

    If ste_id and antenna_id is *None* the functions returns the current
    status of the all ste configuration.

    If antenna_id is different to *None* the antenna is updated.

    Arguments:
    - `ste_id`: is the id of STE that will be assigned to the Antenna
    (in the application the STE_id is its *name*)
    - `antenna_id`: the id of the Antenna that will be updated
    """

    dajax = Dajax()  # object that manage the AJAX connection

    # is retrieved the current block status of the application
    read_only = check_read_only(request)

    # first the antenna information is updated
    # if is passed a antenna_id and the application is not in read_only mode
    # the information of the Antenna is update
    if antenna_id != '' and not read_only:
        antenna = Antenna.objects.get(id=antenna_id)
        # if the ste_id is passed and if the ste is not the same that
        # the current a new STE is assigned to the antenna
        if ste_id != '' and ste_id != antenna.current_ste:
            antenna.requested_ste = ste_id
        else:
            antenna.requested_ste = None

        # The requester and request_date is updated
        antenna.requester = request.user
        antenna.request_date = datetime.now()
        antenna.save()  # the Antenna is saved

    # is loaded all current status of the ste configuration
    antennas = Antenna.objects.all()
    for antenna in antennas:
        if not antenna.active:
            continue

        # the status of the antenna is obtained in HTML format
        status = antenna.html_status()

        # the data is passed to the template function update_status
        dajax.add_data({'antenna': antenna.id,
                        'requested_ste': antenna.requested_ste,
                        'current_ste': antenna.current_ste,
                        'is_requested': antenna.is_requested(),
                        'error': antenna.exist_errors(),
                        'read_only': read_only,
                        'status': status},
                       'update_status')

    return dajax.json()
Exemple #34
0
def locate(request, country, city):
    """
    Locates a city input by the user.
    """
    dajax = Dajax()
    g = GeoNames(None, "veitheller")
    place, (lat, lon) = g.geocode(str(city) + ", " + str(country))
    dajax.add_data([lat, lon], 'addLocationMarker')
    return dajax.json()
Exemple #35
0
def run_code(request, code, quiz=None):
    if quiz:
        test_code = Quiz.objects.get(id=quiz).test_code
    else:
        test_code = ''
    result = run(code, test_code)
    dajax = Dajax()
    dajax.add_data(result, 'show_result')
    return dajax.json()
Exemple #36
0
def search_heroes(request, search_request):
    if len(search_request) < 2:
        return None
    dajax = Dajax()
    result_set = Heroes.objects.filter(
        dota2_name__icontains=search_request)[:25]
    result_string = render_to_string('ajax/search_results_hero.html',
                                     dictionary=dict({'results': result_set}))
    dajax.add_data(result_string, 'render_heroes')
    return dajax.json()
Exemple #37
0
def get_comments(request, post_pk):
    dajax = Dajax()
    
    comments = models.CommentModel.objects.filter(post=post_pk)
    if not comments:
        dajax.add_data('No comments associated with this post.', 'commentStatus')
    else:
        comment_json = serializers.serialize('json', comments)
        dajax.add_data(comment_json, 'render_comments')
    return dajax.json()
Exemple #38
0
def display_area_detail(request, area_id):
    area, locations = get_area_and_locations(area_id)

    dajax = Dajax()
    if locations is not None:
        data = serializers.serialize("json", locations)
        dajax.add_data(data, 'area_detail_add_locations')
        dajax.add_data(None, 'zoom_to_show_all_markers')

    return dajax.json()
Exemple #39
0
def search_players(request, search_request):
    if len(search_request) < 2:
        return None
    dajax = Dajax()
    result_set = SteamPlayer.filter_by_name(name=search_request,
                                            profileurl=search_request,
                                            communityid=search_request)
    result_string = render_to_string('ajax/search_results_players.html',
                                     dictionary=dict({'results': result_set}))
    dajax.add_data(result_string, 'render_players')
    return dajax.json()
Exemple #40
0
def fetch_tag_completion(request, text):
    dajax = Dajax()
    tags = None
    if len(text) == 1:
        tags = Tag.objects.filter(name__istartswith=text)
    else:
        tags = Tag.objects.filter(name__icontains=text)
    response = []
    for tag in tags:
        response.append(tag.name)
    dajax.add_data({'tags': response}, 'update_tag_completion')
    return dajax.json()
Exemple #41
0
def fetch_contact_completion(request, text):
    dajax = Dajax()
    contacts = None
    if len(text) == 1:
        contacts = Contact.objects.filter(name__istartswith=text)
    else:
        contacts = Contact.objects.filter(name__icontains=text)
    response = []
    for contact in contacts:
        response.append(contact.name)
    dajax.add_data({'contacts': response}, 'update_contact_completion')
    return dajax.json()
Exemple #42
0
def fetch_mail_body(request, email_id, url):
    dajax = Dajax()
    search_object = search.get_search_from_url(url)
    email_body = 'Error retrieving email'
    email = Mail.objects.get(pk=email_id)
    if (email):
        email_body = get_expanded_html(email, search_object)
    dajax.add_data({
        'email_id': email_id,
        'email_body': email_body
    }, 'update_mail_body')
    return dajax.json()
Exemple #43
0
def fetch_multibar(request, selected_mails, propagate, url):
    dajax = Dajax()
    search_object = search.get_search_from_url(url)
    result = tags.mail_tags_multibar_html(search_object, selected_mails)
    dajax.add_data(
        {
            'tags_html': result,
            'tags_only': False,
            'tags_changed': False,
            'propagate': propagate
        }, 'update_multibar')
    return dajax.json()
Exemple #44
0
def tags(request, target, object_id, edit=False, formdata=None):
    if formdata is None:
        formdata = {}
    dajax = Dajax()

    response_format = 'html'
    obj = Object.objects.get(pk=object_id)

    tags = obj.tags.all()
    form = None
    if 'tags' in formdata and not type(formdata['tags']) == list:
        formdata['tags'] = [formdata['tags']]

    if edit or formdata:
        if formdata.get('tags_object', 0) == unicode(obj.id):
            form = TagsForm(tags, formdata)
            if form.is_valid():
                if 'multicomplete_tags' in formdata:
                    tag_names = formdata.get('multicomplete_tags').split(',')
                    new_tags = []
                    for name in tag_names:
                        name = name.strip()
                        if name:
                            try:
                                tag = Tag.objects.get(name=name)
                            except Tag.DoesNotExist:
                                tag = Tag(name=name)
                                tag.save()
                            new_tags.append(tag)
                else:
                    new_tags = form.is_valid()

                obj.tags.clear()
                for tag in new_tags:
                    obj.tags.add(tag)
                tags = obj.tags.all()
                form = None
        else:
            form = TagsForm(tags)

    context = {'object': obj, 'tags': tags, 'form': form}

    context = converter.preprocess_context(context)

    output = render_to_string('core/ajax/tags_box',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)

    dajax.add_data({'target': target, 'content': output}, 'anaf.add_data')
    return dajax.json()
Exemple #45
0
def render_schedule( request, width, height, schedule_id ):

    if not 'instances' in request.session:
        request.session['instances'] = []

    if not 'schedules' in request.session:
        request.session['schedules'] = []


    dajax = Dajax()
    dajax.clear( '.entries', 'innerHTML' )

    dayCode = { 
    "M":"monday",
    "T":"tuesday",
    "W":"wednesday",
    "TH":"thursday",
    "F":"friday",
    "S":"saturday",
    "ARR":"null",
    }

    scheduleBlock = "<div class=\"class_block_wrapper\"><div class=\"class_block\" style=\"height: %s; top: %s; width: %s;\">%s</div></div>"
    
    if( len(request.session['schedules']) <= 0):
        return dajax.json()

    if( schedule_id >= len(request.session['schedules']) ):
        schedule_id = 0;

    if( schedule_id <= 0 ):
        schedule_id = len(request.session['schedules'])-1

    for instance in request.session['schedules'][schedule_id]:
        course = Course.objects.filter(id=CourseInstance.objects.filter(id=instance)[0].course_id)[0]
        sections = Section.objects.filter(course_instance_id=instance)
        for section in sections:
            block = SectionTime.objects.filter(section_id=section)[0]
            day = block.day
            startTime = block.start_time.zfill(4)
            endTime = block.end_time.zfill(4)
            start = float(startTime[0:2]) + ( float(startTime[2:4]) / 60.0 )
            end = float(endTime[0:2]) + ( float(endTime[2:4]) / 60.0 )
            length = end-start
            dajax.append( '.'+dayCode[day]+' .entries', 'innerHTML', scheduleBlock % ( str(length*height)+"px", str( (start-8)*height) + "px", str(width)+"px",course.subject_no ) )

            
    dajax.add_data( "", "SetScheduleEvents" )
    request.session.modified = True    
    return dajax.json()
            
Exemple #46
0
def geolocate(request):
    """
    Geolocates the user by IP.
    """
    dajax = Dajax()
    g = pygeoip.GeoIP(preferences.BASE_DIR + '/static/rc/GeoLiteCity.dat')
    ip = request.META.get('REMOTE_ADDR', None)
    if ip:
        if ip == '127.0.0.1':
            ip = '141.45.146.48'
        data = g.record_by_addr(ip)
        dajax.add_data(
            [round(data['latitude'], 2),
             round(data['longitude'], 2)], 'addLocationMarker')
    return dajax.json()
Exemple #47
0
def show_graph(request,body_model_id):
	dajax = Dajax()
	body=Body.objects.get(examination=int(body_model_id))
	body_model=body.compartment_set.all()
	nodes = [i.name for i in body_model]
	edges=[]
	for node in body_model:
		edges.extend([[i.from_compartment.name, i.to_compartment.name,{'label':i.weight}] 
									for i in Edge.objects.filter(from_compartment=node)])

	graphJSON = {"nodes":nodes, "edges":edges}
	print graphJSON
	dajax.add_data(graphJSON,'graph.loadJSON')
	
	return dajax.json()
Exemple #48
0
def load_editor(request, pk=None):
    r = render_to_string('editor.html')

    dajax = Dajax()
    dajax.assign('#content', 'innerHTML', r)

    if pk is not None:
        a = Animation.objects.get(pk=pk)
        a.email = ''
        a.author = ''
        dajax.add_data(serializers.serialize('json', [a]), 'init_editor')
    else:
        dajax.script('init_editor();')

    return dajax.json()
Exemple #49
0
def form_add_specialization(request, form_data):
    dajax = Dajax()
    callback = 'form_add_specialization_callback'
    form = AddSpecializationForm(form_data, request=request)
    if form.is_valid():
        clear_validation(dajax, form)
        data = form.cleaned_data
        specialization = data['specialization']
        user = request.user
        user.add_specialization(specialization)
        dajax.add_data({'status': 'OK'}, callback)
    else:
        show_validation(dajax, form)
        dajax.add_data({'status': 'INVALID'}, callback)
    return dajax.json()
Exemple #50
0
def form_add_skill(request, form_data):
    dajax = Dajax()
    callback = 'form_add_skill_callback'
    form = AddSkillForm(form_data, request=request)
    if form.is_valid():
        clear_validation(dajax, form)
        data = form.cleaned_data
        skill = data['skill']
        user = request.user
        user.add_skill(skill)
        dajax.add_data({'status': 'OK'}, callback)
    else:
        show_validation(dajax, form)
        dajax.add_data({'status': 'INVALID'}, callback)
    return dajax.json()
Exemple #51
0
def fetch_mail_tags(request, email_id, url):
    dajax = Dajax()
    search_object = search.get_search_from_url(url)
    try:
        mail = Mail.objects.get(id=email_id)
    except (Mail.DoesNotExist, Mail.MultipleObjectsReturned):
        pass
    else:
        tags_html = tags.mail_tags_to_html_list(mail, search_object)
        dajax.add_data(
            {
                'email_id': email_id,
                'tags_html': tags_html,
                'propagate': False
            }, 'update_tags')
    return dajax.json()
Exemple #52
0
def fetch_add_tag(request, email_id, tag, url):
    dajax = Dajax()
    search_object = search.get_search_from_url(url)
    mails = Mail.objects.filter(id=email_id)
    if len(mails) > 0:
        t = tags.get_or_create_tag(tag)
        mails[0].tags.add(t)
    tags_html = tags.mail_tags_to_html_list(mails[0], search_object)
    dajax.add_data(
        {
            'email_id': email_id,
            'tags_html': tags_html,
            'propagate': True
        }, 'update_tags')
    update_tag_cloud(dajax, search_object)
    return dajax.json()
Exemple #53
0
def fetch_delete_mail(request, email_id):
    dajax = Dajax()
    logger = logging.getLogger('ajax')
    success = False
    try:
        mail = Mail.objects.get(id=email_id)
        logger.info('delete_email ' + datetime.datetime.utcnow().isoformat() +
                    ' id: ' + str(mail.id) + ' subject: ' + mail.subject)
    except:
        pass
    else:
        if settings.MAILSHARE_ENABLE_DELETE:
            mail.delete()
            success = True

    dajax.add_data({'success': success}, 'update_delete_mail')
    return dajax.json()
Exemple #54
0
def get_more(request, target='#more-news', skip=20):
    dajax = Dajax()

    profile = request.user.profile
    query = _get_filter_query(profile) & (
        ~Q(author=profile) | Q(record_type='share') | Q(score__gt=0))
    updates = UpdateRecord.objects.filter(query).distinct()[skip:skip + 20]

    output = render_to_string('news/ajax/index', {
        'updates': updates,
        'skip': skip + 20
    },
                              context_instance=RequestContext(request),
                              response_format='html')

    dajax.add_data({'target': target, 'content': output}, 'anaf.add_data')
    return dajax.json()
Exemple #55
0
def easy_invite(request, emails=None):

    dajax = Dajax()

    try:
        emails_original = emails
        emails = emails.split(',')

        sender = request.user.profile
        default_group = sender.default_group
        domain = RequestSite(request).domain

        invited = []

        for email in emails:
            email = email.strip()
            if len(email) > 7 and re.match(
                    "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$",
                    email) is not None:
                invitation = Invitation(sender=request.user.profile,
                                        email=email,
                                        default_group=default_group)
                invitation.save()
                EmailInvitation(invitation=invitation,
                                sender=sender,
                                domain=domain).send_email()
                invited.append(email)

        if invited:
            template = 'core/tags/easy_invite_success'
        else:
            template = 'core/tags/easy_invite_failure'
    except:
        template = 'core/tags/easy_invite_failure'

    invite_markup = render_to_string(template, {},
                                     context_instance=RequestContext(request),
                                     response_format='html')

    dajax.add_data(
        {
            'target': "div.easy-invite[emails='{0!s}']".format(
                (emails_original)),
            'content': invite_markup
        }, 'anaf.add_data')
    return dajax.json()
Exemple #56
0
def index_news(request):
    dajax = Dajax()
    commitscomments = CommitComment.objects.filter(
        repository__private=False).order_by('-date')[:5]
    newrepos = Repository.objects.filter(
        private=False).order_by('-created')[:5]
    issues = Issue.objects.filter(
        repository__private=False).order_by('-published')[:5]
    issues_comments = IssueComment.objects.filter(
        issue__repository__private=False).order_by('-date')[:5]

    cc = [{
        'tab': '#tab1',
        'author_id': comment.author.id,
        'author_username': comment.author.username,
        'userid': comment.repository.user.id,
        'slug': comment.repository.slug,
        'sha': comment.sha,
        'repo_user': comment.repository.user.username,
        'date': func.getDate(comment.date)
    } for comment in commitscomments]
    dajax.add_data(cc, "commitcomment")
    iss = [{
        'tab': '#tab1',
        'label': issue.label,
        'author_id': issue.author.id,
        'author_username': issue.author.username,
        'userid': issue.repository.user.id,
        'slug': issue.repository.slug,
        'id': issue.id,
        'repo_user': issue.repository.user.username,
        'date': func.getDate(issue.published)
    } for issue in issues]
    dajax.add_data(iss, "issues")
    icom = [{
        'tab': '#tab1',
        'author_id': comment.author.id,
        'author_username': comment.author.username,
        'userid': comment.issue.repository.user.id,
        'slug': comment.issue.repository.slug,
        'id': comment.issue.id,
        'repo_user': comment.issue.repository.user.username,
        'date': func.getDate(comment.date)
    } for comment in issues_comments]
    dajax.add_data(icom, "issuescomments")
    newrep = [{
        'tab': '#tab1',
        'author_id': repo.user.id,
        'author_username': repo.user.username,
        'slug': repo.slug,
        'date': func.getDate(repo.created)
    } for repo in newrepos]
    dajax.add_data(newrep, "newrepos")

    return dajax.json()
Exemple #57
0
def change_model(request,compartment_form,body_model_id):
	dajax = Dajax()

	body=Body.objects.get(examination=int(body_model_id))
	form=CompartmentForm(deserialize_form(compartment_form))
	compartment=body.compartment_set.get(name=form['name'].value())
	form.instance=compartment
	if form.is_valid():
		
		form.save()
	else:
		for er_field,er_text in form.errors.items():
			dajax.script("""$('#id_%s').parent().parent().addClass('has-error');"""
				%er_field)
	JSONdata=make_circul_model(int(body_model_id),200,1,['concentration','transit_times'])
	#print JSONdata
	dajax.add_data(JSONdata,'draw_concentration_plot')
	return dajax.json()
Exemple #58
0
def form_whiteboard_post(request, form_data):
    dajax = Dajax()
    callback = 'form_whiteboard_post_callback'
    form = AddWhiteboardPostForm(form_data, request=request)
    if form.is_valid():
        clear_validation(dajax, form)
        data = form.cleaned_data
        content = data['content']
        section = data['section']
        post = WhiteboardPost()
        post.content = content
        post.author = request.user
        post.section = section
        post.save()
        dajax.add_data({'status': 'OK'}, callback)
    else:
        show_validation(dajax, form)
        dajax.add_data({'status': 'INVALID'}, callback)
    return dajax.json()