# Create your views here. from django.core import serializers from django.http import HttpResponse from django.forms.models import modelformset_factory, inlineformset_factory from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from running.models import Result, User import json def user_index(request, user_name): user = get_object_or_404(User, name=user_name) ResultFormSet = modelformset_factory(Result, fields=('date', 'distance', 'time'), exclude=('user'), extra=3, can_delete=True) if request.method == 'POST': formset = ResultFormSet(request.POST, request.FILES) if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: instance.user = user instance.save() result_list = Result.objects.filter(user=user) formset = ResultFormSet(queryset=result_list) return render_to_response('user_index.html', { 'user' : user, 'formset' : formset }, context_instance=RequestContext(request)) def index(request): user_list = User.objects.all() return render_to_response('index.html', { 'user_list' : user_list }) def zoom(request): result_list = Result.objects.values_list('date', 'distance') json_list = [] # Output date object in epoch milliseconds as JavaScript find this easy to use. for (date,distance) in result_list: json_list.append({'x': int(date.strftime("%s")) * 1000, 'y' : float(distance)}) data = json.dumps(json_list, ensure_ascii=False, indent=2) return HttpResponse(data,mimetype="application/json") def json_user_column(request,user_id): user = get_object_or_404(User, pk=user_id) result_list = Result.objects.filter(user=user).values_list('date', 'distance') total_list = {} for (date,distance) in result_list: key = date.strftime("%Y-%m") if total_list.has_key(key): total_list[key] += distance else: total_list[key] = distance json_object = { 'label' : [] , 'data' : [] } for (date,distance) in total_list.iteritems(): json_object['label'].append(date) json_object['data'].append(float(distance)) data = json.dumps(json_object, ensure_ascii=False, indent=2) return HttpResponse(data,mimetype="application/json") def json_user_total(request,user_id): result_list = Result.objects.values_list('date', 'distance') json_list = [] distance_total = 0.0 # Output date object in epoch milliseconds as JavaScript find this easy to use. for (date,distance) in result_list: distance_total += float(distance) json_list.append({'x': int(date.strftime("%s")) * 1000, 'y' : distance_total}) data = json.dumps(json_list, ensure_ascii=False, indent=2) return HttpResponse(data,mimetype="application/json")