Self hosted FLOSS fitness/workout, nutrition and weight tracker
Use the canonical representation to render workouts
Roland Geidera9d313efe9c1
diff --git a/wger/manager/models.py b/wger/manager/models.pyindex 342039054..e536dad15 100644--- a/wger/manager/models.py+++ b/wger/manager/models.py@@ -50,12 +50,8 @@ logger = logging.getLogger('wger.custom')## Helper functions#-def reset_workout_muscle_bg_cache(workout_id):- cache.delete(cache_mapper.get_workout_muscle_bg(workout_id))---def reset_day_template_cache(day_id):- delete_template_fragment_cache('day-view', day_id)+def reset_workout_canonical_form(workout_id):+ cache.delete(cache_mapper.get_workout_canonical(workout_id))#@@ -105,20 +101,37 @@ class Workout(models.Model):def canonical_representation(self):'''Returns a canonical representation of the workout++ This form makes it easier to cache and use everywhere where all or part+ of a workout structure is needed. As an additional benefit, the template+ caches are not needed anymore.'''- canonical_repr = []- for day in self.day_set.select_related():- tmp_days_of_week = []- for day_of_week in day.day.select_related():- tmp_days_of_week.append(day_of_week)+ workout_canonical_form = cache.get(cache_mapper.get_workout_canonical(self.pk))+ if not workout_canonical_form:+ day_canonical_repr = []+ muscles_front = []+ muscles_back = []+ for day in self.day_set.select_related():+ canonical_repr_day = day.get_canonical_representation()++ # Collect all muscles+ for i in canonical_repr_day['muscles']['front']:+ if i not in muscles_front:+ muscles_front.append(i)+ for i in canonical_repr_day['muscles']['back']:+ if i not in muscles_back:+ muscles_back.append(i)- canonical_repr.append({'obj': day,- 'days_of_week': {- 'text': u', '.join([unicode(_(i.day_of_week))- for i in tmp_days_of_week]),- 'day_list': tmp_days_of_week},- 'set_list': day.canonical_representation})- return canonical_repr+ day_canonical_repr.append(canonical_repr_day)++ workout_canonical_form = {'obj': self,+ 'muscles': {'front': muscles_front, 'back': muscles_back},+ 'day_list': day_canonical_repr}++ # Save to cache+ cache.set(cache_mapper.get_workout_canonical(self.pk), workout_canonical_form)++ return workout_canonical_formclass ScheduleManager(models.Manager):@@ -375,7 +388,7 @@ class Day(models.Model):Reset all cached infos'''- reset_day_template_cache(self.pk)+ reset_workout_canonical_form(self.training_id)super(Day, self).save(*args, **kwargs)def delete(self, *args, **kwargs):@@ -383,24 +396,48 @@ class Day(models.Model):Reset all cached infos'''- reset_day_template_cache(self.pk)+ reset_workout_canonical_form(self.training_id)super(Day, self).delete(*args, **kwargs)@propertydef canonical_representation(self):'''- Returns a canonical representation of the day+ Return the canonical representation for this day++ This is extracted from the workout representation because that one is cached+ and this isn't.+ '''+ for i in self.training.canonical_representation['day_list']:+ if int(i['obj'].pk) == int(self.pk):+ return i++ def get_canonical_representation(self):+ '''+ Creates a canonical representation for this day'''canonical_repr = []+ muscles_front = []+ muscles_back = []for set_obj in self.set_set.select_related():exercise_tmp = []for exercise in set_obj.exercises.select_related():setting_tmp = []++ # Muscles for this set+ for muscle in exercise.muscles.all():+ if muscle.is_front and muscle.id not in muscles_front:+ muscles_front.append(muscle.id)+ elif not muscle.is_front and muscle.id not in muscles_back:+ muscles_back.append(muscle.id)+for setting in Setting.objects.filter(set=set_obj,exercise=exercise).order_by('order'):setting_tmp.append(setting)+ # "Smart" textual representation+ # This is a human representation of the settings, in a way that humans+ # would also write: e.g. "8 8 10 10" but "4 x 10" and not "10 10 10 10"if len(setting_tmp) > 1:tmp_reps_text = []tmp_reps = []@@ -415,20 +452,41 @@ class Day(models.Model):reps = setting_tmp[0].reps if setting_tmp[0].reps != 99 else '∞'setting_text = u'{0} × {1}'.format(set_obj.sets, reps)setting_list = [reps] * set_obj.sets++ # Exercise comments+ comment_list = []+ for i in exercise.exercisecomment_set.all():+ comment_list.append(i.comment)+exercise_tmp.append({'obj': exercise,'setting_obj_list': setting_tmp,'setting_list': setting_list,- 'setting_text': setting_text})+ 'setting_text': setting_text,+ 'comment_list': comment_list})- if len(exercise_tmp) > 1:- is_superset = True- else:- is_superset = Falsecanonical_repr.append({'obj': set_obj,'exercise_list': exercise_tmp,- 'is_superset': is_superset})-- return canonical_repr+ 'is_superset': True if len(exercise_tmp) > 1 else False,+ 'muscles': {+ 'back': muscles_back,+ 'front': muscles_front+ }})++ # Days of the week+ tmp_days_of_week = []+ for day_of_week in self.day.select_related():+ tmp_days_of_week.append(day_of_week)++ return {'obj': self,+ 'days_of_week': {+ 'text': u', '.join([unicode(_(i.day_of_week))+ for i in tmp_days_of_week]),+ 'day_list': tmp_days_of_week},+ 'muscles': {+ 'back': muscles_back,+ 'front': muscles_front+ },+ 'set_list': canonical_repr}class Set(models.Model):@@ -472,8 +530,7 @@ class Set(models.Model):Reset all cached infos'''- reset_workout_muscle_bg_cache(self.exerciseday.training_id)- reset_day_template_cache(self.exerciseday_id)+ reset_workout_canonical_form(self.exerciseday.training_id)super(Set, self).save(*args, **kwargs)def delete(self, *args, **kwargs):@@ -481,8 +538,7 @@ class Set(models.Model):Reset all cached infos'''- reset_workout_muscle_bg_cache(self.exerciseday.training_id)- reset_day_template_cache(self.exerciseday_id)+ reset_workout_canonical_form(self.exerciseday.training_id)super(Set, self).delete(*args, **kwargs)@@ -512,7 +568,7 @@ class Setting(models.Model):Reset all cached infos'''- reset_day_template_cache(self.set.exerciseday_id)+ reset_workout_canonical_form(self.set.exerciseday.training_id)super(Setting, self).save(*args, **kwargs)def delete(self, *args, **kwargs):@@ -520,7 +576,7 @@ class Setting(models.Model):Reset all cached infos'''- reset_day_template_cache(self.set.exerciseday_id)+ reset_workout_canonical_form(self.set.exerciseday.training_id)super(Setting, self).delete(*args, **kwargs)def get_owner_object(self):diff --git a/wger/manager/templates/mobile/index.html b/wger/manager/templates/mobile/index.htmlindex 1091801c2..a52f359e3 100644--- a/wger/manager/templates/mobile/index.html+++ b/wger/manager/templates/mobile/index.html@@ -108,7 +108,7 @@ pauses you do.{% endblocktrans %}</div><ul data-role="listview" data-inset="true" style="margin-bottom:1em;">{% if current_workout %}- {% for day in current_workout.canonical_representation %}+ {% for day in current_workout.canonical_representation.day_list %}<li>{% if day.set_list|length > 0 %}<a href="{% url 'workout-timer' day.obj.pk %}" data-ajax="false">{% endif %}{{day.obj.description}}diff --git a/wger/manager/templates/mobile/tags/render_day.html b/wger/manager/templates/mobile/tags/render_day.htmlindex 7bb52d609..259db5d16 100644--- a/wger/manager/templates/mobile/tags/render_day.html+++ b/wger/manager/templates/mobile/tags/render_day.html@@ -5,14 +5,14 @@<div data-role="popup"- id="editoptions-day-{{ day.id }}"+ id="editoptions-day-{{ day.obj.id }}"data-theme="d"data-overlay-theme="a"><div data-role="header" data-theme="b">- <h3>{{day.description}}</h3>+ <h3>{{day.obj.description}}</h3></div><div role="main" class="ui-content">- <a href="{% url 'day-log' day.id %}"+ <a href="{% url 'day-log' day.obj.id %}"title="{% trans 'Add weight log to this day' %}"data-role="button"><img src="{% static 'images/icons/statistics.svg' %}"@@ -21,8 +21,8 @@alt="{% trans 'Add weight log to this day' %}">{% trans 'Add weight log to this day' %}</a>- {% if day.set_set.select_related|length > 0 %}- <a href="{% url 'workout-timer' day.id %}"+ {% if day.set_list|length > 0 %}+ <a href="{% url 'workout-timer' day.obj.id %}"title="{% trans 'Start gym mode' %}"data-role="button"data-ajax="false">@@ -33,7 +33,7 @@{% trans "Start gym mode" %}</a>{% endif %}- <a href="{% url 'day-edit' day.id %}"+ <a href="{% url 'day-edit' day.obj.id %}"title="{% trans 'Edit' %}"data-role="button"><img src="{% static 'images/icons/edit.svg' %}"@@ -42,7 +42,7 @@alt="{% trans 'Edit' %}">{% trans 'Edit' %}</a>- <a href="{% url 'wger.manager.views.day.delete' workout.id day.id %}"+ <a href="{% url 'wger.manager.views.day.delete' workout.id day.obj.id %}"title="{% trans 'Delete' %}"data-role="button"><img src="{% static 'images/icons/trash.svg' %}"@@ -55,15 +55,15 @@</div>-{% for set in day.set_set.select_related %}+{% for set in day.set_list %}<div data-role="popup"- id="editoptions-set-{{ set.id }}"+ id="editoptions-set-{{ set.obj.id }}"data-overlay-theme="a"><div data-role="header" data-theme="b"><h3>{% trans "Options" %}</h3></div><div role="main" class="ui-content">- <a href="{% url 'wger.manager.views.set.edit' set.id %}"+ <a href="{% url 'wger.manager.views.set.edit' set.obj.id %}"title="{% trans 'Delete' %}"data-role="button"><img src="{% static 'images/icons/edit.svg' %}"@@ -73,7 +73,7 @@class="ui-li-icon ui-corner-none">{% trans "Edit" %}</a>- <a href="{% url 'wger.manager.views.set.delete' set.id %}"+ <a href="{% url 'wger.manager.views.set.delete' set.obj.id %}"title="{% trans 'Delete' %}"data-role="button"><img src="{% static 'images/icons/trash.svg' %}"@@ -85,11 +85,11 @@</a><h5>{% trans "Exercises" %}</h5>- {% for exercise in set.exercises.select_related %}- <a href="{{ exercise.get_absolute_url }}"- title="{{ exercise.name }}"+ {% for exercise in set.exercise_list %}+ <a href="{{ exercise.obj.get_absolute_url }}"+ title="{{ exercise.obj.name }}"data-role="button">- {{ exercise.name }}+ {{ exercise.obj.name }}</a>{% endfor %}</div>@@ -102,77 +102,46 @@data-split-icon="grid"data-split-theme="b"><li data-theme="b">- <a href="#editoptions-day-{{ day.id }}" data-rel="popup">- <h4>{{day.description}}</h4>- {% for day_of_week in day.day.select_related %}- {% trans day_of_week.day_of_week %}- {% if not forloop.last %}, {% endif %}- {% endfor %}+ <a href="#editoptions-day-{{ day.obj.id }}" data-rel="popup">+ <h4>{{ day.obj.description }}</h4>+ {{ day.days_of_week.text }}</a>-- <a href="{% url 'day-log' day.id %}"></a>+ <a href="{% url 'day-log' day.obj.id %}"></a></li>-- {% for set in day.set_set.select_related %}- <li id="set-{{ set.id }}" data-icon="false">- <a href="#editoptions-set-{{ set.id }}"+ {% for set in day.set_list %}+ <li id="set-{{ set.obj.id }}" data-icon="false">+ <a href="#editoptions-set-{{ set.obj.id }}"data-rel="popup"data-position-to="window">- {% for exercise in set.exercises.select_related %}- <div id="exercise-{{ exercise.id }}" class="ajax-set-edit-target">- <h3>{{ exercise.name }}</h3>+ {% for exercise in set.exercise_list %}+ <div id="exercise-{{ exercise.obj.id }}" class="ajax-set-edit-target">+ <h3>{{ exercise.obj.name }}</h3><p><strong>- {% comment %}- If there are more than 1 settings, don't output the repetitions- e.g. "4 x 8 8 10 10" is shown only as "8 8 10 10", after all- those 4 sets are not done four times! But "3 x 12" is stil shown- like that.- {% endcomment %}- {% if exercise|get_current_settings:set.id|length == 1 %}- {{ set.sets }} ×- {% endif %}-- {% comment %}- get_current_settings only does a exercise.setting_set.filter(set_id=set_id)- {% endcomment %}-- <span class="settings-list">- {% for setting in exercise|get_current_settings:set.id %}- <span id="setting-{{setting.id}}">- {% if setting.reps == 99 %}- ∞- {%else%}- {{setting.reps}}- {%endif%}- {% if not forloop.last %} – {% endif %}- </span>- {% empty %}- <a href="{% url 'set-edit' set.id %}"+ {{exercise.setting_text}}+ </strong></p>+ {% if not exercise.setting_list %}+ <a href="{% url 'set-edit' set.obj.id %}"data-role="button">{% trans "This exercise has no repetitions." %}{% trans "Edit them now."%}</a>- {% endfor %} <!--for setting in exercise-->- </span>- </strong></p>+ {% endif %}<p class="exercise-comments">- {% for comment in exercise.exercisecomment_set.all %}+ {% for comment in exercise.comment_list %}{{comment}}<br>{% endfor %}</p>--</div>{% endfor %} <!--for exercise in set--></a></li>{% empty %}<li>- <a href="{% url 'set-add' day.id %}"+ <a href="{% url 'set-add' day.obj.id %}"data-ajax="false">{% trans "No exercises selected for this day." %}<br>{% trans "Add one now." %}@@ -180,9 +149,9 @@</li>{% endfor %} <!--for set in day-->- {% if day.set_set.select_related %}+ {% if day.set_list %}<li data-icon="arrow-r">- <a href="{% url 'set-add' day.id %}"+ <a href="{% url 'set-add' day.obj.id %}"data-ajax="false">{% trans "Add exercises to this workout day" %}</a></li>diff --git a/wger/manager/templates/mobile/workout/view.html b/wger/manager/templates/mobile/workout/view.htmlindex 6c82e7aa0..5da45fb46 100644--- a/wger/manager/templates/mobile/workout/view.html+++ b/wger/manager/templates/mobile/workout/view.html@@ -45,9 +45,9 @@ $( document ).off("pageinit").on("pageinit", function() {</p>{% endif %}-{% for day in workout.day_set.select_related %}- <div id="div-day-{{ day.id }}">- {% render_day day %}+{% for day in workout.canonical_representation.day_list %}+ <div id="div-day-{{ day.obj.id }}">+ {% render_day day.obj %}</div>{% empty %}diff --git a/wger/manager/templates/tags/render_day.html b/wger/manager/templates/tags/render_day.htmlindex 3e01f84a4..d9f3a0f91 100644--- a/wger/manager/templates/tags/render_day.html+++ b/wger/manager/templates/tags/render_day.html@@ -16,21 +16,22 @@ $(document).ready(function() {})</script>-<table class="bordertable workout-table" id="table-day-{{ day.id }}">+<table class="bordertable workout-table" id="table-day-{{ day.obj.id }}"><thead>- <tr id="day-{{ day.id }}">+ <tr id="day-{{ day.obj.id }}"><th colspan="2">- {{ day.day.select_related|join:", " }} – {{ day.description }}++ {{ day.days_of_week.text }} – {{ day.obj.description }}<span class="editoptions" style="float: right;">- <a href="{% url 'wger.manager.views.day.delete' workout.id day.id %}"+ <a href="{% url 'wger.manager.views.day.delete' workout.id day.obj.id %}"title="{% trans 'Delete' %}"><img src="{% static 'images/icons/trash.svg' %}"width="22"height="22"alt="{% trans 'Delete' %}"></a>- <a href="{% url 'day-edit' day.id %}"+ <a href="{% url 'day-edit' day.obj.id %}"title="{% trans 'Edit' %}"class="modal-dialog"><img src="{% static 'images/icons/edit.svg' %}"@@ -38,7 +39,7 @@ $(document).ready(function() {height="22"alt="{% trans 'Edit' %}"></a>- <a href="{% url 'day-log' day.id %}"+ <a href="{% url 'day-log' day.obj.id %}"title="{% trans 'Add weight log to this day' %}"><img src="{% static 'images/icons/statistics.svg' %}"width="22"@@ -50,8 +51,8 @@ $(document).ready(function() {</tr></thead><tbody>- {% for set in day.set_set.select_related %}- <tr id="set-{{ set.id }}">+ {% for set in day.set_list %}+ <tr id="set-{{ set.obj.id }}"><td class="ym-g10">{{ forloop.counter }}<span class="editoptions"><img src="{% static 'images/icons/move.svg' %}"@@ -61,7 +62,7 @@ $(document).ready(function() {title="{% trans 'Move me' %}"class="dragndrop-handle"><br>- <a href="{% url 'set-edit' set.id %}"+ <a href="{% url 'set-edit' set.obj.id %}"title="{% trans 'Edit' %}"class="modal-dialog"><img src="{% static 'images/icons/edit.svg' %}"@@ -69,7 +70,7 @@ $(document).ready(function() {height="22"alt="{% trans 'Edit' %}"></a>- <a href="{% url 'wger.manager.views.set.delete' set.id %}"+ <a href="{% url 'wger.manager.views.set.delete' set.obj.id %}"title="{% trans 'Delete' %}"><img src="{% static 'images/icons/trash.svg' %}"width="16"@@ -80,62 +81,35 @@ $(document).ready(function() {</td><td><div class="exercise-list">- {% for exercise in set.exercises.select_related %}- <div id="exercise-{{ exercise.id }}" class="ajax-set-edit-target">- <a href="{{ exercise.get_absolute_url }}">{{ exercise.name }}</a>:-- {% comment %}- If there are more than 1 settings, don't output the repetitions- e.g. "4 x 8 8 10 10" is shown only as "8 8 10 10", after all- those 4 sets are not done four times! But "3 x 12" is stil shown- like that.- {% endcomment %}- {% if exercise|get_current_settings:set.id|length == 1 %}- {{ set.sets }} ×+ {% for exercise in set.exercise_list %}+ <div id="exercise-{{ exercise.obj.id }}" class="ajax-set-edit-target">+ <a href="{{ exercise.obj.get_absolute_url }}">{{ exercise.obj.name }}</a>:++ {{exercise.setting_text}}+ {% if not exercise.setting_text %}+ <a href="{% url 'set-edit' set.obj.id %}"+ class="modal-dialog btn btn-block">+ {% trans "This exercise has no repetitions." %}+ {% trans "Edit them now."%}+ </a>{% endif %}- {% comment %}- get_current_settings only does a exercise.setting_set.filter(set_id=set_id)- {% endcomment %}-<span class="settings-list">- {% for setting in exercise|get_current_settings:set.id %}- <span id="setting-{{setting.id}}">--- {% if setting.reps == 99 %}- ∞- {%else%}- {{setting.reps}}- {%endif%}- {% if not forloop.last %} – {% endif %}- </span>- {% empty %}- <a href="{% url 'set-edit' set.id %}"- class="modal-dialog btn btn-block">- {% trans "This exercise has no repetitions." %}- {% trans "Edit them now."%}- </a>- {% endfor %} <!--for setting in exercise-->- </span><div class="exercise-comments dimmed"><ul>- {% for comment in exercise.exercisecomment_set.all %}+ {% for comment in exercise.comment_list %}<li>{{comment}}</li>{% endfor %}</ul></div>---</div>{% endfor %} <!--for exercise in set--></div>{% empty %}<tr><td colspan="2">- <a href="{% url 'set-add' day.id %}"+ <a href="{% url 'set-add' day.obj.id %}"class="modal-dialog btn btn-block">{% trans "No exercises selected for this day." %}{% trans "Add one now." %}@@ -146,7 +120,7 @@ $(document).ready(function() {</tr><tr><td colspan="2">- <a href="{% url 'set-add' day.id %}"+ <a href="{% url 'set-add' day.obj.id %}"class="modal-dialog">{% trans "Add exercises to this workout day" %}</a></td></tr>diff --git a/wger/manager/templates/workout/timer.html b/wger/manager/templates/workout/timer.htmlindex 604903977..6cd9aea40 100644--- a/wger/manager/templates/workout/timer.html+++ b/wger/manager/templates/workout/timer.html@@ -234,7 +234,7 @@ $(document).ready(function() {<h2>{% trans "Your workout today" %}</h2><div class="filler_div">- {% for set in canonical_day %}+ {% for set in canonical_day.set_list %}{% for exercise in set.exercise_list %}{{exercise.obj}}: {{exercise.setting_text}}<br>{% endfor %}diff --git a/wger/manager/templates/workout/view.html b/wger/manager/templates/workout/view.htmlindex 77273c479..87f1e30ba 100644--- a/wger/manager/templates/workout/view.html+++ b/wger/manager/templates/workout/view.html@@ -3,7 +3,6 @@{% load i18n %}{% load staticfiles %}{% load wger_extras %}-{% load cache %}{% block title %}{% trans "Workout" %} – {{ workout.creation_date }}{% endblock %}@@ -51,12 +50,10 @@ $(document).ready(function() {-{% for day in workout.day_set.select_related|dictsort:"get_first_day_id" %}- {% cache cache_timeout day-view day.id %}+{% for day in workout.canonical_representation.day_list %}<div id="div-day-{{ day.id }}">- {% render_day day %}+ {% render_day day.obj %}</div>- {% endcache %}{% empty %}<p><a href="{% url 'day-add' workout.id %}" class="modal-dialog btn btn-block">diff --git a/wger/manager/templatetags/wger_extras.py b/wger/manager/templatetags/wger_extras.pyindex 2c382ad0c..8507c2c9b 100644--- a/wger/manager/templatetags/wger_extras.py+++ b/wger/manager/templatetags/wger_extras.py@@ -49,7 +49,7 @@ def render_day(day):'''Renders a day as it will be displayed in the workout overview'''- return {'day': day,+ return {'day': day.canonical_representation,'workout': day.training}diff --git a/wger/manager/tests/test_workout_canonical.py b/wger/manager/tests/test_workout_canonical.pyindex 6d3eae882..4e2b28eff 100644--- a/wger/manager/tests/test_workout_canonical.py+++ b/wger/manager/tests/test_workout_canonical.py@@ -36,30 +36,43 @@ class WorkoutCanonicalFormTestCase(WorkoutManagerTestCase):workout = Workout.objects.get(pk=1)setting_1 = Setting.objects.get(pk=1)setting_2 = Setting.objects.get(pk=2)- canonical_form = [{'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=2)],- 'text': u'Tuesday'},+ self.assertEqual(workout.canonical_representation['muscles'], {'back': [2], 'front': [1]})+ self.assertEqual(workout.canonical_representation['obj'], workout)++ canonical_form = {'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=2)],+ 'text': u'Tuesday'},+ 'muscles': {'back': [2], 'front': [1]},'obj': Day.objects.get(pk=1),'set_list': [{'exercise_list': [{'obj': Exercise.objects.get(pk=1),+ 'comment_list': [u'test 123'],'setting_list': [8, 8],'setting_obj_list': [setting_1],'setting_text': u'2 \xd7 8'}],'is_superset': False,- 'obj': Set.objects.get(pk=1)}]},- {'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=4)],- 'text': u'Thursday'},- 'obj': Day.objects.get(pk=2),- 'set_list': [{'exercise_list': [{'obj': Exercise.objects.get(pk=2),+ 'muscles': {'back': [2], 'front': [1]},+ 'obj': Set.objects.get(pk=1)}]}+ self.assertEqual(workout.canonical_representation['day_list'][0], canonical_form)++ canonical_form = {'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=4)],+ 'text': u'Thursday'},+ 'obj': Day.objects.get(pk=2),+ 'muscles': {'back': [2], 'front': []},+ 'set_list': [{'exercise_list': [{'obj': Exercise.objects.get(pk=2),+ 'comment_list': [u'Foobar'],'setting_list': [10, 10, 10, 10],'setting_obj_list': [setting_2],'setting_text': u'4 \xd7 10'}],'is_superset': False,- 'obj': Set.objects.get(pk=2)}]},- {'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=5)],- 'text': u'Friday'},- 'obj': Day.objects.get(pk=4),- 'set_list': []}]+ 'muscles': {'back': [2], 'front': []},+ 'obj': Set.objects.get(pk=2)}]}+ self.assertEqual(workout.canonical_representation['day_list'][1], canonical_form)- self.assertEqual(workout.canonical_representation, canonical_form)+ canonical_form = {'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=5)],+ 'text': u'Friday'},+ 'obj': Day.objects.get(pk=4),+ 'muscles': {'back': [], 'front': []},+ 'set_list': []}+ self.assertEqual(workout.canonical_representation['day_list'][2], canonical_form)def test_canonical_form_day(self):'''@@ -67,11 +80,22 @@ class WorkoutCanonicalFormTestCase(WorkoutManagerTestCase):'''day = Day.objects.get(pk=5)+ weekday1 = DaysOfWeek.objects.get(pk=3)+ weekday2 = DaysOfWeek.objects.get(pk=5)+ #import pprint+ #pprint.pprint(day.canonical_representation)+ self.assertEqual(day.canonical_representation['days_of_week'],+ {'day_list': [weekday1, weekday2], 'text': u'Wednesday, Friday'})+ self.assertEqual(day.canonical_representation['muscles'], {'back': [2], 'front': []})+ self.assertEqual(day.canonical_representation['obj'], day)+canonical_form = [{'exercise_list': [{'obj': Exercise.objects.get(pk=2),+ 'comment_list': [u'Foobar'],'setting_list': [10, 10, 10, 10],'setting_obj_list': [Setting.objects.get(pk=3)],'setting_text': u'4 \xd7 10'}],'is_superset': False,+ 'muscles': {'back': [2], 'front': []},'obj': Set.objects.get(pk=3)}]- self.assertEqual(day.canonical_representation, canonical_form)+ self.assertEqual(day.canonical_representation['set_list'], canonical_form)diff --git a/wger/manager/views/day.py b/wger/manager/views/day.pyindex 010cbacd2..432a301d3 100644--- a/wger/manager/views/day.py+++ b/wger/manager/views/day.py@@ -141,9 +141,7 @@ def view(request, id):template_data = {}# Load day and check if its workout belongs to the user- day = get_object_or_404(Day, pk=id)- if day.training.user != request.user:- return HttpResponseForbidden()+ day = get_object_or_404(Day, pk=id, training__user=request.user)template_data['day'] = daydiff --git a/wger/manager/views/workout.py b/wger/manager/views/workout.pyindex b7bd99ad9..b9e33e335 100644--- a/wger/manager/views/workout.py+++ b/wger/manager/views/workout.py@@ -76,43 +76,27 @@ def view(request, id):Show the workout with the given ID'''template_data = {}-workout = get_object_or_404(Workout, pk=id, user=request.user)- template_data['workout'] = workout+ canonical = workout.canonical_representation# Create the backgrounds that show what muscles the workout will work on- backgrounds = cache.get(cache_mapper.get_workout_muscle_bg(int(id)))- if not backgrounds:-- backgrounds_front = []- backgrounds_back = []- for day in workout.day_set.select_related():- for set in day.set_set.select_related():- for exercise in set.exercises.select_related():- for muscle in exercise.muscles.all():- muscle_bg = 'images/muscles/main/muscle-%s.svg' % muscle.id-- # Add the muscles to the background list, but only once.- #- # While the combining effect (the more often a muscle gets- # added, the more intense the colour) is interesting, the- # end result is a very unnatural, very bright colour.- if muscle.is_front and muscle_bg not in backgrounds_front:- backgrounds_front.append(muscle_bg)- elif not muscle.is_front and muscle_bg not in backgrounds_back:- backgrounds_back.append(muscle_bg)-- # Append the correct "main" background, with the silhouette of the human body- backgrounds_front.append('images/muscles/muscular_system_front.svg')- backgrounds_back.append('images/muscles/muscular_system_back.svg')-- backgrounds = (backgrounds_front, backgrounds_back)-- cache.set(cache_mapper.get_workout_muscle_bg(int(id)),- (backgrounds_front, backgrounds_back))-- template_data['muscle_backgrounds_front'] = backgrounds[0]- template_data['muscle_backgrounds_back'] = backgrounds[1]+ muscles_front = []+ muscles_back = []+ for i in canonical['muscles']['front']:+ if not i in muscles_front:+ muscles_front.append('images/muscles/main/muscle-{0}.svg'.format(i))+ for i in canonical['muscles']['back']:+ if not i in muscles_back:+ muscles_back.append('images/muscles/main/muscle-{0}.svg'.format(i))++ # Append the silhouette of the human body as the last entry so the browser+ # renders it in the background+ muscles_front.append('images/muscles/muscular_system_front.svg')+ muscles_back.append('images/muscles/muscular_system_back.svg')++ template_data['workout'] = workout+ template_data['muscle_backgrounds_front'] = muscles_front+ template_data['muscle_backgrounds_back'] = muscles_backreturn render_to_response('workout/view.html',template_data,@@ -233,26 +217,35 @@ class WorkoutEditView(WgerFormMixin, UpdateView, WgerPermissionMixin):login_required = True-def get_last_weight(user, exercise, reps):+class LastWeightHelper():'''- Helper function to retrieve the last workout log for a certain- user, exercise and repetition combination. Returns an emtpy string- if no entry is found-- :param user:- :param exercise:- :param reps:- :return: WorkoutLog or '' if none is found+ Small helper class to retrieve the last workout log for a certain+ user, exercise and repetition combination.'''- last_log = WorkoutLog.objects.filter(user=user,- exercise=exercise,- reps=reps).order_by('-date')- if last_log.exists():- weight = last_log[0].weight- else:- weight = ''+ user = None+ last_weight_list = {}++ def __init__(self, user):+ self.user = user++ def get_last_weight(self, exercise, reps):+ '''+ Returns an emtpy string if no entry is found++ :param exercise:+ :param reps:+ :return: WorkoutLog or '' if none is found+ '''+ key = '{0}-{1}-{2}'.format(self.user.pk, exercise.pk, reps)++ if self.last_weight_list.get(key) is None:+ last_log = WorkoutLog.objects.filter(user=self.user,+ exercise=exercise,+ reps=reps).order_by('-date')+ weight = last_log[0].weight if last_log.exists() else ''+ self.last_weight_list[key] = weight- return weight+ return self.last_weight_list.get(key)@login_required@@ -262,13 +255,13 @@ def timer(request, day_pk):'''day = get_object_or_404(Day, pk=day_pk, training__user=request.user)- #day = Day.objects.get(pk=day_pk, training__user=request.user)canonical_day = day.canonical_representationcontext = {}step_list = []+ last_log = LastWeightHelper(request.user)# Go through the workout day and create the individual 'pages'- for set_dict in canonical_day:+ for set_dict in canonical_day['set_list']:if not set_dict['is_superset']:for exercise_dict in set_dict['exercise_list']:@@ -280,9 +273,7 @@ def timer(request, day_pk):'exercise': exercise,'type': 'exercise','reps': reps,- 'weight': get_last_weight(user=request.user,- exercise=exercise,- reps=reps)})+ 'weight': last_log.get_last_weight(exercise, reps)})step_list.append({'current_step': uuid.uuid4().hex,'step_percent': 0,@@ -304,9 +295,7 @@ def timer(request, day_pk):'exercise': exercise,'type': 'exercise','reps': reps,- 'weight': get_last_weight(user=request.user,- exercise=exercise,- reps=reps)})+ 'weight': last_log.get_last_weight(exercise, reps)})step_list.append({'current_step': uuid.uuid4().hex,'step_percent': 0,diff --git a/wger/utils/cache.py b/wger/utils/cache.pyindex 3487424c0..c002ad79e 100644--- a/wger/utils/cache.py+++ b/wger/utils/cache.py@@ -50,7 +50,7 @@ class CacheKeyMapper(object):EXERCISE_CACHE_KEY = 'exercise-{0}'EXERCISE_CACHE_KEY_MUSCLE_BG = 'exercise-muscle-bg-{0}'INGREDIENT_CACHE_KEY = 'ingredient-{0}'- WORKOUT_MUSCLE_BG = 'workout-muscle-bg-{0}'+ WORKOUT_CANONICAL_REPRESENTATION = 'workout-canonical-representation-{0}'def get_exercise_key(self, param):'''@@ -107,15 +107,15 @@ class CacheKeyMapper(object):return self.INGREDIENT_CACHE_KEY.format(pk)- def get_workout_muscle_bg(self, param):+ def get_workout_canonical(self, param):'''- Return the workout muscle background cache key+ Return the workout canonical representation'''try:pk = param.pkexcept AttributeError:pk = param- return self.WORKOUT_MUSCLE_BG.format(pk)+ return self.WORKOUT_CANONICAL_REPRESENTATION.format(pk)cache_mapper = CacheKeyMapper()