Esempio n. 1
0
def edit(request):
  try:
    editParams = viewutil.request_params(request)
    edittype = editParams['type']
    if not request.user.has_perm('tracker.change_' + permmap.get(edittype,edittype)):
      return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
    Model = modelmap[edittype]
    obj = Model.objects.get(pk=editParams['id'])
    changed = []
    for k,v in editParams.items():
      if k in ('type','id'): continue
      if v == 'None':
        v = None
      elif fkmap.get(k,k) in modelmap:
        v = modelmap[fkmap.get(k,k)].objects.get(id=v)
      if unicode(getattr(obj,k)) != unicode(v):
        changed.append(k)
      setattr(obj,k,v)
    obj.full_clean()
    obj.save()
    if changed:
      log.change(request,obj,u'Changed field%s %s.' % (len(changed) > 1 and 's' or '', ', '.join(changed)))
    resp = HttpResponse(serializers.serialize('json', Model.objects.filter(id=obj.id), ensure_ascii=False),content_type='application/json;charset=utf-8')
    if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
      return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
    return resp
  except IntegrityError, e:
    return HttpResponse(json.dumps({'error': u'Integrity error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
Esempio n. 2
0
def delete(request):
    try:
        deleteParams = viewutil.request_params(request)
        deltype = deleteParams['type']
        if not request.user.has_perm('tracker.delete_' +
                                     permmap.get(deltype, deltype)):
            return HttpResponse('Access denied',
                                status=403,
                                content_type='text/plain;charset=utf-8')
        obj = modelmap[deltype].objects.get(pk=deleteParams['id'])
        logutil.deletion(request, obj)
        obj.delete()
        return HttpResponse(json.dumps(
            {
                'result':
                u'Object %s of type %s deleted' %
                (deleteParams['id'], deleteParams['type'])
            },
            ensure_ascii=False),
                            content_type='application/json;charset=utf-8')
    except IntegrityError, e:
        return HttpResponse(json.dumps({'error': u'Integrity error: %s' % e},
                                       ensure_ascii=False),
                            status=400,
                            content_type='application/json;charset=utf-8')
Esempio n. 3
0
def add(request):
  try:
    addParams = viewutil.request_params(request)
    addtype = addParams['type']
    if not request.user.has_perm('tracker.add_' + permmap.get(addtype,addtype)):
      return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
    Model = modelmap[addtype]
    newobj = Model()
    for k,v in addParams.items():
      if k in ('type','id'):
        continue
      if v == 'null':
        v = None
      elif fkmap.get(k,k) in modelmap:
        v = modelmap[fkmap.get(k,k)].objects.get(id=v)
      setattr(newobj,k,v)
    newobj.full_clean()
    newobj.save()
    log.addition(request, newobj)
    resp = HttpResponse(serializers.serialize('json', Model.objects.filter(id=newobj.id), ensure_ascii=False),content_type='application/json;charset=utf-8')
    if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
      return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
    return resp
  except IntegrityError, e:
    return HttpResponse(json.dumps({'error': u'Integrity error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
Esempio n. 4
0
def prize_donors(request):
    try:
        if not request.user.has_perm('tracker.change_prize'):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
        requestParams = viewutil.request_params(request)
        id = int(requestParams['id'])
        resp = HttpResponse(json.dumps(Prize.objects.get(pk=id).eligible_donors()),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except Prize.DoesNotExist:
        return HttpResponse(json.dumps({'error': 'Prize id does not exist'}),status=404,content_type='application/json;charset=utf-8')
Esempio n. 5
0
def delete(request):
    try:
        deleteParams = viewutil.request_params(request)
        deltype = deleteParams['type']
        if not request.user.has_perm('tracker.delete_' + permmap.get(deltype,deltype)):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
        obj = modelmap[deltype].objects.get(pk=deleteParams['id'])
        logutil.deletion(request, obj)
        obj.delete()
        return HttpResponse(json.dumps({'result': u'Object %s of type %s deleted' % (deleteParams['id'], deleteParams['type'])}, ensure_ascii=False), content_type='application/json;charset=utf-8')
    except IntegrityError, e:
        return HttpResponse(json.dumps({'error': u'Integrity error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
Esempio n. 6
0
def prize_donors(request):
    try:
        if not request.user.has_perm('tracker.change_prize'):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
        requestParams = viewutil.request_params(request)
        id = int(requestParams['id'])
        resp = HttpResponse(json.dumps(Prize.objects.get(pk=id).eligible_donors()),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except Prize.DoesNotExist:
        return HttpResponse(json.dumps({'error': 'Prize id does not exist'}),status=404,content_type='application/json;charset=utf-8')
Esempio n. 7
0
def search(request):
    authorizedUser = request.user.has_perm('tracker.can_search')
    #  return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
    try:
        searchParams = viewutil.request_params(request)
        searchtype = searchParams['type']
        qs = filters.run_model_query(searchtype, searchParams, user=request.user, mode='admin' if authorizedUser else 'user')
        if searchtype in related:
            qs = qs.select_related(*related[searchtype])
        if searchtype in defer:
            qs = qs.defer(*defer[searchtype])
        qs = qs.annotate(**viewutil.ModelAnnotations.get(searchtype,{}))
        if qs.count() > 1000:
            qs = qs[:1000]
        jsonData = json.loads(serializers.serialize('json', qs, ensure_ascii=False))
        objs = dict(map(lambda o: (o.id,o), qs))
        for o in jsonData:
            baseObj = objs[int(o['pk'])]
            if isinstance(baseObj, Donor):
                o['fields']['public'] = baseObj.visible_name()
            else:
                o['fields']['public'] = unicode(baseObj)
            for a in viewutil.ModelAnnotations.get(searchtype,{}):
                o['fields'][a] = unicode(getattr(objs[int(o['pk'])],a))
            for r in related.get(searchtype,[]):
                ro = objs[int(o['pk'])]
                for f in r.split('__'):
                    if not ro: break
                    ro = getattr(ro,f)
                if not ro: continue
                relatedData = json.loads(serializers.serialize('json', [ro], ensure_ascii=False))[0]
                for f in ro.__dict__:
                    if f[0] == '_' or f.endswith('id') or f in defer.get(searchtype,[]): continue
                    v = relatedData["fields"][f]
                    o['fields'][r + '__' + f] = relatedData["fields"][f]
                if isinstance(ro, Donor):
                    o['fields'][r + '__public'] = ro.visible_name()
                else:
                    o['fields'][r + '__public'] = unicode(ro)
            if not authorizedUser:
                donor_privacy_filter(searchtype, o['fields'])
                donation_privacy_filter(searchtype, o['fields'])
                prize_privacy_filter(searchtype, o['fields'])
            clean_fields = getattr(Filters, searchtype, None)
            if clean_fields:
                clean_fields(request.user, o['fields'])
        resp = HttpResponse(json.dumps(jsonData,ensure_ascii=False),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except KeyError, e:
        return HttpResponse(json.dumps({'error': 'Key Error, malformed search parameters'}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
Esempio n. 8
0
def draw_prize(request):
    try:
        if not request.user.has_perm('tracker.change_prize'):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')

        requestParams = viewutil.request_params(request)
        id = int(requestParams['id'])
        prize = Prize.objects.get(pk=id)

        if prize.maxed_winners():
            maxWinnersMessage = "Prize: " + prize.name + " already has a winner." if prize.maxwinners == 1 else "Prize: " + prize.name + " already has the maximum number of winners allowed."
            return HttpResponse(json.dumps({'error': maxWinnersMessage}),status=409,content_type='application/json;charset=utf-8')

        skipKeyCheck = requestParams.get('skipkey', False)

        if not skipKeyCheck:
            eligible = prize.eligible_donors()
            if not eligible:
                return HttpResponse(json.dumps({'error': 'Prize has no eligible donors'}),status=409,content_type='application/json;charset=utf-8')
            key = hash(json.dumps(eligible))
            if 'key' not in requestParams:
                return HttpResponse(json.dumps({'key': key}),content_type='application/json;charset=utf-8')
            else:
                try:
                    inputKey = type(key)(requestParams['key'])
                    if inputKey != key:
                        return HttpResponse(json.dumps({'error': 'Key field did not match expected value'},ensure_ascii=False),status=400,content_type='application/json;charset=utf-8')
                except (ValueError,KeyError),e:
                    return HttpResponse(json.dumps({'error': 'Key field was missing or malformed', 'exception': '%s %s' % (type(e),e)},ensure_ascii=False),status=400,content_type='application/json;charset=utf-8')


        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')

        limit = requestParams.get('limit', prize.maxwinners)
        if not limit:
            limit = prize.maxwinners

        currentCount = prize.current_win_count()
        status = True
        results = []
        while status and currentCount < limit:
            status, data = prizeutil.draw_prize(prize, seed=requestParams.get('seed',None))
            if status:
                currentCount += 1
                results.append(data)
                logutil.change(request,prize,u'Picked winner. %.2f,%.2f' % (data['sum'],data['result']))
                return HttpResponse(json.dumps({'success': results}, ensure_ascii=False),content_type='application/json;charset=utf-8')
            else:
                return HttpResponse(json.dumps(data),status=400,content_type='application/json;charset=utf-8')
Esempio n. 9
0
def draw_prize(request):
    try:
        if not request.user.has_perm('tracker.change_prize'):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')

        requestParams = viewutil.request_params(request)
        id = int(requestParams['id'])
        prize = Prize.objects.get(pk=id)

        if prize.maxed_winners():
            maxWinnersMessage = "Prize: " + prize.name + " already has a winner." if prize.maxwinners == 1 else "Prize: " + prize.name + " already has the maximum number of winners allowed."
            return HttpResponse(json.dumps({'error': maxWinnersMessage}),status=409,content_type='application/json;charset=utf-8')

        skipKeyCheck = requestParams.get('skipkey', False)

        if not skipKeyCheck:
            eligible = prize.eligible_donors()
            if not eligible:
                return HttpResponse(json.dumps({'error': 'Prize has no eligible donors'}),status=409,content_type='application/json;charset=utf-8')
            key = hash(json.dumps(eligible))
            if 'key' not in requestParams:
                return HttpResponse(json.dumps({'key': key}),content_type='application/json;charset=utf-8')
            else:
                try:
                    inputKey = type(key)(requestParams['key'])
                    if inputKey != key:
                        return HttpResponse(json.dumps({'error': 'Key field did not match expected value'},ensure_ascii=False),status=400,content_type='application/json;charset=utf-8')
                except (ValueError,KeyError),e:
                    return HttpResponse(json.dumps({'error': 'Key field was missing or malformed', 'exception': '%s %s' % (type(e),e)},ensure_ascii=False),status=400,content_type='application/json;charset=utf-8')


        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')

        limit = requestParams.get('limit', prize.maxwinners)
        if not limit:
            limit = prize.maxwinners

        currentCount = prize.current_win_count()
        status = True
        results = []
        while status and currentCount < limit:
            status, data = prizeutil.draw_prize(prize, seed=requestParams.get('seed',None))
            if status:
                currentCount += 1
                results.append(data)
                logutil.change(request,prize,u'Picked winner. %.2f,%.2f' % (data['sum'],data['result']))
                return HttpResponse(json.dumps({'success': results}, ensure_ascii=False),content_type='application/json;charset=utf-8')
            else:
                return HttpResponse(json.dumps(data),status=400,content_type='application/json;charset=utf-8')
Esempio n. 10
0
def search(request):
    authorizedUser = request.user.has_perm('tracker.can_search')
    #  return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
    try:
        searchParams = viewutil.request_params(request)
        searchtype = searchParams['type']
        qs = filters.run_model_query(searchtype, searchParams, user=request.user, mode='admin' if authorizedUser else 'user')
        if searchtype in related:
            qs = qs.select_related(*related[searchtype])
        if searchtype in defer:
            qs = qs.defer(*defer[searchtype])
        qs = qs.annotate(**viewutil.ModelAnnotations.get(searchtype,{}))
        if qs.count() > 1000:
            qs = qs[:1000]
        jsonData = json.loads(serializers.serialize('json', qs, ensure_ascii=False))
        objs = dict(map(lambda o: (o.id,o), qs))
        for o in jsonData:
            baseObj = objs[int(o['pk'])]
            if isinstance(baseObj, Donor):
                o['fields']['public'] = baseObj.visible_name()
            else:
                o['fields']['public'] = unicode(baseObj)
            for a in viewutil.ModelAnnotations.get(searchtype,{}):
                o['fields'][a] = unicode(getattr(objs[int(o['pk'])],a))
            for r in related.get(searchtype,[]):
                ro = objs[int(o['pk'])]
                for f in r.split('__'):
                    if not ro: break
                    ro = getattr(ro,f)
                if not ro: continue
                relatedData = json.loads(serializers.serialize('json', [ro], ensure_ascii=False))[0]
                for f in ro.__dict__:
                    if f[0] == '_' or f.endswith('id') or f in defer.get(searchtype,[]): continue
                    v = relatedData["fields"][f]
                    o['fields'][r + '__' + f] = relatedData["fields"][f]
                if isinstance(ro, Donor):
                    o['fields'][r + '__public'] = ro.visible_name()
                else:
                    o['fields'][r + '__public'] = unicode(ro)
            if not authorizedUser:
                donor_privacy_filter(searchtype, o['fields'])
                donation_privacy_filter(searchtype, o['fields'])
                prize_privacy_filter(searchtype, o['fields'])
        resp = HttpResponse(json.dumps(jsonData,ensure_ascii=False),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except KeyError, e:
        return HttpResponse(json.dumps({'error': 'Key Error, malformed search parameters'}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
Esempio n. 11
0
def edit(request):
    try:
        editParams = viewutil.request_params(request)
        edittype = editParams['type']
        if not request.user.has_perm('tracker.change_' + permmap.get(edittype,edittype)):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
        Model = modelmap[edittype]
        obj = Model.objects.get(pk=editParams['id'])
        changed = []
        for k,v in editParams.items():
            if k in ('type','id'):
                continue
            v = parse_value(k, v)
            if unicode(getattr(obj, k)) != unicode(v):
                changed.append(k)
            setattr(obj,k, v)
        obj.full_clean()
        models = obj.save() or [obj]
        if changed:
            logutil.change(request,obj,u'Changed field%s %s.' % (len(changed) > 1 and 's' or '', ', '.join(changed)))
        resp = HttpResponse(serializers.serialize('json', models, ensure_ascii=False),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except IntegrityError as e:
        return HttpResponse(json.dumps({'error': u'Integrity error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ValidationError as e:
        d = {'error': u'Validation Error'}
        if hasattr(e,'message_dict') and e.message_dict:
            d['fields'] = e.message_dict
        if hasattr(e,'messages') and e.messages:
            d['messages'] = e.messages
        return HttpResponse(json.dumps(d, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except AttributeError as e:
        return HttpResponse(json.dumps({'error': 'Attribute Error, malformed edit parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except KeyError as e:
        return HttpResponse(json.dumps({'error': 'Key Error, malformed edit parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except FieldError as e:
        return HttpResponse(json.dumps({'error': 'Field Error, malformed edit parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ValueError as e:
        return HttpResponse(json.dumps({'error': u'Value Error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ObjectDoesNotExist as e:
        return HttpResponse(json.dumps({'error': 'Foreign Key could not be found', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
Esempio n. 12
0
def edit(request):
    try:
        editParams = viewutil.request_params(request)
        edittype = editParams['type']
        if not request.user.has_perm('tracker.change_' + permmap.get(edittype,edittype)):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
        Model = modelmap[edittype]
        obj = Model.objects.get(pk=editParams['id'])
        changed = []
        for k,v in editParams.items():
            if k in ('type','id'):
                continue
            v = parse_value(k, v)
            if unicode(getattr(obj, k)) != unicode(v):
                changed.append(k)
            setattr(obj,k, v)
        obj.full_clean()
        models = obj.save() or [obj]
        if changed:
            logutil.change(request,obj,u'Changed field%s %s.' % (len(changed) > 1 and 's' or '', ', '.join(changed)))
        resp = HttpResponse(serializers.serialize('json', models, ensure_ascii=False),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except IntegrityError as e:
        return HttpResponse(json.dumps({'error': u'Integrity error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ValidationError as e:
        d = {'error': u'Validation Error'}
        if hasattr(e,'message_dict') and e.message_dict:
            d['fields'] = e.message_dict
        if hasattr(e,'messages') and e.messages:
            d['messages'] = e.messages
        return HttpResponse(json.dumps(d, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except AttributeError as e:
        return HttpResponse(json.dumps({'error': 'Attribute Error, malformed edit parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except KeyError as e:
        return HttpResponse(json.dumps({'error': 'Key Error, malformed edit parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except FieldError as e:
        return HttpResponse(json.dumps({'error': 'Field Error, malformed edit parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ValueError as e:
        return HttpResponse(json.dumps({'error': u'Value Error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ObjectDoesNotExist as e:
        return HttpResponse(json.dumps({'error': 'Foreign Key could not be found', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
Esempio n. 13
0
def add(request):
    try:
        addParams = viewutil.request_params(request)
        addtype = addParams['type']
        if not request.user.has_perm('tracker.add_' + permmap.get(addtype,addtype)):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
        Model = modelmap[addtype]
        newobj = Model()
        for k,v in addParams.items():
            if k in ('type','id'):
                continue
            setattr(newobj, k, parse_value(k, v))
        newobj.full_clean()
        models = newobj.save() or [newobj]
        logutil.addition(request, newobj)
        resp = HttpResponse(serializers.serialize('json', models, ensure_ascii=False),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except IntegrityError as e:
        return HttpResponse(json.dumps({'error': u'Integrity error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ValidationError as e:
        d = {'error': u'Validation Error'}
        if hasattr(e,'message_dict') and e.message_dict:
            d['fields'] = e.message_dict
        if hasattr(e,'messages') and e.messages:
            d['messages'] = e.messages
        return HttpResponse(json.dumps(d, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except AttributeError as e:
        return HttpResponse(json.dumps({'error': 'Attribute Error, malformed add parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except KeyError as e:
        return HttpResponse(json.dumps({'error': 'Key Error, malformed add parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except FieldError as e:
        return HttpResponse(json.dumps({'error': 'Field Error, malformed add parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ValueError as e:
        return HttpResponse(json.dumps({'error': u'Value Error', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ObjectDoesNotExist as e:
        return HttpResponse(json.dumps({'error': 'Foreign Key could not be found', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
Esempio n. 14
0
def add(request):
    try:
        addParams = viewutil.request_params(request)
        addtype = addParams['type']
        if not request.user.has_perm('tracker.add_' + permmap.get(addtype,addtype)):
            return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
        Model = modelmap[addtype]
        newobj = Model()
        for k,v in addParams.items():
            if k in ('type','id'):
                continue
            setattr(newobj, k, parse_value(k, v))
        newobj.full_clean()
        models = newobj.save() or [newobj]
        logutil.addition(request, newobj)
        resp = HttpResponse(serializers.serialize('json', models, ensure_ascii=False),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except IntegrityError as e:
        return HttpResponse(json.dumps({'error': u'Integrity error: %s' % e}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ValidationError as e:
        d = {'error': u'Validation Error'}
        if hasattr(e,'message_dict') and e.message_dict:
            d['fields'] = e.message_dict
        if hasattr(e,'messages') and e.messages:
            d['messages'] = e.messages
        return HttpResponse(json.dumps(d, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except AttributeError as e:
        return HttpResponse(json.dumps({'error': 'Attribute Error, malformed add parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except KeyError as e:
        return HttpResponse(json.dumps({'error': 'Key Error, malformed add parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except FieldError as e:
        return HttpResponse(json.dumps({'error': 'Field Error, malformed add parameters', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ValueError as e:
        return HttpResponse(json.dumps({'error': u'Value Error', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
    except ObjectDoesNotExist as e:
        return HttpResponse(json.dumps({'error': 'Foreign Key could not be found', 'exception': unicode(e)}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')