Ejemplo n.º 1
0
def get_logged_in_user(request):
    if request.is_ajax():
        current_user = request.user.username
        response = {"user":current_user}
        return HttpResponse(json.dumps(response), content_type="application/json")
    else:
        return HttpResponse(json.dumps({'error':'ajax required'}), content_type="application/json")
Ejemplo n.º 2
0
def get_topic_form(request):
    if request.is_ajax():
        form = {'form':TopicForm()}
        template = 'courses/topic_create.html'
        response = {"form_html":render_to_string(template, form)}
        return HttpResponse(json.dumps(response), content_type="application/json")
    else:
        return HttpResponse(json.dumps({'error':'ajax required'}), content_type="application/json")
Ejemplo n.º 3
0
	def _output_json(self, payload):

		from django.core.serializers.json import simplejson

		if "callback" in self.request.DATA:
			return self.request.DATA["callback"] + "(%s);" % simplejson.dumps(payload)

		if hasattr(self, "sexy"):
			return simplejson.dumps(payload, indent=4)

		return simplejson.dumps(payload)
Ejemplo n.º 4
0
def handle_login(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    form = None

    if request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        csrf_middleware.process_view(request, None, None, None)
        if 'data' in request.POST:
            form = LoginForm(data=request.POST['data'])
            if form.is_valid():
                if not request.POST['meta']['validate']:
                    auth_login(request, form.get_user())
    else:
        form = LoginForm(request)
        response_data['csrfmiddlewaretoken'] = get_token(request)

    if form is not None:
        remote_form = RemoteForm(form)
        response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                            mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
Ejemplo n.º 5
0
def getstuinfoajax(request):
    if "userid" in request.session:
        if request.is_ajax():
            if request.method == 'POST':
                varuser = request.session['userid']
                varerr = ""
                post = request.POST.copy()
                acccode = post['userid']
                # print acccode
                session, klass = acccode.split(':')
                kk = []
                data = Student.objects.filter(admitted_class=klass,
                                              admitted_session=session,
                                              gone=False).order_by('fullname')
                for p in data:
                    jn = p.fullname
                    kk.append(jn)
                return HttpResponse(json.dumps(kk),
                                    mimetype='application/json')
            else:
                gdata = ""
                return render_to_response('index.html', {'gdata': gdata})
        else:

            gdata = ""
            return render_to_response('getlg.htm', {'gdata': gdata})
    else:
        return HttpResponseRedirect('/login/')
Ejemplo n.º 6
0
def handle_login(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    form = None

    if request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        csrf_middleware.process_view(request, None, None, None)
        if 'data' in request.POST:
            form = LoginForm(data=request.POST['data'])
            if form.is_valid():
                if not request.POST['meta']['validate']:
                    auth_login(request, form.get_user())
    else:
        form = LoginForm(request)
        response_data['csrfmiddlewaretoken'] = get_token(request)

    if form is not None:
        remote_form = RemoteForm(form)
        response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
Ejemplo n.º 7
0
def json_players(request, equipo):
	jugadores = Jugador.objects.filter(equipo__pk=equipo)
	jugadores = [{
			'pk':jugador.pk, 
			'nombre':jugador.nombre,
			'casaca':jugador.casaca,
		} for jugador in jugadores]
	return HttpResponse(simplejson.dumps({'jugadores':jugadores}))
Ejemplo n.º 8
0
def borraApuesta(request,id_apuesta):
    apuesta=get_object_or_404(Apuesta,pk=id_apuesta)
    participaciones=Participacion.objects.filter(apuesta=apuesta)
    for p in participaciones:
        usuario=Perfil.objects.get(user=p.user)
        usuario.dinero+=p.cantidad
        usuario.save()
        p.delete()
    apuesta.delete()
    response_data={'result':'ok'}
    return HttpResponse(simplejson.dumps(response_data), content_type="application/json")
    def generate_smd(self):

        smd = {"serviceType": "JSON-RPC", "serviceURL": self.rpc_service_instance.url, "methods": []}

        if self.report_methods:
            smd["methods"] = [
                {"name": method, "parameters": getattr(self.rpc_service_instance, method).get_args()}
                for method in self.get_public_methods()
            ]

        return HttpResponse(simplejson.dumps(smd), content_type="application/json")
Ejemplo n.º 10
0
Archivo: views.py Proyecto: pilt/bboard
 def create_ajax_response(self):
     completes = []
     try:
         term = self.request.GET['term']
         searches = Search.objects.filter(
             term__icontains=term
         ).exclude(
             hit_count=0
         ).order_by('-hit_count')
         completes = [s.term for s in searches]
     except KeyError:
         pass
     return HttpResponse(json.dumps(completes), mimetype='text/plain')
    def handle_request(self, request):
        data_to_process = {}
        if request.method == "POST":
            data_to_process = request.raw_post_data

        if len(data_to_process) > 0:
            self.time0 = time.time()
            response = self.serialize(data_to_process)
            self.time1 = time.time()
            time_string = "%.4f" % (self.time1 - self.time0)
            response.__setitem__("time_to_process", time_string)
            # return HttpResponse(encode(response), content_type="application/json")
            return HttpResponse(simplejson.dumps(response), content_type="application/json")

        return self.generate_smd()
Ejemplo n.º 12
0
def json_topic_form(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        form = TopicForm()
    elif request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)

        csrf_middleware.process_view(request, None, None, None, None)
        form_data = request.POST.get('data', {})
        form = TopicForm(form_data)
        if form.is_valid():
            form.save()

    remote_form = RemoteForm(form)

    response_data.update(remote_form_as_dict())

    response = HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), mimetype='application/json')

    csrf_middleware.process_response(request, response)
    return response;
Ejemplo n.º 13
0
def handle_instance_form(request, app_label, model_name, instance_id=None):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    csrf_middleware = CsrfViewMiddleware()

    response_data = {
        'meta': {
            'app_label': app_label,
            'model_name': model_name
        },

        'admin': {}
    }

    instance = None

    for model, model_admin in site._registry.items():
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue

        field_configuration = {
            'include': model_admin.fields or [],
            'exclude': model_admin.exclude or [],
            'ordering': model_admin.fields or [],
            'fieldsets': model_admin.fieldsets or {},
            'readonly': model_admin.readonly_fields or []
        }

        if instance_id is not None:
            response_data[instance_id] = instance_id
            try:
                instance = model.objects.get(pk=instance_id)
            except model.DoesNotExist:
                raise Http404('Invalid instance ID')

        current_model = model

        CurrentModelForm = ADMIN_FORM_OVERRIDES.get(model_name, None)

        if CurrentModelForm is None:
            class CurrentModelForm(ModelForm):
                class Meta:
                    model = current_model

        if request.method == 'GET':
            # Return instance form for given model name
            # Return initial values if instance ID is supplied, otherwise return empty form
            if instance is None:
                form = CurrentModelForm()
            else:
                form = CurrentModelForm(instance=instance)
                for field_name, initial_value in form.initial.items():
                    if initial_value is not None and field_name in form.fields:
                        form.fields[field_name].initial = initial_value

            response_data['csrfmiddlewaretoken'] = get_token(request)

            remote_form = RemoteForm(form, **field_configuration)
            response_data.update(remote_form.as_dict())
        elif request.raw_post_data:
            request.POST = json.loads(request.raw_post_data)
            csrf_middleware.process_view(request, None, None, None)
            if 'data' in request.POST:
                if instance_id is None:
                    form = CurrentModelForm(request.POST['data'])
                else:
                    form = CurrentModelForm(request.POST['data'], instance=instance)
                if form.is_valid():
                    if not request.POST['meta']['validate']:
                        form.save()

                remote_form = RemoteForm(form, **field_configuration)
                response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
Ejemplo n.º 14
0
def json_response(object, *args, **kwargs):
    kwargs['mimetype'] = 'text/json'
    response = HttpResponse(json.dumps(object), *args, **kwargs)
    response['Content-Disposition'] = 'inline'
    return response
Ejemplo n.º 15
0
    vtrack = []
    offset = int(request.GET.get('offset', 0))
    _status = 200
    if request.GET.get('id', None):
        vehicleid = request.GET.get('id')
    else:
        raise Http404
    try:
        vtrack = VehiclePosition.all().filter('vehicle_id = ' , vehicleid ).order('when').fetch(1000, offset=offset)
    except Exception, e:
        _status = 500
        
    # Form the Json 
    tpointList = []
    for tp in vtrack:
        _tempPt = { "pid": tp.key().id(), "lat": tp.latitude, "lng": tp.longitude, "time": str(tp.when), "speed": tp.speed }
        tpointList.append(_tempPt)
        
    _result = { 'status': _status, "id": vehicleid, "tracks": tpointList, "tstamp": str(datetime.datetime.now()) }
    jsondata = simplejson.dumps(_result, check_circular=True)
    
    return HttpResponse(jsondata, 'application/json')




def home(request):
    ''' Renders the page with Google map for interactivly tracking Vehicle with feeded GPS Data'''
    return render_to_response('base.html')
    
    
Ejemplo n.º 16
0
def get_models(request, app_label=None):
    # Return data on all models registered with admin

    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized request', status=401)

    if request.user.is_staff or request.user.is_superuser:
        has_module_perms = True
    else:
        has_module_perms = request.user.has_module_perms(app_label)

    app_list = []

    for model, model_admin in site._registry.items():
        model_name = model._meta.module_name

        if app_label is not None and app_label != model._meta.app_label:
            continue
        else:
            current_app_label = model._meta.app_label

        is_new_app = True
        current_app_dict = {
            'label': current_app_label,
            'title': capfirst(current_app_label),
            'has_module_perms': has_module_perms,
            'models': []
        }

        for app_dict in app_list:
            if app_dict['label'] == current_app_label:
                current_app_dict = app_dict
                is_new_app = False
                break

        if has_module_perms:
            if request.user.is_superuser:
                perms = {'add': True, 'change': True, 'delete': True}
            else:
                perms = model_admin.get_model_perms(request)

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True in perms.values():
                model_dict = {
                    'app_label': current_app_label,
                    'name': model_name,
                    'title':
                    unicode(capfirst(model._meta.verbose_name_plural)),
                    'perms': perms,
                }

                current_app_dict['models'].append(model_dict),

        if 'models' in current_app_dict:
            # Sort the models alphabetically within each app.
            current_app_dict['models'].sort(key=lambda x: x['name'])

        if is_new_app:
            app_list.append(current_app_dict)

    if not app_list:
        raise Http404('The requested admin page does not exist')

    response_data = {'app_list': app_list}

    return HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                        mimetype="application/json")
Ejemplo n.º 17
0
def handle_instance_form(request, app_label, model_name, instance_id=None):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    csrf_middleware = CsrfViewMiddleware()

    response_data = {
        'meta': {
            'app_label': app_label,
            'model_name': model_name
        },
        'admin': {}
    }

    instance = None

    for model, model_admin in site._registry.items():
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue

        field_configuration = {
            'include': model_admin.fields or [],
            'exclude': model_admin.exclude or [],
            'ordering': model_admin.fields or [],
            'fieldsets': model_admin.fieldsets or {},
            'readonly': model_admin.readonly_fields or []
        }

        if instance_id is not None:
            response_data[instance_id] = instance_id
            try:
                instance = model.objects.get(pk=instance_id)
            except model.DoesNotExist:
                raise Http404('Invalid instance ID')

        current_model = model

        CurrentModelForm = ADMIN_FORM_OVERRIDES.get(model_name, None)

        if CurrentModelForm is None:

            class CurrentModelForm(ModelForm):
                class Meta:
                    model = current_model

        if request.method == 'GET':
            # Return instance form for given model name
            # Return initial values if instance ID is supplied, otherwise return empty form
            if instance is None:
                form = CurrentModelForm()
            else:
                form = CurrentModelForm(instance=instance)
                for field_name, initial_value in form.initial.items():
                    if initial_value is not None and field_name in form.fields:
                        form.fields[field_name].initial = initial_value

            response_data['csrfmiddlewaretoken'] = get_token(request)

            remote_form = RemoteForm(form, **field_configuration)
            response_data.update(remote_form.as_dict())
        elif request.raw_post_data:
            request.POST = json.loads(request.raw_post_data)
            csrf_middleware.process_view(request, None, None, None)
            if 'data' in request.POST:
                if instance_id is None:
                    form = CurrentModelForm(request.POST['data'])
                else:
                    form = CurrentModelForm(request.POST['data'],
                                            instance=instance)
                if form.is_valid():
                    if not request.POST['meta']['validate']:
                        form.save()

                remote_form = RemoteForm(form, **field_configuration)
                response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                            mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
Ejemplo n.º 18
0
def get_model_instances(request, app_label, model_name):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    # Return list of instances for a given model
    response_data = {
        'name': model_name,
        'header': [],
        'instances': [],
        'admin': {}
    }

    for model, model_admin in site._registry.items():
        current_app_label = ''
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue
        else:
            current_app_label = model._meta.app_label

        response_data['admin'].update({
            'list_display': model_admin.list_display,
            'list_editable': model_admin.list_editable,
            'ordering': model_admin.ordering
        })

        if 'app' not in response_data:
            response_data['app'] = {
                'label': current_app_label,
                'title': capfirst(current_app_label)
            }

        if 'title' not in response_data:
            response_data['title'] = unicode(
                capfirst(model._meta.verbose_name_plural))

        is_header_generated = False

        for model_instance in model.objects.all():
            instance_data = {
                'id': model_instance.pk,
                'name': model_name,
                'app_label': app_label,
                'list_data': {
                    'lead': None,
                    'rest': []
                }
            }

            if '__str__' in response_data['admin']['list_display']:
                instance_data['list_data']['rest'] = (
                    model_instance.pk,
                    unicode(model_instance),
                )

                if not is_header_generated:
                    response_data['header'] = (
                        'ID',
                        'Title',
                    )
            else:
                for instance_property_name in response_data['admin'][
                        'list_display']:
                    instance_property_value = getattr(model_instance,
                                                      instance_property_name,
                                                      '')
                    if callable(instance_property_value):
                        instance_property_value = instance_property_value()

                    instance_property_value = unicode(instance_property_value)

                    if not is_header_generated:
                        normalized_instance_property_name = instance_property_name
                        if '__' in instance_property_name:
                            normalized_instance_property_name = ' '.join(
                                instance_property_name.split('__')[1:])

                        normalized_instance_property_name = capfirst(
                            normalized_instance_property_name)
                        response_data['header'].append(
                            normalized_instance_property_name)

                    instance_data['list_data']['rest'].append(
                        instance_property_value)

            if not is_header_generated:
                is_header_generated = True

            # Split the list of values
            instance_data['list_data']['lead'] = instance_data['list_data'][
                'rest'][0]
            instance_data['list_data']['rest'] = instance_data['list_data'][
                'rest'][1:]

            response_data['instances'].append(instance_data)

    return HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                        mimetype="application/json")
Ejemplo n.º 19
0
def get_models(request, app_label=None):
    # Return data on all models registered with admin

    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized request', status=401)

    if request.user.is_staff or request.user.is_superuser:
        has_module_perms = True
    else:
        has_module_perms = request.user.has_module_perms(app_label)

    app_list = []

    for model, model_admin in site._registry.items():
        model_name = model._meta.module_name

        if app_label is not None and app_label != model._meta.app_label:
            continue
        else:
            current_app_label = model._meta.app_label

        is_new_app = True
        current_app_dict = {
            'label': current_app_label,
            'title': capfirst(current_app_label),
            'has_module_perms': has_module_perms,
            'models': []
        }

        for app_dict in app_list:
            if app_dict['label'] == current_app_label:
                current_app_dict = app_dict
                is_new_app = False
                break

        if has_module_perms:
            if request.user.is_superuser:
                perms = {'add': True, 'change': True, 'delete': True}
            else:
                perms = model_admin.get_model_perms(request)

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True in perms.values():
                model_dict = {
                    'app_label': current_app_label,
                    'name': model_name,
                    'title': unicode(capfirst(model._meta.verbose_name_plural)),
                    'perms': perms,
                }

                current_app_dict['models'].append(model_dict),

        if 'models' in current_app_dict:
            # Sort the models alphabetically within each app.
            current_app_dict['models'].sort(key=lambda x: x['name'])

        if is_new_app:
            app_list.append(current_app_dict)

    if not app_list:
        raise Http404('The requested admin page does not exist')

    response_data = {
        'app_list': app_list
    }

    return HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
Ejemplo n.º 20
0
def render_json(output):
    if 'data' in output and isinstance(output['data'],dict) or isinstance(output['data'], OrderedDict):
        output['data'] = OrderedDict([(k.name, v) for k,v in output['data'].items()])
    return HttpResponse(simplejson.dumps(output, cls=JSONEncoder, indent=2), content_type="application/json")
Ejemplo n.º 21
0
def get_model_instances(request, app_label, model_name):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    # Return list of instances for a given model
    response_data = {
        'name': model_name,
        'header': [],
        'instances': [],
        'admin': {}
    }

    for model, model_admin in site._registry.items():
        current_app_label = ''
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue
        else:
            current_app_label = model._meta.app_label

        # Ignore callable admin change list field definitions. Sometimes these
        # are used to display static text in a change list column, and in such
        # cases we *could* do the call and pass the result through the
        # API. Let's do that only once we have a use case for it.
        regular_fields = [field_name for field_name in model_admin.list_display
                          if isinstance(field_name, basestring)]

        response_data['admin'].update({
            'list_display': regular_fields,
            'list_editable': model_admin.list_editable,
            'ordering': model_admin.ordering
        })

        if 'app' not in response_data:
            response_data['app'] = {
                'label': current_app_label,
                'title': capfirst(current_app_label)
            }

        if 'title' not in response_data:
            response_data['title'] = unicode(capfirst(model._meta.verbose_name_plural))

        is_header_generated = False

        for model_instance in model.objects.all():
            instance_data = {
                'id': model_instance.pk,
                'name': model_name,
                'app_label': app_label,
                'list_data': {
                    'lead': None,
                    'rest': []
                }
            }

            if '__str__' in response_data['admin']['list_display']:
                instance_data['list_data']['rest'] = (model_instance.pk, unicode(model_instance),)

                if not is_header_generated:
                    response_data['header'] = ('ID', 'Title',)
            else:
                for instance_property_name in response_data['admin']['list_display']:
                    instance_property_value = getattr(model_instance, instance_property_name, '')
                    if callable(instance_property_value):
                        instance_property_value = instance_property_value()

                    instance_property_value = unicode(instance_property_value)

                    if not is_header_generated:
                        normalized_instance_property_name = instance_property_name
                        if '__' in instance_property_name:
                            normalized_instance_property_name = ' '.join(instance_property_name.split('__')[1:])

                        normalized_instance_property_name = capfirst(normalized_instance_property_name)
                        response_data['header'].append(normalized_instance_property_name)

                    instance_data['list_data']['rest'].append(instance_property_value)

            if not is_header_generated:
                is_header_generated = True

            # Split the list of values
            instance_data['list_data']['lead'] = instance_data['list_data']['rest'][0]
            instance_data['list_data']['rest'] = instance_data['list_data']['rest'][1:]

            response_data['instances'].append(instance_data)

    return HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
Ejemplo n.º 22
0
def get_model_instances(request, app_label, model_name):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    # Return list of instances for a given model
    response_data = {
        'name': model_name,
        'header': [],
        'instances': [],
        'admin': {}
    }

    for model, model_admin in site._registry.items():
        current_app_label = ''
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue
        else:
            current_app_label = model._meta.app_label

        response_data['admin'].update({
            'list_display': model_admin.list_display,
            'list_editable': model_admin.list_editable,
            'ordering': model_admin.ordering
        })

        if 'app' not in response_data:
            response_data['app'] = {
                'label': current_app_label,
                'title': capfirst(current_app_label)
            }

        if 'title' not in response_data:
            response_data['title'] = unicode(capfirst(model._meta.verbose_name_plural))

        is_header_generated = False

        for model_instance in model.objects.all():
            instance_data = {
                'id': model_instance.pk,
                'name': model_name,
                'app_label': app_label,
                'list_data': {
                    'lead': None,
                    'rest': []
                }
            }

            if '__str__' in response_data['admin']['list_display']:
                instance_data['list_data']['rest'] = (model_instance.pk, unicode(model_instance),)

                if not is_header_generated:
                    response_data['header'] = ('ID', 'Title',)
            else:
                for instance_property_name in response_data['admin']['list_display']:
                    instance_property_value = getattr(model_instance, instance_property_name, '')
                    if callable(instance_property_value):
                        instance_property_value = instance_property_value()

                    instance_property_value = unicode(instance_property_value)

                    if not is_header_generated:
                        normalized_instance_property_name = instance_property_name
                        if '__' in instance_property_name:
                            normalized_instance_property_name = ' '.join(instance_property_name.split('__')[1:])

                        normalized_instance_property_name = capfirst(normalized_instance_property_name)
                        response_data['header'].append(normalized_instance_property_name)

                    instance_data['list_data']['rest'].append(instance_property_value)

            if not is_header_generated:
                is_header_generated = True

            # Split the list of values
            instance_data['list_data']['lead'] = instance_data['list_data']['rest'][0]
            instance_data['list_data']['rest'] = instance_data['list_data']['rest'][1:]

            response_data['instances'].append(instance_data)

    return HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
Ejemplo n.º 23
0
def jsonfilter(obj):
    return mark_safe(
        json.dumps(obj)
    )
Ejemplo n.º 24
0
 def wrap(req, *args, **kwargs):
     resp = func(req, *args, **kwargs)
     if isinstance(resp, HttpResponse):
         return resp
     return HttpResponse(json.dumps(resp), mimetype="application/json")
Ejemplo n.º 25
0
def json_response(data, **kw):
    return HttpResponse(json.dumps(data), content_type="application/json", **kw)