Exemplo n.º 1
0
def save_editted_tab(request, form, tab_id):
    # validates the tab details that were submitted while editing an existing tab
    tab = Tab.objects.get(id=tab_id)
    f = TabAddForm(form, instance=tab)
    if f.is_valid():
        event = request.user.get_profile().is_coord_of
        unsaved_tab = f.save(commit=False)
        unsaved_tab.event = event
        unsaved_tab.save()
        tab = unsaved_tab
        tabs = get_tabs(event)
        template = loader.get_template('ajax/events/tab_list.html')
        t1 = template.render(RequestContext(request, locals()))
        template2 = loader.get_template('ajax/events/tab_detail.html')
        t2 = template2.render(RequestContext(request, locals()))
        dajax = Dajax()
        dajax.assign('#tabs', 'innerHTML', t1)
        dajax.assign('#detail', 'innerHTML', t2)
        return dajax.json()
    else:
        template = loader.get_template('ajax/events/tab_edit_form.html')
        t = template.render(RequestContext(request, locals()))
        dajax = Dajax()
        dajax.assign('#detail', 'innerHTML', t)
        return dajax.json()
Exemplo n.º 2
0
    def process(self):
        """
        Process the dajax request calling the apropiate method.
        """
        if self.is_callable():
            # 1. get the function
            thefunction = self.get_ajax_function()

            # 2. call the function
            try:
                response = thefunction(self.request)
                if isinstance(response, Dajax):
                    return response.render()
                else:
                    return response
            except Exception, e:
                log.exception("dajax error, e=%s" % (e))  # added by hehao
                # Development Server Debug
                if settings.DEBUG and DajaxRequest.get_dajax_debug():
                    import traceback
                    from dajax.utils import print_green_start, print_blue_start, print_clear, print_red

                    print_green_start()
                    print "#" * 50
                    print "uri:      %s" % self.request.build_absolute_uri()
                    print "function: %s" % self.full_name
                    print "#" * 50
                    print ""
                    print_red(str(e))
                    print_blue_start()
                    traceback.print_exc(e)
                    print_clear()

                # If it's an ajax request we need soft debug
                # http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.is_ajax
                if self.request.is_ajax():
                    # If project was in debug mode, alert with Exception info
                    # if settings.DEBUG:#modified by hehao
                    if True:
                        response = Dajax()
                        # response.alert('Exception %s: Check %s manually for more information or your server log.' % (str(e), self.request.get_full_path()))
                        response.alert(u'亲,出错啦,请联系您的顾问!')
                        return response.render()
                    # If not, check DAJAX_ERROR_CALLBACK, if present call this function
                    # elif DajaxRequest.get_dajax_error_callback() != None:#modified by hehao
                    if DajaxRequest.get_dajax_error_callback() != None:
                        response = Dajax()
                        response.script(
                            DajaxRequest.get_dajax_error_callback() % str(e))
                        return response.render()
                    # Otherside ... raise Exception
                    else:
                        raise
                # If it's a non-ajax request raise Exception, Django cares.
                else:
                    raise
Exemplo n.º 3
0
def insert_comment(request, text, image):
    dajax = Dajax()
    if text == '':
        return dajax.json()
    else:
        dajax = Dajax()
        Comment.objects.create(text=text, image=Image.objects.get(pk=image))
        dajax.assign('#id_text', 'value', '')
        comments = Comment.objects.filter(image=image)
        render_comments = render_to_string('single_image/comments.html', {
            'comments': comments,
        })
        dajax.assign('#comments', 'innerHTML', render_comments)
        return dajax.json()
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
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()
Exemplo n.º 6
0
def load_start(request):
    r = render_to_string('start.html')

    dajax = Dajax()
    dajax.assign('#content', 'innerHTML', r)
    dajax.script('init_start();')
    return dajax.json()
Exemplo n.º 7
0
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()
Exemplo n.º 8
0
def multiply(request):
    a = int(request.POST['a'])
    b = int(request.POST['b'])
    c = a * b
    dajax = Dajax()
    dajax.assign('#result', 'value', str(c))
    return dajax.calls
Exemplo n.º 9
0
def filtercat(request, option):
    dajax = Dajax()
    #logging.error(option)
    try:
        filtercat = Tag.objects.get(name=option).product_set.all()
        if len(filtercat) == 0:
            out = '<p class="nores">Nessun risultato trovato</p>'
        else:
            out = '<table width="550px">'
            for i in filtercat:
                var = "'%s', document.getElementById('%s').value" % (i.name,
                                                                     i.name)
                out += '<th><td><h3 id="title-comm">%s</h3></td></th>' % (
                    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.description, valore_prezzo)
                out += creaselect(i.name, i.number, i.date_disponibility, var)
                out += '</td></tr>'
            out += '</table>'
    except Exception, e:
        logging.error(e)
        out = '<p class="nores">Nessun risultato trovato</p>'
Exemplo n.º 10
0
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()
Exemplo n.º 11
0
def curFind(request, id, big):
    dajax = Dajax()

    curriculum = Curriculum.objects.get(pk=id)

    htmlStr = ""
    for g in curriculum.grade_set.filter(hasResource=True).order_by('number'):
        tempStr = "<li class='dropText' onClick='selGrade(%d, this)'> %s </li>" % (
            g.id, g.title)
        htmlStr += tempStr

    #dajax.assign('#curSelection','innerHTML',curriculum.title)
    dajax.assign('#graSelection', 'innerHTML', "Select Grade")
    dajax.assign('#subSelection', 'innerHTML',
                 "<span class='faded'>Select Subject</span>")
    dajax.assign('#drop2', 'innerHTML', htmlStr)
    dajax.assign('#drop3', 'innerHTML', "")

    if big:
        dajax.assign(
            '#findButton', 'innerHTML',
            "<a class='btn btn-large btn-danger disabled'>Find Resources</a>")
    else:
        dajax.assign(
            '#findButton', 'innerHTML',
            "<a class='btn btn-small btn-danger disabled'>Find Resources</a>")
    return dajax.json()
Exemplo n.º 12
0
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()
Exemplo n.º 13
0
def addUser(request, form):
    dajax = Dajax()
    form = deserialize_form(form)
    k_id = form['kitty_id']
    user_form = KittyUserForm(form)

    if user_form.is_valid():
        dajax.remove_css_class('.form-group', 'has-error')
        user = user_form.save(commit=False)
        user.kitty_id = k_id
        user.save()
        # create item <-> User Connection
        for item in Item.objects.filter(kitty_id=k_id):
            if not user.useritem_set.filter(item=item).exists():
                UserItem.objects.create(item=item, quantity=0, user=user)
        dajax.script("$('#newUserModal').modal('hide');")
        dajax.script("location.reload();")
        brodcastNewUser(user)
    else:
        dajax.remove_css_class('.form-group', 'has-error')
        for error in user_form.errors:
            dajax.script(
                "$('#id_%s').parent().parent().addClass('has-error')" % error)

    return dajax.json()
Exemplo n.º 14
0
def decItem(request, item_id):
    dajax = Dajax()

    user_item = UserItem.objects.get(id=item_id)

    # dec item count
    user_item.quantity -= 1

    # giv back money to user
    user = user_item.user
    user.money += user_item.item.price

    # save both
    user_item.save()
    user.save()

    item = user_item.item
    item_quantity = item.useritem_set.all().aggregate(Sum('quantity'))

    # change frontend to new value
    dajax.assign('#id_user_item_%s' % item_id, 'innerHTML', user_item.quantity)
    dajax.assign('#id_user_name_%s' % user.id, 'innerHTML',
                 '%s (%s EUR)' % (user.name, user.money))
    dajax.assign('#id_item_quantity_consumed_%s' % item.id, 'innerHTML',
                 item_quantity['quantity__sum'])
    dajax.assign('#id_item_quantity_available_%s' % item.id, 'innerHTML',
                 item.quantity - item_quantity['quantity__sum'])

    brodcastUpdateUserItem(user_item)

    return dajax.json()
Exemplo n.º 15
0
def sync_misecampi(request):
	dajax=Dajax()
	from django.core.management import call_command
	#pdb.set_trace()
	call_command('MiseCampi')
	dajax.script("setInterval(function() {Dajaxice.persone.sync_misecampi_status(Dajax.process,{});}, 3000);")
	return dajax.json()
Exemplo n.º 16
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()
Exemplo n.º 17
0
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.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()
Exemplo n.º 18
0
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()
Exemplo n.º 19
0
def masCuadrillas(request):
    if request.method == 'POST':
        nuw = '%s-%s-%s %s' % (str(datetime.datetime.today().year),
                               str(datetime.datetime.today().month),
                               str(datetime.datetime.today().day),
                               str(timezone.localtime(timezone.now()).time()))
        print request.POST
        print nuw
        t = request.POST['fechaHora']
        if request.POST['fhFin']:
            nuw = str(request.POST['fhFin'])
        dajax = Dajax()
        pos = posicion.objects.filter(
            usuario__usuario_sico__contrato=request.session['contrato'],
            fechaHora__gt=str(t),
            fechaHora__lte=nuw).order_by('-fechaHora').distinct(
                'fechaHora', 'latitud', 'longitud')

        data = {'cuadrillas': pos}
        agregar = render_to_response('cuadrillas/renderCuadrilla.html', data)
        #print agregar
        dajax.prepend('#listaCuadrillas', 'innerHTML', agregar)

        return dajax.calls

    else:
        return None
Exemplo n.º 20
0
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()
Exemplo n.º 21
0
def get_person(req, dni):
    dajax = Dajax()
    try:
        p = Interrogatorio.objects.get(credencialPaciente=dni)
        dajax.assign('#id_herenciaMadre', 'value', p.herenciaMadre)
        dajax.assign('#id_herenciaPadre', 'value', p.herenciaPadre)
        dajax.assign('#id_herenciaHermanos', 'value', p.herenciaHermanos)
        dajax.assign('#id_herenciaHijos', 'value', p.herenciaHijos)
        dajax.assign('#id_habitosHigienicosVest', 'value',
                     p.habitosHigienicosVest)
        dajax.assign('#id_habitosHigienicosCorp', 'value',
                     p.habitosHigienicosCorp)
        dajax.assign('#id_adicciones', 'value', p.adicciones)
        dajax.assign('#id_alergias', 'value', p.alergias)
        dajax.assign('#id_fechaHospitalizaion', 'value', p.fechaHospitalizaion)
        dajax.assign('#id_padecimientoActual', 'value', p.padecimientoActual)
        dajax.assign('#id_aparatoDigestivo', 'value', p.aparatoDigestivo)
        dajax.assign('#id_aparatoRespiratorio', 'value', p.aparatoRespiratorio)
        dajax.assign('#id_aparatoCardioBascular', 'value',
                     p.aparatoCardioBascular)
        dajax.assign('#id_apararoGenitourinario', 'value',
                     p.apararoGenitourinario)
        dajax.assign('#id_sistemaEndocrina', 'value', p.sistemaEndocrina)
        dajax.assign('#id_sistemaHemopoyetico', 'value', p.sistemaHemopoyetico)
        dajax.assign('#id_sistemamusculoEsqueletico', 'value',
                     p.sistemamusculoEsqueletico)
        dajax.assign('#id_aparatoTegumentario', 'value', p.aparatoTegumentario)
        dajax.assign('#id_habitusExterior', 'value', p.habitusExterior)
        dajax.assign('#id_cabeza', 'value', p.cabeza)
    except Exception as e:
        print e

    return dajax.json()
Exemplo n.º 22
0
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()
Exemplo n.º 23
0
def bug_form_submit(request, form):
    dajax = Dajax()
    form = BugForm(deserialize_form(form))
    if form.is_valid():
        dajax.remove_css_class('#bug-form input', 'error')
        dajax.remove_css_class('#bug-form select', 'error')
        dajax.remove_css_class('#bug-form textarea', 'error')
        dajax.remove('.error-message')
        dajax.alert('Forms valid')
    else:
        dajax.remove_css_class('#bug-form input', 'error')
        dajax.remove_css_class('#bug-form select', 'error')
        dajax.remove_css_class('#bug-form textarea', 'error')
        dajax.remove('.error-message')
        for error in form.errors:
            dajax.add_css_class('#id_{0}'.format(error), 'error')
        for field in form:
            for error in field.errors:
                message = '<div class="error-message">* {0}</div>'.format(
                    error)
                dajax.append('#id_{0}_wrapper'.format(field.name), 'innerHTML',
                             message)
        # non field errors
        if form.non_field_errors():
            message = '<div class="error-message"><small>{0}</small></div>'.format(
                form.non_field_errors())
            dajax.append('#non-field-errors', 'innerHTML', message)
    return dajax.json()
Exemplo n.º 24
0
def notifiche(request,option,url):
    dajax = Dajax()
    #pdb.set_trace()
    i=0
    dajax.assign('#sele','value','')
    for not_id in url.rsplit('_'):
        i += 1
        selector='#not-'+not_id
        m = Notifica.objects.get(id=not_id)
        if (option == 'letto'):
            m.letto=True
            m.save()
            dajax.remove_css_class(selector,'warning')
        if (option == 'nonletto'):
            m.letto=False
            m.save()
            dajax.add_css_class(selector,'warning')
        if (option == 'cancella'):
            m.delete()
            dajax.remove(selector)
            dajax.remove('#not-inv-'+not_id)
            #dajax.alert(request.user.get_profile().nonletti())
    try:
        non=request.user.pers_user.notifiche_non_lette()
        if non >0:
           dajax.assign('#notifiche-badge','innerHTML',non)
        else:
           dajax.assign('#notifiche-badge','innerHTML','')
    except:
        pass
    dajax.clear('.ch','checked')
    dajax.script("$('#loading').addClass('hidden');")
    return dajax.json()
Exemplo n.º 25
0
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()
Exemplo n.º 26
0
def fileHistoryTimeliner(request, cloudItem, tokenID, altName):

    dajax = Dajax()

    try:
        t = parseAjaxParam(tokenID)
        ci = checkCloudItem(cloudItem, request.user.id)
        tkn = checkAccessToken(t, ci)
        tc = TimelinerController(tkn)
        data = tc.fileHistoryTimeLine(altName)

        #check that we have at least one item
        if len(data) > 0:
            ft = FileDownload.objects.get(alternateName=altName,
                                          tokenID=t).fileName
            table = render_to_string(
                "dashboard/timeliner/filehistorytimeline.html", {
                    'events': data,
                    'fileTitle': ft,
                    'altName': altName
                })
            dajax.assign("#fileHistory", "innerHTML", table)
            dajax.assign("#formHistoryError", "innerHTML", "")
        else:
            raise Exception("No history for this file")
    except Exception as e:
        dajax.assign("#formHistoryError", "innerHTML", formatException(e))

    return dajax.json()
Exemplo n.º 27
0
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()
Exemplo n.º 28
0
def updateSummary(request):
    """
    This function updates the table in summary div whenever a new group/core is added or when an existing group/core is edited or deleted

    """
    dajax = Dajax()
    dajax.assign(
        "#summary", 'innerHTML',
        "<table border='1'><thead><tr><th>S.No</th><th>Group Name</th><th>Cores</th></tr></thead><tbody id='groups'>"
    )
    groups = Group.objects.order_by('id').all()[1:]
    for g in groups:
        dajax.append(
            "#groups", 'innerHTML',
            "<tr><td>" + str(g.id - 1) + "</td><td class='grps' id=" + g.name +
            "><a href=" + '#editgroup/' + str(g.id) + '/' + ">" + g.name +
            "</a></td><td id=" + str(g.id) + "></td></tr>")
        cores = User.objects.filter(groups__name=g.name)
        for c in cores:
            if c.get_profile().is_core:
                dajax.append(
                    "#" + str(g.id), 'innerHTML',
                    "<li class='cores' id=" + str(c.username) + "><a href=" +
                    '#editcore/' + str(c.id) + '/' + ">" + str(c) + "</a>")
    dajax.assign(".bbq-item", "innerHTML", "<i>Space for displaying forms</i>")
    return dajax.json()
Exemplo n.º 29
0
def ajax_login(request):
    #return HttpResponse("Hello, world. You're at the poll index.")
    return simplejson.dumps({'message': 'Hello World'})
    dajax = Dajax()
    result = 3 * 5
    dajax.assign('#result', 'value', str(result))
    return dajax.json()
Exemplo n.º 30
0
def add_edit_core(request, form="", id=0):
    """
    This function calls the AddCoreForm from forms.py
    If a new core is being created, a blank form is displayed and the super user can fill in necessary details.
    If an existing core's details is being edited, the same form is displayed populated with current core details for all fields

    """
    dajax = Dajax()
    if id:
        core_form = AddCoreForm(form, instance=User.objects.get(id=id))
        if core_form.is_valid():
            core_form.save()
            dajax.script("updateSummary();")
        else:
            template = loader.get_template('ajax/admin/editcore.html')
            html = template.render(RequestContext(request, locals()))
            dajax.assign(".bbq-item", 'innerHTML', html)
    else:
        core_form = AddCoreForm(form)
        if core_form.is_valid():
            core = core_form.save()
            core.set_password("default")
            core.save()
            core_profile = UserProfile(user=core, is_core=True)
            core_profile.save()
            dajax.script("updateSummary();")
        else:
            template = loader.get_template('ajax/admin/addcore.html')
            html = template.render(RequestContext(request, locals()))
            dajax.assign(".bbq-item", 'innerHTML', html)
    return dajax.json()