Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Move WorkoutCalendar from views to helper file

Roland Geidere41983a9fd07
diff --git a/wger/manager/helpers.py b/wger/manager/helpers.py
index a8836c8b8..cd11c0d15 100644
--- a/wger/manager/helpers.py
+++ b/wger/manager/helpers.py
@@ -15,12 +15,16 @@
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
+import datetime
+from calendar import HTMLCalendar
+
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.platypus import Paragraph
from reportlab.platypus import Table
from reportlab.platypus import KeepTogether
+from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from wger.utils.pdf import styleSheet
@@ -148,3 +152,84 @@ def reps_smart_text(settings, set_obj):
setting_list = tmp_reps
return setting_text, setting_list
+
+
+class WorkoutCalendar(HTMLCalendar):
+ '''
+ A calendar renderer, see this blog entry for details:
+ * http://uggedal.com/journal/creating-a-flexible-monthly-calendar-in-django/
+ '''
+ def __init__(self, workout_logs, *args, **kwargs):
+ super(WorkoutCalendar, self).__init__(*args, **kwargs)
+ self.workout_logs = workout_logs
+
+ def formatday(self, day, weekday):
+
+ # days belonging to last or next month are rendered empty
+ if day == 0:
+ return self.day_cell('noday', '&nbsp;')
+
+ date_obj = datetime.date(self.year, self.month, day)
+ cssclass = self.cssclasses[weekday]
+ if datetime.date.today() == date_obj:
+ cssclass += ' today'
+
+ # There are no logs for this day, doesn't need special attention
+ if date_obj not in self.workout_logs:
+ return self.day_cell(cssclass, day)
+
+ # Day with a log, set background and link
+ entry = self.workout_logs.get(date_obj)
+
+ # Note: due to circular imports we use can't import the workout session
+ # model to access the impression values directly, so they are hard coded
+ # here.
+ if entry['session']:
+ # Bad
+ if entry['session'].impression == '1':
+ background_css = 'btn-danger'
+ # Good
+ elif entry['session'].impression == '3':
+ background_css = 'btn-success'
+ # Neutral
+ else:
+ background_css = 'btn-warning'
+
+ else:
+ background_css = 'btn-warning'
+
+ url = reverse('manager:log:log', kwargs={'pk': entry['workout'].id})
+ formatted_date = date_obj.strftime('%Y-%m-%d')
+ body = []
+ body.append('<a href="{0}" '
+ 'data-log="log-{1}" '
+ 'class="btn btn-block {2} calendar-link">'.format(url,
+ formatted_date,
+ background_css))
+ body.append(repr(day))
+ body.append('</a>')
+ return self.day_cell(cssclass, '{0}'.format(''.join(body)))
+
+ def formatmonth(self, year, month):
+ '''
+ Format the table header. This is basically the same code from python's
+ calendar module but with additional bootstrap classes
+ '''
+ self.year, self.month = year, month
+ out = []
+ out.append('<table class="month table table-bordered">\n')
+ out.append(self.formatmonthname(year, month))
+ out.append('\n')
+ out.append(self.formatweekheader())
+ out.append('\n')
+ for week in self.monthdays2calendar(year, month):
+ out.append(self.formatweek(week))
+ out.append('\n')
+ out.append('</table>\n')
+ return ''.join(out)
+
+ def day_cell(self, cssclass, body):
+ '''
+ Renders a day cell
+ '''
+ return '<td class="{0}" style="vertical-align: middle;">{1}</td>'.format(cssclass, body)
diff --git a/wger/manager/models.py b/wger/manager/models.py
index 45c1c25f3..3b3e1be84 100644
--- a/wger/manager/models.py
+++ b/wger/manager/models.py
@@ -677,6 +677,7 @@ class WorkoutSession(models.Model):
Model for a workout session
'''
+ # Note: values hardcoded in manager.helpers.WorkoutCalendar
IMPRESSION_BAD = '1'
IMPRESSION_NEUTRAL = '2'
IMPRESSION_GOOD = '3'
diff --git a/wger/manager/views/log.py b/wger/manager/views/log.py
index b6e616658..23075b2b0 100644
--- a/wger/manager/views/log.py
+++ b/wger/manager/views/log.py
@@ -17,13 +17,11 @@
import logging
import uuid
import datetime
-from calendar import HTMLCalendar
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.http import HttpResponseForbidden
-from django.core.cache import cache
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
@@ -36,6 +34,7 @@ from django.views.generic import CreateView
from django.views.generic import DetailView
from django.views.generic import DeleteView
+from wger.manager.helpers import WorkoutCalendar
from wger.manager.models import Workout
from wger.manager.models import WorkoutSession
from wger.manager.models import Day
@@ -44,13 +43,13 @@ from wger.manager.models import Schedule
from wger.manager.forms import HelperDateForm
from wger.manager.forms import HelperWorkoutSessionForm
from wger.manager.forms import WorkoutLogForm
-from wger.utils.cache import cache_mapper
from wger.utils.generic_views import WgerFormMixin
from wger.utils.generic_views import WgerDeleteMixin
from wger.utils.generic_views import WgerPermissionMixin
from wger.utils.helpers import check_access, make_token
from wger.weight.helpers import process_log_entries, group_log_entries
+
logger = logging.getLogger(__name__)
@@ -316,79 +315,6 @@ class WorkoutLogDetailView(DetailView, WgerPermissionMixin):
return super(WorkoutLogDetailView, self).dispatch(request, *args, **kwargs)
-class WorkoutCalendar(HTMLCalendar):
- '''
- A calendar renderer, see this blog entry for details:
- * http://uggedal.com/journal/creating-a-flexible-monthly-calendar-in-django/
- '''
- def __init__(self, workout_logs, *args, **kwargs):
- super(WorkoutCalendar, self).__init__(*args, **kwargs)
- self.workout_logs = workout_logs
-
- def formatday(self, day, weekday):
-
- # days belonging to last or next month are rendered empty
- if day == 0:
- return self.day_cell('noday', '&nbsp;')
-
- date_obj = datetime.date(self.year, self.month, day)
- cssclass = self.cssclasses[weekday]
- if datetime.date.today() == date_obj:
- cssclass += ' today'
-
- # There are no logs for this day, doesn't need special attention
- if date_obj not in self.workout_logs:
- return self.day_cell(cssclass, day)
-
- # Day with a log, set background and link
- entry = self.workout_logs.get(date_obj)
- if entry['session']:
- if entry['session'].impression == WorkoutSession.IMPRESSION_BAD:
- background_css = 'btn-danger'
- elif entry['session'].impression == WorkoutSession.IMPRESSION_GOOD:
- background_css = 'btn-success'
- else:
- background_css = 'btn-warning'
- else:
- background_css = 'btn-warning'
-
- url = reverse('manager:log:log', kwargs={'pk': entry['workout'].id})
- formatted_date = date_obj.strftime('%Y-%m-%d')
- body = []
- body.append('<a href="{0}" '
- 'data-log="log-{1}" '
- 'class="btn btn-block {2} calendar-link">'.format(url,
- formatted_date,
- background_css))
- body.append(repr(day))
- body.append('</a>')
- return self.day_cell(cssclass, '{0}'.format(''.join(body)))
-
- def formatmonth(self, year, month):
- '''
- Format the table header. This is basically the same code from python's
- calendar module but with additional bootstrap classes
- '''
- self.year, self.month = year, month
- out = []
- out.append('<table class="month table table-bordered">\n')
- out.append(self.formatmonthname(year, month))
- out.append('\n')
- out.append(self.formatweekheader())
- out.append('\n')
- for week in self.monthdays2calendar(year, month):
- out.append(self.formatweek(week))
- out.append('\n')
- out.append('</table>\n')
- return ''.join(out)
-
- def day_cell(self, cssclass, body):
- '''
- Renders a day cell
- '''
- return '<td class="{0}" style="vertical-align: middle;">{1}</td>'.format(cssclass, body)
-
-
def calendar(request, username=None, year=None, month=None):
'''
Show a calendar with all the workout logs