def dajaxice_register(original_function): """ Register the original funcion and returns it """ dajaxice_functions.register(original_function) return original_function
def decorator(function): @functools.wraps(function) def wrapper(request, *args, **kwargs): return function(request, *args, **kwargs) dajaxice_functions.register(function, *dargs, **dkwargs) return wrapper
def dajaxice_register(original_function): """ Register the original funcion and returns it """ dajaxice_functions.register(original_function) return original_function
def decorator(function): @functools.wraps(function) def wrapper(request, *args, **kwargs): return function(request, *args, **kwargs) dajaxice_functions.register(function, *dargs, **dkwargs) return wrapper
def dajaxice_register(*dargs, **dkwargs): """ Register some function as a dajaxice function For legacy purposes, if only a function is passed register it a simple single ajax function using POST, i.e: @dajaxice_register def ajax_function(request): ... After 0.5, dajaxice allow to customize the http method and the final name of the registered function. This decorator covers both the legacy and the new functionality, i.e: @dajaxice_register(method='GET') def ajax_function(request): ... @dajaxice_register(method='GET', name='my.custom.name') def ajax_function(request): ... You can also register the same function to use a different http method and/or use a different name. @dajaxice_register(method='GET', name='users.get') @dajaxice_register(method='POST', name='users.update') def ajax_function(request): ... """ if len(dargs) and not dkwargs: function = dargs[0] dajaxice_functions.register(function) return function def decorator(function): @functools.wraps(function) def wrapper(request, *args, **kwargs): return function(request, *args, **kwargs) dajaxice_functions.register(function, *dargs, **dkwargs) return wrapper return decorator
def dajaxice_register(*dargs, **dkwargs): """ Register some function as a dajaxice function For legacy purposes, if only a function is passed register it a simple single ajax function using POST, i.e: @dajaxice_register def ajax_function(request): ... After 0.5, dajaxice allow to customize the http method and the final name of the registered function. This decorator covers both the legacy and the new functionality, i.e: @dajaxice_register(method='GET') def ajax_function(request): ... @dajaxice_register(method='GET', name='my.custom.name') def ajax_function(request): ... You can also register the same function to use a different http method and/or use a different name. @dajaxice_register(method='GET', name='users.get') @dajaxice_register(method='POST', name='users.update') def ajax_function(request): ... """ if len(dargs) and not dkwargs: dajaxice_functions.register(*dargs) return dargs def decorator(function): @functools.wraps(function) def wrapper(request, *args, **kwargs): return function(request, *args, **kwargs) dajaxice_functions.register(function, *dargs, **dkwargs) return wrapper return decorator
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # DAMAGE. #---------------------------------------------------------------------- from django.utils import simplejson from dajaxice.core import dajaxice_functions def test_registered_function(request): return "" dajaxice_functions.register(test_registered_function) def test_string(request): return simplejson.dumps({'string': 'hello world'}) dajaxice_functions.register(test_string) def test_ajax_exception(request): raise Exception() return dajaxice_functions.register(test_ajax_exception) def test_foo(request): return ""
'is_update': update, 'profile': profile, 'likes': likes, 'dislikes': dislikes, 'comments': comments, 'ilike': ilike, 'idislike': idislike, 'icommented': icommented, 'expand': expand}, context_instance=RequestContext(request), response_format=response_format) dajax.add_data({'target': target, 'content': output}, 'anaf.add_data') return dajax.json() dajaxice_functions.register(comments_likes) 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']]
from dajaxice.core import dajaxice_functions from dajax.core.Dajax import Dajax from django.template import RequestContext from django.db.models import Q from treeio.core.rendering import render_to_string from treeio.core.models import UpdateRecord from treeio.news.views import _get_filter_query def get_more(request, target='#more-news', skip=20): dajax = Dajax() profile = request.user.get_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}, 'treeio.add_data') return dajax.json() dajaxice_functions.register(get_more)
from django.utils import simplejson from django.core.urlresolvers import reverse from dajaxice.core import dajaxice_functions from datetime import date today = date.today() from antxetamedia.agenda.models import Happening def happenings_for_month(request, year=today.year, month=today.month): dates = Happening.objects.filter( date__year=year, date__month=month, ).values_list('date') response = {} for date in dates: date = date[0] response[date.day] = reverse('agenda:day', args=( date.year, date.month, date.day)) return simplejson.dumps(response) dajaxice_functions.register(happenings_for_month)
'lat': 37.412061929307924, 'lng': -122.08582878112793, 'text': 'Other Site #2' }) points.append({ 'lat': 37.41301636171327, 'lng': -122.0780611038208, 'text': 'Other Site #3' }) dajax.add_data(points, 'example_draw_points') dajax.assign('#example_log', 'value', "3 Points loaded...") return dajax.json() dajaxice_functions.register(request_points) def move_point(request, lat, lng): dajax = Dajax() message = "Saved new location at, %s, %s" % (lat, lng) dajax.assign('#example_log', 'value', message) return dajax.json() dajaxice_functions.register(move_point) def multiply(request, a, b): dajax = Dajax() result = int(a) * int(b)
from datetime import datetime from dajaxice.core import dajaxice_functions from dajax.core import Dajax from models import Task, Milestone from django.contrib import messages from django.utils.translation import ugettext as _ def gantt(request, task, start, end): dajax = Dajax() try: t = Task.objects.get(pk=task) ot = _("Task") except: t = Milestone.objects.get(pk=task) ot = _("Milestone") s = datetime.strptime(start, "%Y-%m-%d").replace(hour=12) e = datetime.strptime(end, "%Y-%m-%d").replace(hour=12) t.start_date = s t.end_date = e t.save() messages.add_message( request, messages.INFO, _('%(ot)s "%(t)s" dates have been updated.') % {"ot": ot, "t": unicode(t)} ) return dajax.json() dajaxice_functions.register(gantt)
query_notificacion = queries_notificacion.pop() for item in queries_notificacion: query_notificacion &= item notificaciones = core_models.Documento.objects.filter(query_notificacion).\ filter(Q(leido=False) | Q(leido__isnull=True)) for notificacion in notificaciones: notificacion.leido=True notificacion.save() print 'check_watch - Se cambiaron ',len(notificaciones),' notificaciones...' return simplejson.dumps({'variable':variable}) dajaxice_functions.register(check_watch) def cargar_sub_categorias(request, nombre_categoria=None): subcategorias_json = [] if nombre_categoria: print 'cargar_sub_categorias - Filtrando por categoria', nombre_categoria subcategorias = core_models.SubcategoriaProducto.objects.filter(categoria = nombre_categoria) print 'cargar_sub_categorias - Encontrados', len(subcategorias), 'elementos' for subcategoria in subcategorias: subcategorias_json.append({ 'id' : subcategoria.nombre, 'value' : subcategoria.nombre }) else: print 'cargar_sub_categorias - No se ha dado el nombre de la categoria' return simplejson.dumps({'subcategorias':subcategorias_json})
'events':events},'draw_points') dajax.assign('#messageDisplay','innerHTML',"%d observations loaded..." % (len(events))) return dajax.json() dajax.assign('#messageDisplay','innerHTML',"No observations found") return dajax.json() def move_point(request, lat, lng): dajax = Dajax() message = "Saved new location at, %s, %s" % (lat, lng) dajax.assign('#example_log','value',message) return dajax.json() dajaxice_functions.register(request_points) dajaxice_functions.register(move_point) dajaxice_functions.register(filter) dajaxice_functions.register(post_accomplishments) dajaxice_functions.register(clear_accomplishments) dajaxice_functions.register(award_badge) dajaxice_functions.register(refresh_badges) def serialize_accomplishments(accomplishments): data = [] for accomplishment in accomplishments: data.append({'id':accomplishment.id, 'type':accomplishment.content_type.name, 'station':accomplishment.station.title, 'inquiry':accomplishment.inquiry.title, 'content':accomplishment.content, 'created':timesince(accomplishment.created)}) return data
dajax.assign('p#loginfieldhelp', 'innerHTML', '') dajax.assign('input#crtboxbutton', 'value', 'Save') dajax.assign('input#crtboxbutton', 'disabled', '') dajax.remove('#loginForm') dajax.redirect('/servers/') return dajax.json() else: dajax = Dajax() dajax.assign('p#loginfieldhelp', 'innerHTML', 'Account Disabled!') return dajax.json() else: dajax = Dajax() dajax.assign('p#loginfieldhelp', 'innerHTML', 'Invalid Login!') return dajax.json() dajaxice_functions.register(login_a) def server_stop(req, server_pk): """ Stop a server """ res = stop.delay(server_pk) res.wait() dajax = Dajax() dajax.assign('div#serverstatus', 'innerHTML', 'Stopped') return dajax.json() dajaxice_functions.register(server_stop) def server_start(req, server_pk): """ Start a server """ res = start.delay(server_pk) res.wait()
valid_contracts = Contract.objects.filter(start_date__lte=datetime.today(), end_date__gte=datetime.today()) msg = "<strong>Valid contracts :</strong><table>" print str(valid_contracts) for contract in valid_contracts: msg += "<tr class='hosts_expand'><td>%s</td><td>" % contract msg += "<span onclick=\"Dajaxice.banquise.web.add_host_to_contract('Dajax.process',{'host_id':%s,'contract_id':%s});\">" % ( host_id, contract.id) msg += "<img src='/media/images/icons/ok.png' height='16' border='0'></span></td></tr>" msg += "</table>" div_id = "#host_%s" % host_id dajax.assign(div_id, 'innerHTML', msg) return dajax.json() dajaxice_functions.register(display_valid_contracts) def add_host_to_contract(request, host_id, contract_id): dajax = Dajax() host = Host.objects.get(id=host_id) contract = Contract.objects.get(id=contract_id) contract.hosts.add(host) contract.save() msg = "" div_id = "#img_host_%s" % host_id dajax.assign(div_id, 'innerHTML', msg) div_id = "#host_%s" % host_id dajax.assign(div_id, 'innerHTML', msg) return dajax.json()
from django.contrib.gis.measure import Distance, D from dajaxice.core import dajaxice_functions from songs.models import SongLocation from songs.forms import SongLocationForm from songs.utils import * logger = logging.getLogger(__name__) def hello_ajax(request): ''' help test ajax function ''' return simplejson.dumps({'message':'Hello World'}) dajaxice_functions.register(hello_ajax) def get_items(request, zone): ''' return items to show in the map ''' # convert string zone to python dict zone = ast.literal_eval(zone) # filter by this location items = SongLocation.objects.all() if request.user.is_authenticated(): items = SongLocation.objects.all().exclude(user = request.user) inside_items = [] for item in items: if item.lat > zone[0][0] and item.lat < zone[1][0] and item.lon > zone[0][1] and item.lon < zone[1][1]: inside_items.append(item) json_serializer = serializers.get_serializer("json")() response = json_serializer.serialize(inside_items, ensure_ascii=False)
from django.utils import simplejson from dajaxice.core import dajaxice_functions from dajax.core import Dajax def myexample(request): return simplejson.dumps({'message': 'Hello World'}) def showalert(request): dajax = Dajax() #dajax.alert("foo") #dajax.redirect("http://www.google.com",delay=0) dajax.script('alert("foo")') return dajax.json() dajaxice_functions.register(showalert) dajaxice_functions.register(myexample)
# notice, this list of conditions, and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # o Neither the name of Digital Creations nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS AND CONTRIBUTORS *AS # IS* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL # CREATIONS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # DAMAGE. #---------------------------------------------------------------------- from dajaxice.core import dajaxice_functions def test_submodule_registered_function(request): return "" dajaxice_functions.register(test_submodule_registered_function)
"%d observations loaded..." % (len(events))) return dajax.json() dajax.assign('#messageDisplay', 'innerHTML', "No observations found") return dajax.json() def move_point(request, lat, lng): dajax = Dajax() message = "Saved new location at, %s, %s" % (lat, lng) dajax.assign('#example_log', 'value', message) return dajax.json() dajaxice_functions.register(request_points) dajaxice_functions.register(move_point) dajaxice_functions.register(filter) dajaxice_functions.register(post_accomplishments) dajaxice_functions.register(clear_accomplishments) dajaxice_functions.register(award_badge) dajaxice_functions.register(refresh_badges) def serialize_accomplishments(accomplishments): data = [] for accomplishment in accomplishments: data.append({ 'id': accomplishment.id, 'type': accomplishment.content_type.name,
def dajaxicyfy(func): dajaxice.register(func) return func
if formset.is_valid(): for form in formset: num_books = int(form.cleaned_data['numbers']) book_year = form.cleaned_data['years'] if num_books > 0: price += num_books * Book.objects.get(year=book_year).price if shipping_paid: price += num_books * shipping_price items.append("%sx%s-Book" %(num_books, book_year)) price = locale.currency(price, grouping=True) items.sort(reverse=True) if shipping_paid: items.append("Shipping") items = ", ".join(items) except ObjectDoesNotExist: dajax.alert("Oops! We don't have a price defined - please email [email protected] to let us know and we'll get it fixed as soon as possible.") price = "Error!" comment = "Error!" except Exception as ex: dajax.alert(ex.message) dajax.assign('#total', 'value', price); dajax.assign('#comment', 'value', items); return dajax.json() dajaxice_functions.register(update_purchase)
from django.utils import simplejson from django.core.urlresolvers import reverse from dajaxice.core import dajaxice_functions from datetime import date today = date.today() from antxetamedia.agenda.models import Happening def happenings_for_month(request, year=today.year, month=today.month): dates = Happening.objects.filter( date__year=year, date__month=month, ).values_list('date') response = {} for date in dates: date = date[0] response[date.day] = reverse('agenda:day', args=(date.year, date.month, date.day)) return simplejson.dumps(response) dajaxice_functions.register(happenings_for_month)
'likes': likes, 'dislikes': dislikes, 'comments': comments, 'ilike': ilike, 'idislike': idislike, 'icommented': icommented, 'expand': expand }, context_instance=RequestContext(request), response_format=response_format) dajax.add_data({'target': target, 'content': output}, 'anaf.add_data') return dajax.json() dajaxice_functions.register(comments_likes) 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']]
from django.utils import simplejson from dajaxice.core import dajaxice_functions def example1(request): return simplejson.dumps({'message':'hello world'}) dajaxice_functions.register(example1) def example2(request): return simplejson.dumps({'numbers':[1,2,3]}) dajaxice_functions.register(example2) def example3(request, data, name): result = sum(map(int,data)) return simplejson.dumps({'result':result}) dajaxice_functions.register(example3) def error_example(request): raise Exception("Some Exception") dajaxice_functions.register(error_example)
form = GigBargainBandTimelineForm(form) return submit_form(request, '#timeline-form', form, gigbargainband) def remuneration_edit(request, gigbargainband_id, form): gigbargainband = get_object_or_404(GigBargainBand, pk=gigbargainband_id) form = GigBargainBandRemunerationForm(form) return submit_form(request, '#remuneration-form', form, gigbargainband) def defrayment_edit(request, gigbargainband_id, form): gigbargainband = get_object_or_404(GigBargainBand, pk=gigbargainband_id) form = GigBargainBandDefraymentForm(form) return submit_form(request, '#defrayment-form', form, gigbargainband) def band_invite(request, gigbargain_id, form): gigbargain = get_object_or_404(GigBargain, pk=gigbargain_id) form = GigBargainBandInviteForm(gigbargain, form) return submit_form(request, '#band-invite-form', form, gigbargain) dajaxice_functions.register(band_invite) dajaxice_functions.register(timeline_edit) dajaxice_functions.register(remuneration_edit) dajaxice_functions.register(defrayment_edit) dajaxice_functions.register(access_edit)
# Default imports for JavaScript functionality from django.utils import simplejson from dajaxice.core import dajaxice_functions # In this file declare all ajax related views, oookaay? def myexample(request): return simplejson.dumps({'message':'Hello World'}) dajaxice_functions.register(myexample)
def dajaxice_function(f): dajaxice_functions.register(f) return f
from dajax.core import Dajax from django.template.loader import render_to_string from dajaxice.core import dajaxice_functions def assign_test(request): dajax = Dajax() dajax.assign('#block01 li','innerHTML','Something else...') dajax.append('#console','innerHTML',"dajax.assign('#block01 li','innerHTML','Something else...')<br/>") return dajax.json() dajaxice_functions.register(assign_test) def clear_test(request): dajax = Dajax() dajax.clear('#block02 li','innerHTML') dajax.append('#console','innerHTML',"dajax.clear('#block02 li','innerHTML')<br/>") return dajax.json() dajaxice_functions.register(clear_test) def alert_test(request): dajax = Dajax() dajax.alert('Alert Test Works!!') dajax.append('#console','innerHTML',"dajax.alert('Alert Test Works!!')<br/>") return dajax.json() dajaxice_functions.register(alert_test) def cssadd_test(request): dajax = Dajax()
from dajax.core import Dajax from dajaxice.core import dajaxice_functions from academica.models import PlanEstudio __author__ = 'Luisk' # # def getMunicipiosByProvincia(request,id_provincia): # dajax = Dajax() # objects = Municipio.objects.filter(provincia=id_provincia) # options = '<option selected="selected" value="">---------</option>' # for obj in objects: # options += '<option value="%s">%s</option>' % (obj.id_mcpio,obj.nombre) # dajax.assign('#id_municipio','innerHTML', options) # return dajax.json() # # dajaxice_functions.register(getMunicipiosByProvincia) def getPlandeEstudios(request): dajax = Dajax() options = '<option selected="selected" value="">---------</option>' plan = PlanEstudio.objects.all() for p in plan: options += '<optgroup label="%s">' % p.nom_plan options += '<option value="%s">%s</option>'% (p.id,p.get_full_name()) options += '</optgroup>' #~ dajax.assign('#id_participantes','innerHTML',options) return dajax.json() dajaxice_functions.register(getPlandeEstudios)
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # DAMAGE. #---------------------------------------------------------------------- from django.utils import simplejson from dajaxice.core import dajaxice_functions def test_registered_function(request): return "" dajaxice_functions.register(test_registered_function) def test_string(request): return simplejson.dumps({'string': 'hello world'}) dajaxice_functions.register(test_string) def test_ajax_exception(request): raise Exception() return dajaxice_functions.register(test_ajax_exception)
from plandechicasapp.models import UserProfile, FriendRequest, Message, MessageThread, Notification, Product from django.contrib.auth.models import User from django.db.models import Q def send_friend_request(request, request_message, receiver): user_to_search = User.objects.get(username=receiver) profile = user_to_search.get_profile() fRequest = FriendRequest() fRequest.sender = request.user.get_profile() fRequest.receiver = profile fRequest.text = request_message fRequest.sender_username = request.user.username fRequest.receiver_username = user_to_search.username fRequest.save() dajaxice_functions.register(send_friend_request) def send_message(request, message_text, receiver): user_to_search = User.objects.get(username=receiver) profile = user_to_search.get_profile() messageThread = MessageThread() message = Message() messageThread.sender = request.user.get_profile() messageThread.receiver = profile message.text = message_text message.save() messageThread.save() dajaxice_functions.register(send_message) def accept_friend_request(request, receiver):
#from dajax.core import Dajax from django.utils import simplejson from dajaxice.core import dajaxice_functions from models import * import logging l = logging.getLogger() debug = l.debug def get_municipio_code(request, nombre): try: debug("Buscando %s"%nombre) municipio = Municipio.objects.get(nombre__icontains=nombre) debug("Encontrado el municipio con id %s"%municipio.id) mensaje ="Hola %s!"%(municipio.get_code()) id = municipio.id code = municipio.get_code() except: id = 0 code = 0 mensaje = "No lo hemos encontrado" return simplejson.dumps({'message':mensaje, 'id': id, 'loc_id':code}) dajaxice_functions.register(get_municipio_code)
def dajaxicyfy(func): dajaxice.register(func) return func
""" ajax module """ from django.utils import simplejson from dajaxice.core import dajaxice_functions from store.models import User, User_Apps, App, Chartstring, Group from notifications import delete_Notifications def message_update(request): user = User.objects.get(name=request.session['user']) # Debugging statements. print '=====================================' print user.name delete_Notifications(user) return simplejson.dumps({'message': 'Messages cleared!'}) dajaxice_functions.register(message_update)
import urllib import re #set java server Java Server java_server = 'http://live.2.dev2012oexpp.appspot.com' #java_server='http://127.0.0.1:8888' #_____________________________________________# def myExample(request): return simplejson.dumps({'message': 'Hello World'}) dajaxice_functions.register(myExample) #_____________________________________________# def getSolution(request, q_id): params = {} q = question.objects.get(id=q_id) if (q.std_answer != None and q.std_answer != ''): params['answer'] = q.std_answer elif (q.std_answer_latex != None and q.std_answer_latex != ''): params['answer'] = q.std_answer_latex else: ans = answer.objects.filter(question_id=q_id) if (len(ans) > 0): params['answer'] = ans[0].content
#for calling java at version 2 import urllib2 import urllib import re #set java server Java Server java_server='http://live.2.dev2012oexpp.appspot.com' #java_server='http://127.0.0.1:8888' #_____________________________________________# def myExample(request): return simplejson.dumps({'message':'Hello World'}) dajaxice_functions.register(myExample) #_____________________________________________# def getSolution(request,q_id): params={} q=question.objects.get(id=q_id) if(q.std_answer!=None and q.std_answer!=''): params['answer']=q.std_answer elif(q.std_answer_latex!=None and q.std_answer_latex!=''): params['answer']=q.std_answer_latex else: ans=answer.objects.filter(question_id=q_id) if (len(ans)>0): params['answer']=ans[0].content else:
from django.utils import simplejson from dajaxice.core import dajaxice_functions def example1(request): """ First simple example """ return simplejson.dumps({'message': 'hello world'}) dajaxice_functions.register(example1) def example2(request): """ Second simple example """ return simplejson.dumps({'numbers': [1, 2, 3]}) dajaxice_functions.register(example2) def example3(request, data, name): result = sum(map(int, data)) return simplejson.dumps({'result': result}) dajaxice_functions.register(example3) def error_example(request): raise Exception("Some Exception") dajaxice_functions.register(error_example)
News ajax views """ from dajaxice.core import dajaxice_functions from dajax.core import Dajax from django.template import RequestContext from django.db.models import Q from anaf.core.rendering import render_to_string from anaf.core.models import UpdateRecord from views import _get_filter_query 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() dajaxice_functions.register(get_more)
from django.utils import simplejson from dajaxice.core import dajaxice_functions def complex_example1(request): return simplejson.dumps({'message':'hello world'}) dajaxice_functions.register(complex_example1) def complex_example2(request): return simplejson.dumps({'numbers':[1,2,3]}) dajaxice_functions.register(complex_example2)
''' Created on Jun 24, 2011 @author: jackdreilly ''' from VoyeurHero.backend.models import VHPost from dajaxice.core import dajaxice_functions from django.shortcuts import render_to_response from django.template.context import RequestContext from django.utils import simplejson from django.template.loader import render_to_string def post_comments_form(request, post_id): return render_to_string('backend/ajax/post_comments_form.html',dict(post = VHPost.objects.get(id=post_id)), RequestContext(request)) dajaxice_functions.register(post_comments_form)
from django.utils import simplejson from dajaxice.core import dajaxice_functions import views def myexample(request): return search(request) dajaxice_functions.register(myexample)
text = arduino.readline().rstrip() except serial.SerialException: error = True else: text_array = text.split(',') try: newVotes = map(lambda x: int(x), text_array) except ValueError: error = True try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: choices = ['some', 'error', 'happened', '^ ^', 'LOL'] else: if not(error) and len(newVotes) >= 5: i = 0 for choice in p.choice_set.all(): choice.votes = newVotes[i] choice.save() i += 1 votes = [] choices = [] for choice in p.choice_set.values_list(): choices.append(choice[2]) votes.append(choice[3]) #dajax.assign('#result', 'value', ') return simplejson.dumps({'choices': choices, 'votes': votes}) dajaxice_functions.register(getVotes)
htmlOutput = "" for user in users: link_prof_details = reverse('profile_detail', args=(user,)) try: name = user.get_profile().first_name lastname = user.get_profile().last_name small_about = user.get_profile().get_small_about() except: name = user.username lastname = '' small_about = '' username = user.username avatar = avatar_url(user, 70) if len(name) == 0: name = username htmlOutput += template % ( link_prof_details, name, lastname, avatar, username, link_prof_details, name, lastname, name, lastname, small_about ) dajax = Dajax() dajax.append('#list-profiles','innerHTML', htmlOutput) dajax.assign('#last_profile','innerHTML', last_prof+len(users)) return dajax.json() dajaxice_functions.register(more_profiles)
def dajaxice_function(f): dajaxice_functions.register(f) return f
from django.core.serializers import json from dajaxice.decorators import dajaxice_register from dajaxice.core import dajaxice_functions @dajaxice_register def sayhello(request): return json.dumps({'message': 'Hello World'}) dajaxice_functions.register(sayhello)
from django.utils import simplejson from dajaxice.core import dajaxice_functions from dajax.core import Dajax def myexample(request): return simplejson.dumps({'message':'Hello World'}) def showalert(request): dajax = Dajax() #dajax.alert("foo") #dajax.redirect("http://www.google.com",delay=0) dajax.script('alert("foo")') return dajax.json() dajaxice_functions.register(showalert) dajaxice_functions.register(myexample)
# License www.tree.io/license from datetime import datetime, time from dajaxice.core import dajaxice_functions from dajax.core.Dajax import Dajax from treeio.projects.models import Task, Milestone from django.contrib import messages from django.utils.translation import ugettext as _ def gantt(request, task, start, end): dajax = Dajax() try: t = Task.objects.get(pk=task) ot = _("Task") except: t = Milestone.objects.get(pk=task) ot = _("Milestone") s = datetime.strptime(start, '%Y-%m-%d').replace(hour=12) e = datetime.strptime(end, '%Y-%m-%d').replace(hour=12) t.start_date = s t.end_date = e t.save() messages.add_message( request, messages.INFO, _("%s \"%s\" dates have been updated.") % (ot, unicode(t))) return dajax.json() dajaxice_functions.register(gantt)
link_details_pub = reverse('publication_details', args=(update.publication.author,update.publication.id,)) name = update.publication.author.get_profile().first_name lastname = update.publication.author.get_profile().last_name text_pub = update.publication.get_small_text() username = update.publication.author.username avatar_pub = avatar_url(update.publication.author, 70) htmlOutput += template_pub % ( link_prof_details_pub, name, lastname, avatar_pub, username ,link_prof_details_pub, name, lastname, name, lastname, link_details_pub, media_url, update.publication.get_thumbnail150_name(), link_details_pub, update.publication.title, link_details_pub, update.publication.title, text_pub ) else: link_prof_details_post = reverse('profile_detail', args=(update.post.author,)) link_post_url = update.post.get_absolute_url() name = update.post.author.get_profile().first_name lastname = update.post.author.get_profile().last_name text_post = update.post.get_small_text() username = update.post.author.username avatar_post = avatar_url(update.post.author, 70) htmlOutput += template_post % ( link_prof_details_post, name, lastname, avatar_post, username, link_prof_details_post, name, lastname, name, lastname, link_post_url, update.post.title, text_post ) dajax = Dajax() dajax.append('#list-updates','innerHTML', htmlOutput) dajax.assign('#last_update','innerHTML', last_up+len(updates)) return dajax.json() dajaxice_functions.register(more_updates)
except: clothes = Clothing.objects.all().iterator() continue if random.random() < .2: returnSet.append(next) return serialize('json',returnSet) def getGridItems(request): index = randint(0,450) return dumps([render_to_string('startup/webui/grid-item.html',dict(model = model)) for model in Clothing.objects.all()[index:index + 8]]) def getLeadItem(request): index = randint(0,450) return render_to_string('startup/webui/lead-item.html',dict(model = Clothing.objects.all()[index])) dajaxice_functions.register(clothingVote) dajaxice_functions.register(startClothes) dajaxice_functions.register(getGridItems) dajaxice_functions.register(getLeadItem) def filterOnWaist(request,waist): temps = [render_to_string('startup/webui/grid-item.html',dict(model = model)) for model in Clothing.objects.filter(waist_size=int(waist))[:8]] shuffle(temps) return dumps(temps) dajaxice_functions.register(filterOnWaist)
from django.utils import simplejson from dajaxice.core import dajaxice_functions def complex_example1(request): return simplejson.dumps({'message': 'hello world'}) dajaxice_functions.register(complex_example1) def complex_example2(request): return simplejson.dumps({'numbers': [1, 2, 3]}) dajaxice_functions.register(complex_example2)
if project_themes_form.is_valid(): project_themes_form.save() # Convert objectives to list if string or empty if not related_form.has_key('objectives-form-objectives'): related_form['objectives-form-objectives'] = [] if not isinstance(related_form['objectives-form-objectives'], list): related_form['objectives-form-objectives'] = related_form['objectives-form-objectives'].split(',') project_objectives_form = I4pProjectObjectivesForm(related_form, instance=parent_project, prefix="objectives-form") if project_objectives_form.is_valid(): project_objectives_form.save() return simplejson.dumps({}) # Dajax Registration dajaxice_functions.register(project_update_related)