bia-fitness/lifting/views.py

76 lines
2.3 KiB
Python
Raw Normal View History

2015-04-03 20:46:59 +00:00
import datetime
import os
2015-04-02 21:58:26 +00:00
import tempfile
2015-04-03 20:46:59 +00:00
import calendar
from collections import defaultdict
2015-04-02 21:58:26 +00:00
2015-03-31 21:25:19 +00:00
from django.shortcuts import render
2015-04-01 22:19:20 +00:00
from django import forms
2015-04-02 21:58:26 +00:00
from django.contrib.auth.decorators import login_required
2015-04-03 20:46:59 +00:00
from django.views.generic import dates
2015-04-02 21:58:26 +00:00
from . import importers
2015-04-03 20:46:59 +00:00
from .models import Set
@login_required
def month(request, year, month):
year, month = int(year), int(month)
2015-04-03 21:09:38 +00:00
sets_by_day = defaultdict(set)
2015-04-03 20:46:59 +00:00
for workset in Set.objects.filter(user=request.user, date__year=year, date__month=month):
2015-04-03 21:09:38 +00:00
sets_by_day[workset.date.day].add(workset.exercise)
2015-04-03 20:46:59 +00:00
date = datetime.date(year, month, 1)
first_day, max_days = calendar.monthrange(year, month)
# make first_day use 0 for sunday
first_day = (first_day + 1) % 7
# start calendar with a few blank days
days = [None]*first_day
2015-04-03 21:19:11 +00:00
for day in range(1, max_days+1):
2015-04-03 20:46:59 +00:00
days.append({'number': day, 'sets': sets_by_day[day]})
2015-04-03 21:19:11 +00:00
days_by_week = [days[0:7], days[7:14], days[14:21], days[21:28], days[28:35], days[35:42]]
2015-04-03 20:46:59 +00:00
2015-04-06 15:43:36 +00:00
# prev and next month
if date.month == 1:
prev_date = datetime.date(year-1, 12, 1)
next_date = datetime.date(year, 2, 1)
elif date.month == 12:
prev_date = datetime.date(year, 11, 1)
next_date = datetime.date(year+1, 1, 1)
else:
prev_date = datetime.date(year, month-1, 1)
next_date = datetime.date(year, month+1, 1)
return render(request, 'month.html', {'date': date,
'days': days_by_week,
'prev_date': prev_date,
'next_date': next_date,
2015-04-03 20:46:59 +00:00
})
2015-03-31 21:25:19 +00:00
2015-04-01 22:19:20 +00:00
class FitnotesUploadForm(forms.Form):
file = forms.FileField()
2015-04-02 21:58:26 +00:00
@login_required
2015-04-01 22:19:20 +00:00
def fitnotes_upload(request):
if request.method == 'POST':
form = FitnotesUploadForm(request.POST, request.FILES)
if form.is_valid():
2015-04-02 21:58:26 +00:00
_, fname = tempfile.mkstemp()
with open(fname, 'wb') as tmp:
for chunk in request.FILES['file'].chunks():
tmp.write(chunk)
try:
importers.import_fitnotes_db(fname, request.user)
finally:
os.remove(fname)
2015-04-01 22:19:20 +00:00
else:
form = FitnotesUploadForm()
return render(request, 'upload.html', {'form': form})