def elimina_turno(request,turno_id): dajax=Dajax() t=Turno.objects.get(id=turno_id) html_elimina = render_to_string( 'elimina_turno.html', { 't': t, 'request':request } ) dajax.assign('div #elimina-turno-'+str(t.id), 'innerHTML', html_elimina) dajax.script("$('#elimina-turno-"+str(t.id)+"').modal('show');") return dajax.json()
def search_results_ajax(request, data): from data_collectors import search_results from views import is_logged user, openid_user, user_details = is_logged(request) if user.is_authenticated: game_type = data['game_type'] results = search_results(request, data) # if data.has_key('skip'): # skip = {'next_page':0, 'prev_page': 0, 'to_add': 0} # if return_int(data['skip']) is None: # data['skip'] = 0 # skip['next_page'] = return_int(data['skip']) + 20 # skip['prev_page'] = return_int(data['skip']) - 20 # if skip['prev_page'] < 0: # skip['prev_page'] = 0 # skip['to_add'] = (skip['next_page'] + skip['prev_page'])/2 # if skip['to_add'] == 10: # skip['to_add'] = 0 # else: # data['skip'] = 0 dajax = Dajax() render = render_to_string('hatsdb/ajax/search_results_ajax.html', { "results": results, 'game_type': game_type, 'user_details': user_details }, context_instance=RequestContext(request)) dajax.assign('#results', 'innerHTML', render) dajax.assign('#page', 'value', results['page']) dajax.script('stickyFooter()') return dajax.json()
def flickr_save(request, new_title): dajax = Dajax() # Use new_title... dajax.script('cancel_edit();') dajax.assign('#title', 'value', new_title) dajax.alert('Save complete using "%s"' % new_title) return dajax.json()
def listPagination(request, p, ready_to_use): items, pagelist, itemcount = get_list_page(ready_to_use, p) render = render_to_string('hardware/hardwarelisttable.html', {'hardware': items, 'pagelist':pagelist, 'itemcount':itemcount, 'ready_to_use':ready_to_use}) dajax = Dajax() dajax.assign('#pagination', 'innerHTML', render) return dajax.json()
def add_edit_mobapp_tab(request, form=''): dajax = Dajax() event = request.user.get_profile().is_coord_of mob_app_tab = get_mob_app_tab(event) template = loader.get_template('ajax/events/add_edit_mobapptab.html') if form: if mob_app_tab: f = MobAppWriteupForm(form, instance=mob_app_tab) else: f = MobAppWriteupForm(form) if f.is_valid(): unsaved = f.save(commit=False) unsaved.event = event unsaved.save() dajax.alert('saved successfully!') else: dajax.alert('Error. Your write up could not be saved!') else: if mob_app_tab: f = MobAppWriteupForm(instance=mob_app_tab) else: f = MobAppWriteupForm() t = template.render(RequestContext(request, locals())) dajax.assign('#detail', 'innerHTML', t) 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 flickr_save(request, new_title): dajax = Dajax() # Use new_title... dajax.script("cancel_edit();") dajax.assign("#title", "value", new_title) dajax.alert('Save complete using "%s"' % new_title) return dajax.json()
def test_newsite(request): requestProcessor = HttpRequestProcessor(request) dajax = Dajax() data = {} ajax = requestProcessor.getParameter('ajax') if (ajax != None): if (ajax == 'editmode'): formtype = requestProcessor.getParameter('formtype') name = requestProcessor.getParameter('name') value = requestProcessor.getParameter('value') div = requestProcessor.getParameter('div') help = requestProcessor.getParameter('help') data['formtype'] = formtype data['name'] = name data['help'] = help tp = get_template('website/blocks/form_field.html') c = Context(data) aa = tp.render(c) #aa = '<div class="input"><input type="text" id="id_'+name+'" name="'+name+'"></div>' #aa += '<label class="helptext">'+help+'</label>' dajax.assign('#'+div+'','innerHTML', aa) #dajax.script('alert("'+formtype+'")') return HttpResponse(dajax.json()) return render_to_response('website/test_newsite.html', data, context_instance=RequestContext(request))
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 modal_elimina_utente(request,utente_id): dajax=Dajax() u=User.objects.get(id=utente_id) html_elimina = render_to_string( 'elimina_utente.html', { 'utente': u, 'request':request } ) dajax.assign('div #elimina-utente-'+str(u.id), 'innerHTML', html_elimina) dajax.script("$('#elimina-utente-"+str(u.id)+"').modal('show');") return dajax.json()
def show_diff(request, sha=None, parent_sha=None, wiki=None, path=None): dajax = Dajax() if not sha or not wiki: return dajax.json() # Retrieve git repository try: w = Wiki.objects.get(slug=wiki) except Wiki.DoesNotExist: return dajax.json() if parent_sha and path: diff = w.repo.git.diff(parent_sha, sha, '--', path.encode('utf-8')).decode('utf-8') elif parent_sha and not path: diff = w.repo.git.diff(parent_sha, sha).decode('utf-8') elif not parent_sha and path: diff = w.repo.git.diff(sha, '--', path.encode('utf-8')).decode('utf-8') else: diff = w.repo.git.diff(sha).decode('utf-8') dajax.assign('#diff', 'innerHTML', highlight(diff, DiffLexer(), HtmlFormatter(cssclass='codehilite'))) return dajax.json()
def primopiano(request): dajax = Dajax() primo_piano = Product.objects.filter(primo_piano=True) out = '<table width="550px">' for i in primo_piano: out += '<th><td><h3 id="title-comm">%s</h3></td></th>' % (i.name) var = "'%s', document.getElementById('%s').value" % (i.name, i.name) try: sconto = Discount.objects.get(product=i).discount prezzo = i.price - (i.price * sconto / 100) #logging.error("prezzo scontato %s" % prezzo) valore_prezzo = "<em><s>EUR %s</s> EUR %s</em>" % (str( i.price), prezzo) #logging.error("FIN %s" % valore_prezzo) except: valore_prezzo = "<em>EUR %s</em>" % (str(i.price)) out += str(LISTRESULTS) % (i.image.url, i.image.url, i.name, i.name, i.description, valore_prezzo) out += creaselect(i.name, i.number, i.date_disponibility, var) out += '</td></tr>' out += '</table>' dajax.assign('#elenco', 'innerHTML', out) out = '<h2 id="title-comm">Primo Piano</h2>' dajax.assign('#titolo', 'innerHTML', out) return dajax.json()
def check_log(request, settings): dajax = Dajax() settings = LogViewerForm(settings) if not settings.data: settings = LogViewerForm({ 'limit': 10, 'filter': map(lambda (x, y): x, LOG_TYPE), 'refresh_timeout': 1 }) logs = Log.objects.filter( type__in=map(int, settings.data['filter'])).order_by( '-time')[:settings.data['limit'] or 10] if settings.data['host']: logs = filter(lambda x: settings.data['host'] in hex(x.hwaddr), logs) task = settings.data['task'] if task: logs = filter(lambda x: x.task and task in x.task.name or False, logs) test = settings.data['test'] if test: logs = filter(lambda x: x.test and test in x.test or False, logs) suite = settings.data['suite'] if suite: logs = filter(lambda x: x.suite and suite in x.suite or False, logs) logs = logs and '<br>'.join(map(unicode, logs)) or 'Log is empty' for _str in COLORIZE: logs = logs.replace(_str, COLORIZE[_str]) dajax.assign('#log', 'innerHTML', logs) return dajax.json()
def add_whitelist_country(request, country_id): dajax = Dajax() try: country = Country.objects.get(id=int(country_id)) country_id = country.id prefix_list = Prefix.objects.values_list( 'prefix', flat=True).filter(country_id=country_id) add_flag = False for prefix in prefix_list: rec_count = Whitelist.objects.filter( user=request.user, phonenumber_prefix=int(prefix), country_id=country_id).count() # No duplicate record found, so insert if rec_count == 0: Whitelist.objects.create( user=request.user, phonenumber_prefix=int(prefix), country_id=country_id, ) add_flag = True if add_flag: message = whitelist_success % (country.countryname) else: message = whitelist_info % (country.countryname) html_table = get_html_table(request, 'whitelist') dajax.assign('#id_whitelist_table', 'innerHTML', str(html_table)) except: message = whitelist_error % (str(prefix)) dajax.assign('#id_alert_message', 'innerHTML', str(message)) return dajax.json()
def add_whitelist_prefix(request, prefix): dajax = Dajax() try: prfix_obj = Prefix.objects.get(prefix=int(prefix)) country_id = prfix_obj.country_id.id rec_count = Whitelist.objects.filter(user=request.user, phonenumber_prefix=int(prefix), country_id=country_id).count() add_flag = False # No duplicate record, so insert if rec_count == 0: Whitelist.objects.create( user=request.user, phonenumber_prefix=int(prefix), country_id=country_id, ) add_flag = True if add_flag: message = whitelist_success % (str(prefix)) else: message = whitelist_info % (str(prefix)) html_table = get_html_table(request, 'whitelist') dajax.assign('#id_whitelist_table', 'innerHTML', str(html_table)) except: message = whitelist_error % (str(prefix)) dajax.assign('#id_alert_message', 'innerHTML', str(message)) return dajax.json()
def showTokens(request, platform, impID): """ Show the tokens """ if not isAuthenticated(request): return None dajax = Dajax() cleanPlatform = strip_tags(platform) if cleanPlatform == "google": eID = "#gStat" tab = "#googleTokenTable" elif cleanPlatform == "dropbox": eID = "#dStat" tab = "#dropTokenTable" try: data = dict() data['tknTable'] = AccessToken.objects.filter( serviceType=cleanPlatform) data['link'] = cleanPlatform data['id'] = parseAjaxParam(impID) table = render_to_string("dashboard/tokenTable.html", data) dajax.assign(tab, "innerHTML", table) except Exception as e: dajax.assign(eID, "innetHTML", e.message) return dajax.json()
def render_dajax_response(template, context): render = render_to_string(template, context) dajax = Dajax() dajax.assign('.filter-list-container', 'innerHTML', render) dajax.script('ListFilter.init();') return dajax.json()
def approve_corrected_time(request, record, button_id): dajax = Dajax() record_data = UserMissedHours.objects.get(id=record) #send request subject = "[TT] corrected hours" message = "Your hours were corrected! \n\r Your request at [ %s ] with message: \n %s" % ( record_data.date, record_data.umess) #get user db data user = User.objects.get(id=record_data.user) datatuple = ((subject, message, utils.TT_EMAIL_SYSTEM, [user.email]), ) utils.mail(datatuple) record_data.status = 1 record_data.save() dajax.script("$('#" + button_id + "').hide()") dajax.assign( '#msg_area_editor', 'innerHTML', 'User is informed! Time correction is done. <a href="/user_requests/">BACK</a>' ) return dajax.json()
def list_toggle(request, character, listname, elementid, toggle=True): """ Toggle whether or not a user is in one's personal lists. """ result = "" dajax = Dajax() permitted_lists = { 'watching': ('Watch this character.', 'Unwatch this character.'), 'hiding_from': ('Stop hiding from this character.', 'Hide from this character.'), 'ignoring': ('Stop ignoring this character.', 'Ignore this character.') } try: player, character, my_character = get_settings(request, character) mapping = {} mapping[True], mapping[False] = permitted_lists[listname] except IndexError: result = "Could not find player internally." except KeyError: result = "Not a valid list name." if not result: status = my_character.check_list(character, listname) if toggle: my_character.toggle_list(character, not status, listname) result = mapping[not status] else: result = mapping[status] dajax.assign(elementid, 'innerHTML', result) return dajax.json()
def aggiorna_statistiche(request, da, al): dajax = Dajax() if (da == "0"): dati = statistiche_intervallo(request, datetime.date(2000, 1, 1), datetime.datetime.now().date()) html_statistiche = render_to_string( 'statistiche.html', { 'dati': dati, 'elenco_statistiche': elenco_statistiche, 'request': request }) dajax.assign('div #stat', 'innerHTML', html_statistiche) elif (da != "" and al != ""): data_da = datetime.datetime.strptime(da, "%d/%m/%Y").date() data_al = datetime.datetime.strptime(al, "%d/%m/%Y").date() dati = statistiche_intervallo(request, data_da, data_al) html_statistiche = render_to_string( 'statistiche.html', { 'dati': dati, 'elenco_statistiche': elenco_statistiche, 'request': request }) dajax.assign('div #stat', 'innerHTML', html_statistiche) dajax.script("$('#loading').addClass('hidden');") #dajax.alert() return dajax.json()
def update_services_as_per_device_type(request, dvt_id): """ update service according to the device type selected :param request: :param device_type_id: """ dajax = Dajax() out = list() services = list() # process if type_id is not empty if dvt_id and dvt_id != "": try: dt = DeviceType.objects.get(id=dvt_id) for svc in dt.service.all(): services.append(svc) # some devices have same services, so here we are making list of distinct services distinct_service = set(services) out = ["<option value=''>Select</option>"] for svc in distinct_service: out.append("<option value='%d'>%s</option>" % (svc.id, svc.alias)) except Exception as e: logger.info(e) else: out = ["<option value=''>Select</option>"] dajax.assign('#id_service', 'innerHTML', ''.join(out)) return dajax.json()
def gt_critical_choices(request, option): """ update 'gt_critical' field choices :param request: :param option: """ dajax = Dajax() icon_settings = IconSettings.objects.all() out = list() out.append("<option value="">Select</option>") for icon_setting in icon_settings: img_url = "/media/"+ str(icon_setting.upload_image) \ if "uploaded" in str(icon_setting.upload_image) \ else static('img/{}'.format(icon_setting.upload_image)) # img_url = static('img/{}'.format(icon_setting.upload_image)) if icon_setting.id == int(option): out.append("<option value="+str(icon_setting.id)+" " "style='background-image:url(\""+img_url+"\"); " "background-size: 24px 24px;' selected>"+str(icon_setting.alias)+" </option>") else: out.append("<option value="+str(icon_setting.id)+" " "style='background-image:url(\""+img_url+"\"); " "background-size: 24px 24px;'>"+str(icon_setting.alias)+"</option>") dajax.assign("#id_gt_critical", 'innerHTML', ''.join(out)) return dajax.json()
def aggiorna_statistiche(request, da, al, mansioni, gruppi): dajax = Dajax() elenco_mansioni = Mansione.objects.filter(id__in=mansioni.rsplit('_')) senza_gruppo = False #import pdb; pdb.set_trace() if "all_" in gruppi: senza_gruppo = True gruppi = gruppi.replace("all_", "") if "all" in gruppi: senza_gruppo = True gruppi = gruppi.replace("all", "") if gruppi != "": elenco_gruppi = Gruppo.objects.filter(id__in=gruppi.rsplit('_')) else: elenco_gruppi = Gruppo.objects.all() data_da = datetime.date(datetime.datetime.today().year, 1, 1) data_al = datetime.datetime.now().date() if (da == "0"): elenco_mansioni = Mansione.objects.all() elenco_gruppi = Gruppo.objects.all() elif (da != "" and al != ""): data_da = datetime.datetime.strptime(da, "%d/%m/%Y").date() data_al = datetime.datetime.strptime(al, "%d/%m/%Y").date() tot_turni, tot_punti = statistiche_intervallo(request, data_da, data_al, elenco_mansioni, elenco_gruppi, senza_gruppo) html_statistiche = render_to_string('statistiche/statistiche.html', { 'tot_turni': tot_turni, 'tot_punti': tot_punti, 'request': request }) dajax.assign('div #stat', 'innerHTML', html_statistiche) dajax.script("$('#loading').addClass('hidden');") 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 scorri_calendario(request,direction): dajax=Dajax() if direction == '+1': remove_day = request.session['start'] start = request.session['start'] + datetime.timedelta(days=7) stop = start + datetime.timedelta(days=1) request.session['start'] = request.session['start'] + datetime.timedelta(days=1) elif direction == '-1': remove_day = request.session['start'] + datetime.timedelta(days=6) start = request.session['start'] - datetime.timedelta(days=1) stop = request.session['start'] request.session['start'] = request.session['start'] - datetime.timedelta(days=1) c = Calendario.objects.get(id=request.session['calId']) t = Turno.objects.filter(inizio__range=(start, stop),calendario=c).order_by('inizio', 'tipo__priorita') html_giorno = render_to_string( 'giorno.html', { 'turno': t, 'giorno': start, 'request':request } ) dajax.remove('div #giorno-'+remove_day.strftime("%d_%m_%Y")) if direction == '+1': dajax.script("$('.row-fluid.calendario').append('<div id=\"giorno-"+start.strftime("%d_%m_%Y")+"\" class=\"giorno span1\" ></div>');") elif direction == '-1': dajax.script("$('.row-fluid.calendario').prepend('<div id=\"giorno-"+start.strftime("%d_%m_%Y")+"\" class=\"giorno span1\" ></div>');") dajax.assign('div #giorno-'+start.strftime("%d_%m_%Y"), 'innerHTML', html_giorno) dajax.script("$('#loading').addClass('hidden');") dajax.script("window.allinea_calendario();") return dajax.json()
def searchPagination(request, p, searchquery, searchstate, searchcategory, searchcondition, searchsort): items, pagelist, itemcount = get_search_page(p, searchquery, searchstate, searchcategory, searchcondition, searchsort) render = render_to_string('hardware/hardwarelisttable.html', {'hardware': items, 'pagelist':pagelist, 'searchquery':searchquery, 'itemcount':itemcount, 'search':True}) dajax = Dajax() dajax.assign('#pagination', 'innerHTML', render) return dajax.json()
def disp(request, turno_id, mansione_id, persona_id, disp): dajax = Dajax() p=Persona.objects.get(id=persona_id) t=Turno.objects.get(id=turno_id) if disp!="-": d=nuova_disponibilita(request, turno_id, mansione_id, persona_id, disp) if not d[0]: dajax.script('$(".bottom-right").notify({ message: { text: "Errore'+str(d[1])+'" }}).show();') d=Disponibilita.objects.get(persona=p,turno=t) elif request.user.is_staff: d=Disponibilita.objects.get(persona=p,turno=t) if request.user.is_superuser or request.user==d.creata_da: d.delete() d={} temp = Template('<div class="input-prepend input-append small span4"><span class="add-on"><i class="icon-comment"></i></span><input id="note-disp-{{d.id}}" type="text" value="{{d.note}}"><button class="btn" type="button" onclick="nota_disponibilita({{d.id}});">salva</button></div>' +'{% if get_sovrascrivi_punteggio %}<div class="input-prepend input-append small span3"><span class="add-on"><i class="icon-trophy"></i></span><input id="punteggio-disp-{{d.id}}" type="number" {% if d.punteggio != -1 %} value="{{d.punteggio}}" {% else %} placeholder="{{t.valore}}" {% endif %}> <button class="btn" type="button" onclick="punteggio_disponibilita({{d.id}});">salva</button> </div>{% endif %}' +'</br>{{d.creata_da}}:{{d.ultima_modifica|date:"d M"}} {{d.ultima_modifica|time:"H:i"}}') c = Context({"d": d, "t":t, "get_sovrascrivi_punteggio": getattr(settings, 'GET_SOVRASCRIVI_PUNTEGGIO', False)}) dajax.assign('#disponibilita-'+str(p.id), 'innerHTML', temp.render(c)) t=Turno.objects.get(id=turno_id) html_anteprima = render_to_string( 'turno.html', { 't': t, 'request':request } ) dajax.assign('div #anteprima', 'innerHTML', html_anteprima+'<div style="clear:both;"></div>') dajax.script('$(".bottom-right").notify({ message: { text: "Aggiornata disponibilita per '+str(p)+'" }}).show();') dajax.script('$(".h6-mansione-'+mansione_id+'").addClass("mansione-sel");') dajax.script("$('#loading').addClass('hidden');") return dajax.json()
def add_edit_event(request,form="",id=0): """ This function calls the AddEventForm from forms.py If a new event is being created, a blank form is displayed and the core can fill in necessary details. If an existing event's details is being edited, the same form is displayed populated with current event details for all fields """ dajax = Dajax() if form == "" : if id: template = loader.get_template('ajax/core/editevent.html') event_form = AddEventForm(instance=Event.objects.get(id=id)) html=template.render(RequestContext(request,locals())) else: template = loader.get_template('ajax/core/addevent.html') event_form = AddEventForm() html=template.render(RequestContext(request,locals())) dajax.assign('#space', 'innerHTML', html) return dajax.json() if id: event_form = AddEventForm(form, instance=Event.objects.get(id=id)) else: event_form = AddEventForm(form) if event_form.is_valid(): event_form.save() dajax.assign("#space",'innerHTML',"") dajax.script("updateSummary();") 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 addCourseByProfToSession(request, form): dajax = Dajax() sessionList = [] c = Course.objects.filter(subject=form['courseSubjectByProf'], number=form['courseNumberByProf'])[0].title d = Instructor.objects.filter(userid=form['subjectProfs']) firstName = d[0].first_name lastName = d[0].last_name courseTuple = (form['courseSubjectByProf'], form['subjectProfs'], form['courseNumberByProf'], c, firstName, lastName) if 'byProf' in request.session: if courseTuple in request.session['byProf']: dajax.assign('#warningDiv', 'innerHTML', 'You have already selected %s %s - %s, taught by: %s %s!' % (courseTuple[0], courseTuple[2], courseTuple[3], courseTuple[4], courseTuple[5])) return dajax.json() sessionList = request.session['byProf'] sessionList.append(courseTuple) else: sessionList.append(courseTuple) request.session['byProf'] = sessionList out = [] for i in request.session['byProf']: out.append("<li>%s %s - %s, taught by: %s %s <a onclick=\"deleteCourseByProfFromSession('%s', '%s', '%s', '%s', '%s', '%s')\">(remove)</a></li>" % (i[0], i[2], i[3], i[4], i[5], i[0], i[1], i[2], i[3], i[4], i[5])) dajax.assign('#addCourseByProfList', 'innerHTML', ''.join(out)) dajax.clear('#warningDiv', 'innerHTML') 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 add_edit_mobapp_tab(request, form = ''): dajax = Dajax() event = request.user.get_profile().is_coord_of mob_app_tab = get_mob_app_tab(event) template = loader.get_template('ajax/events/add_edit_mobapptab.html') if form: if mob_app_tab: f = MobAppWriteupForm(form, instance = mob_app_tab) else: f = MobAppWriteupForm(form) if f.is_valid(): unsaved = f.save(commit = False) unsaved.event = event unsaved.save() dajax.alert('saved successfully!') else: dajax.alert('Error. Your write up could not be saved!') else: if mob_app_tab: f = MobAppWriteupForm(instance = mob_app_tab) else: f = MobAppWriteupForm() t = template.render(RequestContext(request,locals())) dajax.assign('#detail', 'innerHTML', t) return dajax.json()
def item_report(request, begin, end, direction): dajax = Dajax() start_date = string_to_date(begin) end_date = string_to_date(end) end_date = datetime.combine(end_date, time(23, 59, 59, 999999)) stock_changes = StockChange.objects.filter( date_changed__range=(start_date, end_date), direction=direction ) totals = {} for stock_change in stock_changes: if stock_change.item.id in totals: totals[stock_change.item.id]['amount'] += stock_change.quantity else: totals[stock_change.item.id] = {} totals[stock_change.item.id]['amount'] = stock_change.quantity totals[stock_change.item.id]['unit_cost'] = stock_change.item.price totals[stock_change.item.id]['units'] = stock_change.item.units totals[stock_change.item.id]['name'] = stock_change.item.name if totals: out = ["<table id='report-table' class='table table-condensed tablesorter'><thead><tr><th>Item</th><th>Amount</th><th>Total Cost</th></tr></thead><tbody>"] for item in totals.itervalues(): out.append("<tr><td>%s</td><td>%s %s</td><td>$%s</td></tr>" % ( item['name'], item['amount'], item['units'], item['amount'] * item['unit_cost'] )) out.append("</tbody></table>") else: out = ["No results for this date range"] dajax.assign('#report-results', 'innerHTML', ''.join(out)) if totals: dajax.script('report.attach_tablesorter();') return dajax.json()
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()
def load_start(request): r = render_to_string('start.html') dajax = Dajax() dajax.assign('#content', 'innerHTML', r) dajax.script('init_start();') return dajax.json()
def add_blacklist_country(request, country_id): dajax = Dajax() try: country = Country.objects.get(id=int(country_id)) country_id = country.id prefix_list = Prefix.objects.values_list('prefix', flat=True).filter(country_id=country_id) add_flag = False for prefix in prefix_list: rec_count = Blacklist.objects.filter(user=request.user, phonenumber_prefix=int(prefix), country_id=country_id).count() # No duplicate record found, so insert if rec_count == 0: Blacklist.objects.create( user=request.user, phonenumber_prefix=int(prefix), country_id=country_id, ) add_flag = True if add_flag: message = blacklist_success % (country.countryname) else: message = blacklist_info % (country.countryname) html_table = get_html_table(request, 'blacklist') dajax.assign('#id_blacklist_table', 'innerHTML', str(html_table)) except: message = blacklist_error % (country.countryname) dajax.assign('#id_alert_message', 'innerHTML', str(message)) return dajax.json()
def send_form(request, form): print 'in send form' dajax = Dajax() form = Search_Form(deserialize_form(form)) print 'errors' print form.errors # must do this to clean the form if form.is_valid(): print 'form is valid' cars = make_query(form) items = land_page_pagination(page=1, items=cars) render = render_to_string('./parts/pagination_page2.html', {'items': items}) dajax = Dajax() dajax.assign('#respo', 'innerHTML', render) # print(dir(dajax.json())) return dajax.json() else: dajax.alert('error in form validation') return dajax.json()
def after_update_data_sources_as_per_service(request, svc_id="", selected=""): """ update data sources as per service :param request: :param svc_id: :param selected: """ dajax = Dajax() out = list() if svc_id and svc_id != "": try: # getting data sources associated with the selected service data_sources = Service.objects.get(id=svc_id).service_data_sources.all() out = ["<option value=''>Select</option>"] for data_source in data_sources: if data_source.id == int(selected): out.append("<option value='%d' selected>%s</option>" % (data_source.id, data_source.alias)) else: out.append("<option value='%d'>%s</option>" % (data_source.id, data_source.alias)) except Exception as e: logger.info(e) else: out = ["<option value=''>Select</option>"] dajax.assign('#id_data_source', 'innerHTML', ''.join(out)) return dajax.json()
def deleteUnavailableFromSession(request, day, startMinute, startHour, endMinute, endHour): dajax = Dajax() listOfDays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] t1 = time(int(startHour), int(startMinute)) t2 = time(int(endHour), int(endMinute)) sesList = request.session['timesUnavailable'] sesList.remove((int(day), t1, t2, listOfDays[int(day)])) request.session['timesUnavailable'] = sesList out = [] for i in request.session['timesUnavailable']: if int(i[1].minute) < 10: firstMinute = str(i[1].minute) + '0' else: firstMinute = str(i[1].minute) if int(i[2].minute) < 10: lastMinute = str(i[2].minute) + '0' else: lastMinute = str(i[2].minute) out.append("<li>%s from %s:%s %s to %s:%s %s <a onclick=\"Dajaxice.scheduler.deleteUnavailableFromSession(Dajax.process, { 'day':'%s', 'startMinute':'%s', 'startHour':'%s', 'endMinute':'%s', 'endHour':'%s' })\">(remove)</a></li>" % (i[3], changeFrom24To12(i[1].hour), firstMinute, hourIsAMorPM(i[1].hour), changeFrom24To12(i[2].hour), lastMinute, hourIsAMorPM(i[2].hour), i[0], i[1].minute, i[1].hour, i[2].minute, i[2].hour)) if not request.session['timesUnavailable']: out.append("<span>There are no times specified.</span>") dajax.assign('#addTimeList', 'innerHTML', ''.join(out)) dajax.clear('#warningDiv', 'innerHTML') return dajax.json()
def createFaction(request, name, motto, description): dajax = Dajax() try: faction = Faction.objects.get(name=name) dajax.assign('#name-warnings','innerHTML','<div class="alert alert-danger">A faction with that name already exists! Please try another.</div>') return dajax.json() except: pass if len(name) == 0: dajax.assign('#name-warnings','innerHTML','<div class="alert alert-danger">Your faction must have a name!</div>') return dajax.json() faction = Faction( name=name, motto=motto, description=description ) faction.save() founder = utils.getPlayer(request.user) try: old_faction = founder.faction if len(Player.objects.filter(faction=old_faction)) == 1: old_faction.delete() except Exception, e: pass
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 utente_persona(request,user_id,persona_id): dajax = Dajax() s='' if Persona.objects.filter(user=user_id): a=User.objects.get(id=user_id) per=Persona.objects.get(user=user_id) per.user=None per.save() if persona_id=='n': s=s+'noty({"text":"l\' utente <b>'+str(a)+'</b> non e piu assegnato a <b>nessuna persona</b>","layout":"bottomRight","type":"success","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":500,"timeout":5000,"closeButton":true,"closeOnSelfClick":true,"closeOnSelfOver":false});' pass if persona_id!='n' and User.objects.filter(pers_user=persona_id): a=User.objects.get(pers_user=persona_id) dajax.assign('select#'+str(a.id),'selectedIndex','0') s=s+'noty({"text":"<b>Attenzione</b>:La persona era precedentemente assegnato all\'utente <b>'+str(a)+'</b>","layout":"bottomRight","type":"alert","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":500,"timeout":5000,"closeButton":true,"closeOnSelfClick":true,"closeOnSelfOver":false});' if persona_id!='n': per=Persona.objects.get(id=persona_id) u=User.objects.get(id=user_id) per.user=u s=s+'noty({"text":"La persona <b>'+str(per)+'</b> e stato assegnata all\'utente <b>'+str(u)+'</b>","layout":"bottomRight","type":"success","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":500,"timeout":5000,"closeButton":true,"closeOnSelfClick":true,"closeOnSelfOver":false});' dajax.script(s) per.save() return dajax.json()
def requisito_form(request, form, form_id): dajax = Dajax() #pdb.set_trace() f = deserialize_form(form) if Requisito.objects.filter(mansione=f['mansione'],tipo_turno=f['tipo_turno']).exists(): r = Requisito.objects.get(mansione=f['mansione'],tipo_turno=f['tipo_turno']) form = RequisitoForm(f,instance=r) else: form = RequisitoForm(f) dajax.remove_css_class(str(form_id)+ ' #id_operatore', 'ui-state-error') dajax.remove_css_class(str(form_id)+ ' #id_valore', 'ui-state-error') if form.data.get('operatore')=='NULL' and Requisito.objects.filter(mansione=f['mansione'],tipo_turno=f['tipo_turno']).exists(): r=Requisito.objects.get(mansione=form.data.get('mansione'),tipo_turno=form.data.get('tipo_turno')) turni=Turno.objects.filter(tipo=form.data.get('tipo_turno')) for t in turni: for d in Disponibilita.objects.filter(turno=t, mansione=form.data.get('mansione')): d.mansione=None d.save() r.delete() dajax.script('$("#applica-'+str(form.data.get('mansione'))+'-'+str(form.data.get('tipo_turno'))+'").hide();') dajax.assign(str(form_id)+ ' input', 'value','') elif form.is_valid(): form.save() dajax.script('$("#applica-'+str(form.data.get('mansione'))+'-'+str(form.data.get('tipo_turno'))+'").hide();') dajax.script('noty({"text":"Modifiche apportate con successo","layout":"bottomRight","type":"success","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":500,"timeout":5000,"closeButton":true,"closeOnSelfClick":true,"closeOnSelfOver":false});') else: for error in form.errors: dajax.add_css_class('%(form)s #id_%(error)s' % {"form": form_id, "error": error}, 'ui-state-error') return dajax.json()
def 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 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 showTokens(request, platform, impID): """ Show the tokens """ if not isAuthenticated(request): return None dajax = Dajax() cleanPlatform = strip_tags(platform) if cleanPlatform == "google": eID = "#gStat" tab = "#googleTokenTable" elif cleanPlatform == "dropbox": eID = "#dStat" tab = "#dropTokenTable" try: data = dict() data['tknTable'] = AccessToken.objects.filter(serviceType=cleanPlatform) data['link'] = cleanPlatform data['id'] = parseAjaxParam(impID) table = render_to_string("dashboard/tokenTable.html",data) dajax.assign(tab, "innerHTML", table) except Exception as e: dajax.assign(eID, "innetHTML", e.message) return dajax.json()
def addCourseToSession(request, form): dajax = Dajax() sessionList = [] c = Course.objects.filter(subject=form['courseSubject'], number=form['courseNumber'])[0].title courseTuple = (form['courseSubject'], form['courseNumber'], c) if 'byCourse' in request.session: if courseTuple in request.session['byCourse']: dajax.assign('#warningDiv', 'innerHTML', 'You have already selected %s %s - %s!' % courseTuple) return dajax.json() sessionList = request.session['byCourse'] sessionList.append(courseTuple) else: sessionList.append(courseTuple) request.session['byCourse'] = sessionList out = [] for i in request.session['byCourse']: out.append("<li>%s %s - %s <a onclick=\"deleteCourseFromSession('%s', '%s', '%s')\">(remove)</a></li>" % (i[0], i[1], i[2], i[0], i[1], i[2])) dajax.assign('#addCourseList', 'innerHTML', ''.join(out)) dajax.clear('#warningDiv', 'innerHTML') return dajax.json()
def text_send_form(request, form): print 'in text send form' query_string = '' found_entries = None dajax = Dajax() form = Text_Search_Form(deserialize_form(form)) print 'errors' print form.errors # must do this to clean the form if form.is_valid(): print 'form is valid' text = form.cleaned_data['target_text'] query_string = text entry_query = get_query(query_string, ['title', 'category',]) print entry_query found_entries = Offer.objects.filter(entry_query) items = land_page_pagination(page=1, items=found_entries) render = render_to_string('./parts/pagination_page2.html', {'items': items}) dajax = Dajax() dajax.assign('#respo', 'innerHTML', render) return dajax.json() else: dajax.alert('error in form validation') return dajax.json()
def test_edit(request): requestProcessor = HttpRequestProcessor(request) jurisdiction_id = 130732 dajax = Dajax() data = {} data['jurisdiction_id'] = jurisdiction_id answer_reference_class_obj = AnswerReference() ajax = requestProcessor.getParameter('ajax') if (ajax != None): if (ajax == 'jurisdiction_website_submit'): data['website'] = requestProcessor.getParameter('website') jurisdiction_website_div = requestProcessor.getParameter('jurisdiction_website_div') form_id = 'form_website' question_text = 'website' jurisdiction_id = requestProcessor.getParameter('jurisdiction_id') process_answer(data, question_text, jurisdiction_id, request.user) question_text = "website" body = get_website_html(form_id, question_text, jurisdiction_id, request, 'edit') dajax.assign('#'+str(jurisdiction_website_div),'innerHTML', body) return HttpResponse(dajax.json()) if (ajax == 'jurisdiction_email_submit'): data['email'] = requestProcessor.getParameter('email') jurisdiction_website_div = requestProcessor.getParameter('jurisdiction_email_div') form_id = 'form_email' question_text = 'website' jurisdiction_id = requestProcessor.getParameter('jurisdiction_id') process_answer(data, question_text, jurisdiction_id, request.user) question_text = "website" body = get_email_html(form_id, question_text, jurisdiction_id, request, 'edit') dajax.assign('#'+str(jurisdiction_website_div),'innerHTML', body) return HttpResponse(dajax.json()) return HttpResponse(dajax.json()) ############### website - start ##################### data['jurisdiction_website_div'] = 'jurisdiction_website_div' data['form_website'] = 'form_website' question_text = "website" body = get_website_html(data['form_website'], question_text, jurisdiction_id, request, 'edit') data['body_website'] = body return requestProcessor.render_to_response(request,'website/test/test_edit.html', data, '')
def load_menu(request, slug=None, path=None): dajax = Dajax() if not slug or not path: return dajax.json() # Retrieve wiki object try: wiki = Wiki.objects.get(slug=slug) except Wikit.DoesNotExist: return dajax.json() # Get repository tree tree = wiki.repo.get_tree() node = tree['node'] # Create template tmpl = get_template('wiki/menuitem.html') itemid = [0] # Generate the menu from the templates def buildtree(node): ret = u'' for element in node['children']: # Now parse the file element['node']['path'] = os.path.splitext(element['node']['path'])[0] element['node']['name'] = os.path.splitext(element['node']['name'])[0] if element['node']['type'] == 'tree': itemid[0] += 1 data = { 'is_folder_item': True, 'checked': element['node']['path'] in path, 'wiki': wiki, 'node': element['node'], 'itemid': itemid[0], 'submenu_html': buildtree(element['node']) } ret = u'{0}\n{1}'.format(ret, tmpl.render(Context(data))) else: data = { 'is_folder_item': False, 'checked': False, 'wiki': wiki, 'node': element['node'] } ret = u'{0}\n{1}'.format(ret, tmpl.render(Context(data))) return ret # Assign generated HTML to element dajax.assign('#wiki-menu', 'innerHTML', buildtree(node)) return dajax.json()
def pagination(request, text, p): # track_list = get_pagination_page(p) track_list = get_search_results(text, p) render = render_to_string('trackList.html', {'track_list': track_list}) dajax = Dajax() dajax.assign('#pagination', 'innerHTML', render) return dajax.json()
def occorrenze(request,occ_id,turno_id): dajax=Dajax() html='' for t in Turno.objects.filter(occorrenza_id=occ_id): html+='<li>'+str(t.inizio)+'</li>' dajax.assign("div#occorrenze-"+str(turno_id), "innerHTML", html) dajax.script('$("div#occorrenze-'+str(turno_id)+'").slideDown();') return dajax.json()
def revision_form(request): dajax = Dajax() form = RevisionForm() context = {'form': form} context.update(csrf(request)) data = render_to_string('website/templates/submit-revision.html', context) dajax.assign('#submit-revision-wrapper', 'innerHTML', data) return dajax.json()
def checkmessages(request): if not request.user.is_authenticated(): return dajax = Dajax() unread = Message.objects.filter(user=request.user, read=False).count() dajax.assign("#messcount", "innerHTML", unread) return dajax.json()
def confirm_delete_tab(request, tab_id): # asks coord 'are u sure u want to delete this tab?' tab = Tab.objects.get(id=tab_id) template = loader.get_template('ajax/events/tab_delete.html') t = template.render(RequestContext(request, locals())) dajax = Dajax() dajax.assign('#detail', 'innerHTML', t) return dajax.json()
def get_users_to_lend(request, query): dajax = Dajax() userlist = User.objects.filter(username__icontains=query) endlist = [] for user in userlist: endlist.append(user.username) dajax.assign('#id_username', 'data-source', endlist) return dajax.json()