Self hosted FLOSS fitness/workout, nutrition and weight tracker
Start removing the crime that was the canonical representation of a workout
Roland Geider55b5b8162e6a
diff --git a/wger/core/templates/tags/muscles.html b/wger/core/templates/tags/muscles.htmlindex 15a35dae7..6d682f9ea 100644--- a/wger/core/templates/tags/muscles.html+++ b/wger/core/templates/tags/muscles.html@@ -1,5 +1,5 @@{% load static %}-{% if not empty %}+{% if backgrounds %}<div class="muscle-background mx-auto"style="background-image: {% for background in backgrounds %}url({{ background }}){% if not forloop.last %},{% endif %}{% endfor %};"></div>diff --git a/wger/core/templates/tags/render_day.html b/wger/core/templates/tags/render_day.htmlindex 1e443566f..1d27ca142 100644--- a/wger/core/templates/tags/render_day.html+++ b/wger/core/templates/tags/render_day.html@@ -13,34 +13,33 @@})</script>-<table class="table table-bordered workout-table" id="table-day-{{ day.obj.id }}"- data-id="{{ day.obj.id }}">+<table class="table table-bordered workout-table"+ id="table-day-{{ day.id }}"+ data-id="{{ day.id }}"><thead class="thead-light">- <tr id="day-{{ day.obj.id }}">+ <tr id="day-{{ day.id }}"><th colspan="2">--{% if editable %}<div class="float-right"><div class="dropdown"><button class="btn btn-sm dropdown-toggle " type="button"- id="dropdownMenuDay{{ day.obj.id }}" data-toggle="dropdown"+ id="dropdownMenuDay{{ day.id }}" data-toggle="dropdown"aria-haspopup="true" aria-expanded="false"><span class="{% fa_class 'cog' %}"></span></button><div class="dropdown-menu dropdown-menu-right"- aria-labelledby="dropdownMenuDay{{ day.obj.id }}">- <a href="{% url 'manager:day:log' day.obj.id %}" class="dropdown-item">+ aria-labelledby="dropdownMenuDay{{ day.id }}">+ <a href="{% url 'manager:day:log' day.id %}" class="dropdown-item"><span class="{% fa_class 'chart-line' %}"></span>{% translate 'Add weight log' %}</a>- <a href="{% url 'manager:day:edit' day.obj.id %}"+ <a href="{% url 'manager:day:edit' day.id %}"class="wger-modal-dialog dropdown-item"><span class="{% fa_class 'edit' %}"></span>{% translate 'Edit' %}</a><div class="dropdown-divider"></div>- <a href="{% url 'manager:day:delete' day.obj.id %}"+ <a href="{% url 'manager:day:delete' day.id %}"class="dropdown-item"><span class="{% fa_class 'trash' %}"></span>{% translate 'Delete' %}@@ -51,32 +50,32 @@</div>{% endif %}- <h4>{{ day.obj.description }}</h4>+ <h4>{{ day.description }}</h4>{{ day.days_of_week.text }}</th></tr></thead><tbody>- {% for set in day.set_list %}- <tr data-id="{{ set.obj.id }}" id="set-{{ set.obj.id }}">+ {% for set_data in day.sets %}+ <tr data-id="{{ set_data.set.id }}" id="set-{{ set_data.set.id }}"><td style="width: 15%;border-right-width: 0;"><span>#{{ forloop.counter }}</span>{% if editable %}<div class="dropdown float-right"><button class="btn btn-link btn-sm btn-block dropdown-toggle " type="button"- id="dropdownMenuSet{{ set.obj.id }}" data-toggle="dropdown"+ id="dropdownMenuSet{{ set_data.set.id }}" data-toggle="dropdown"aria-haspopup="true" aria-expanded="false"></button><div class="dropdown-menu dropdown-menu-right"- aria-labelledby="dropdownMenuSet{{ set.obj.id }}">- <a href="{% url 'manager:set:edit' set.obj.id %}"+ aria-labelledby="dropdownMenuSet{{ set_data.set.id }}">+ <a href="{% url 'manager:set:edit' set_data.set.id %}"class="wger-modal-dialog dropdown-item"><span class="{% fa_class 'edit' %}"></span>{% translate 'Edit' %}</a><div class="dropdown-divider"></div>- <a href="{% url 'manager:set:delete' set.obj.id %}"+ <a href="{% url 'manager:set:delete' set_data.set.id %}"class="dropdown-item"><span class="{% fa_class 'trash' %}"></span>{% translate 'Delete' %}@@ -93,20 +92,21 @@{% endif %}</td><td style="border-left-width: 0px;">- {% if set.obj.comment %}- <p class="text-muted">{{ set.obj.comment }}</p>+ {% if set_data.set.comment %}+ <p class="text-muted">{{ set_data.set.comment }}</p>{% endif %}<div class="exercise-list">- {% for exercise in set.exercise_list %}- <div id="exercise-{{ exercise.obj.id }}" class="ajax-set-edit-target">++ {% for exercise_data in set_data.exercises %}+ <div id="exercise-{{ exercise_data.exercise.id }}" class="ajax-set-edit-target"><div class="media"><div style="width: 64px; height: 64px;">- <a href="{{ exercise.obj.get_absolute_url }}">- {% if exercise.obj.main_image %}+ <a href="{{ exercise_data.exercise.get_absolute_url }}">+ {% if exercise_data.main_image %}<img class="img-fluid"- src="{{ exercise.obj.main_image.image|thumbnail_url:'small' }}"- alt="{{ exercise.obj }}"+ src="{{ exercise_data.main_image.image|thumbnail_url:'small' }}"+ alt="{{ exercise_data }}"style="max-width: 100%; max-height: 100%;">{% else %}<img class="img-fluid"@@ -119,24 +119,26 @@<div class="media-body ml-2"><p class="media-heading h5">- {{ exercise.obj.name }}+ {{ exercise_data.exercise.name }}+ </p>+ <p>+ {{ exercise_data.setting_text }}</p>- <p>{{ exercise.setting_text }}</p>{% if editable %}- {% if not exercise.setting_obj_list %}+ {% if not exercise_data.settings %}<p>{% translate "This exercise has no repetitions." %}<br>- <a href="{% url 'manager:set:edit' set.obj.id %}"+ <a href="{% url 'manager:set:edit' set_data.set.id %}"class="wger-modal-dialog">{% translate "Edit them now." %}</a></p>{% endif %}- {% if exercise.comment_list %}+ {% if exercise_data.exercise.comment_set.all %}<p class="text-muted exercise-comments">- {% for comment in exercise.comment_list %}+ {% for comment in exercise_data.exercise.comment_set.all %}{{ comment }}<br>{% endfor %}</p>@@ -153,7 +155,7 @@{% if editable %}<tr><td colspan="2" class="py-0">- <a href="{% url 'manager:set:add' day.obj.id %}"+ <a href="{% url 'manager:set:add' day.id %}"class="wger-modal-dialog btn btn-link btn-block">{% translate "Add exercises to this workout day" %}</a></td></tr>diff --git a/wger/core/templatetags/wger_extras.py b/wger/core/templatetags/wger_extras.pyindex 745bc9bfa..3cda8677d 100644--- a/wger/core/templatetags/wger_extras.py+++ b/wger/core/templatetags/wger_extras.py@@ -14,10 +14,12 @@## You should have received a copy of the GNU Affero General Public License+# Standard Library+from collections import Iterable+# Djangofrom django import templatefrom django.conf import settings-from django.db.models import QuerySetfrom django.templatetags.static import staticfrom django.utils.html import strip_spaces_between_tagsfrom django.utils.safestring import mark_safe@@ -27,6 +29,7 @@ from django.utils.translation import ()# wger+from wger.manager.models import Dayfrom wger.utils.constants import (PAGINATION_MAX_TOTAL_PAGES,PAGINATION_PAGES_AROUND_CURRENT,@@ -49,12 +52,12 @@ def get_current_settings(exercise, set_id):@register.inclusion_tag('tags/render_day.html')-def render_day(day, editable=True):+def render_day(day: Day, editable=True):"""Renders a day as it will be displayed in the workout overview"""return {- 'day': day.canonical_representation,+ 'day': day,'workout': day.training,'editable': editable,}@@ -118,27 +121,28 @@ def render_muscles(muscles=None, muscles_sec=None):"""Renders the given muscles"""+ out = {"backgrounds": []}if not muscles and not muscles_sec:- return {"empty": True}+ return outout_main = []if muscles:- out_main = muscles if isinstance(muscles, (list, tuple, QuerySet)) else [muscles]+ out_main = muscles if isinstance(muscles, Iterable) else [muscles]- out_sec = []+ out_secondary = []if muscles_sec:- out_sec = muscles_sec if isinstance(muscles_sec, (list, tuple, QuerySet)) else [muscles_sec]+ out_secondary = muscles_sec if isinstance(muscles_sec, Iterable) else [muscles_sec]- try:+ if out_main:front_back = "front" if out_main[0].is_front else "back"- except IndexError:- front_back = "front" if out_sec[0].is_front else "back"+ else:+ front_back = "front" if out_secondary[0].is_front else "back"- backgrounds = [i.image_url_main for i in out_main] \- + [i.image_url_secondary for i in out_sec] \+ out['backgrounds'] = [i.image_url_main for i in out_main] \+ + [i.image_url_secondary for i in out_secondary] \+ [static(f"images/muscles/muscular_system_{front_back}.svg")]- return {"backgrounds": backgrounds, "empty": False}+ return out@register.inclusion_tag('tags/language_select.html', takes_context=True)diff --git a/wger/manager/helpers.py b/wger/manager/helpers.pyindex f27f472cd..cee3d77a3 100644--- a/wger/manager/helpers.py+++ b/wger/manager/helpers.py@@ -18,6 +18,7 @@# Standard Libraryimport datetimefrom calendar import HTMLCalendar+from typing import List# Djangofrom django.urls import reverse@@ -36,6 +37,7 @@ from reportlab.platypus import ()# wger+from wger.exercises.models import Musclefrom wger.utils.pdf import (header_colour,row_color,@@ -275,3 +277,34 @@ class WorkoutCalendar(HTMLCalendar):Renders a day cell"""return '<td class="{0}" style="vertical-align: middle;">{1}</td>'.format(cssclass, body)+++class MusclesHelper:+ """+ Helper container for trained muscles in a workout plan, day, etc.+ """+ front: List[Muscle]+ back: List[Muscle]+ front_secondary: List[Muscle]+ back_secondary: List[Muscle]++ def __init__(self):+ self.front = []+ self.front_secondary = []+ self.back = []+ self.back_secondary = []++ def __add__(self, other):+ for attr in ['front', 'front_secondary', 'back', 'back_secondary']:+ for m in getattr(other, attr):+ self.add(m)++ return self++ def add(self, muscle: Muscle, main=True):+ target = 'front' if muscle.is_front else 'back'+ suffix = '_secondary' if not main else ''+ muscles: List = getattr(self, target + suffix)++ if not muscle in muscles:+ muscles.append(muscle)diff --git a/wger/manager/models/day.py b/wger/manager/models/day.pyindex a69bc27c4..704ca7137 100644--- a/wger/manager/models/day.py+++ b/wger/manager/models/day.py@@ -23,6 +23,7 @@ from wger.core.models import DaysOfWeekfrom wger.utils.cache import reset_workout_canonical_form# Local+from ..helpers import MusclesHelperfrom .workout import Workout@@ -80,138 +81,44 @@ class Day(models.Model):super(Day, self).delete(*args, **kwargs)@property- def canonical_representation(self):- """- Return the canonical representation for this day+ def muscles(self) -> MusclesHelper:+ """All trained muscles by the exercises in this day"""+ out = MusclesHelper()- 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+ for set_obj in self.set_set.all():+ for exercise in set_obj.exercises:+ for muscle in exercise.muscles.all():+ out.add(muscle)++ for muscle in exercise.muscles_secondary.all():+ out.add(muscle, False)++ return out++ @property+ def sets(self):- def get_canonical_representation(self):- """- Creates a canonical representation for this day- """# Localfrom .setting import Setting- canonical_repr = []- muscles_front = []- muscles_back = []- muscles_front_secondary = []- muscles_back_secondary = []-+ out = []for set_obj in self.set_set.select_related():- exercise_tmp = []+ set_data = {+ 'exercises': [],+ 'set': set_obj,+ }for exercise in set_obj.exercises:- setting_tmp = []- exercise_images_tmp = []+ exercise_data = {+ 'exercise':+ exercise,+ 'setting_text':+ set_obj.reps_smart_text(exercise),+ 'settings':+ Setting.objects.filter(set=set_obj, exercise=exercise).order_by('order', 'id'),+ }+ set_data['exercises'].append(exercise_data)- # Muscles for this set- for muscle in exercise.muscles.all():- if muscle.is_front and muscle not in muscles_front:- muscles_front.append(muscle)- elif not muscle.is_front and muscle not in muscles_back:- muscles_back.append(muscle)+ out.append(set_data)- for muscle in exercise.muscles_secondary.all():- if muscle.is_front and muscle not in muscles_front:- muscles_front_secondary.append(muscle)- elif not muscle.is_front and muscle.id not in muscles_back:- muscles_back_secondary.append(muscle)-- for setting in Setting.objects.filter(set=set_obj,- exercise=exercise).order_by('order', 'id'):- setting_tmp.append(setting)-- # "Smart" textual representation- setting_text = set_obj.reps_smart_text(exercise)-- # Exercise comments- comment_list = []- for i in exercise.exercisecomment_set.all():- comment_list.append(i.comment)-- # Flag indicating whether any of the settings has saved weight- has_weight = False- for i in setting_tmp:- if i.weight:- has_weight = True- break-- # Collect exercise images- for image in exercise.images.all():- exercise_images_tmp.append(- {- 'image': image.image.url,- 'is_main': image.is_main,- }- )-- # Put it all together- exercise_tmp.append(- {- 'obj': exercise,- 'setting_obj_list': setting_tmp,- 'setting_text': setting_text,- 'has_weight': has_weight,- 'comment_list': comment_list,- 'image_list': exercise_images_tmp- }- )-- # If it's a superset, check that all exercises have the same repetitions.- # If not, just take the smallest number and drop the rest, because otherwise- # it doesn't make sense-- # if len(exercise_tmp) > 1:- # common_reps = 100- # for exercise in exercise_tmp:- # if len(exercise['setting_list']) < common_reps:- # common_reps = len(exercise['setting_list'])-- # for exercise in exercise_tmp:- # if len(exercise['setting_list']) > common_reps:- # exercise['setting_list'].pop(-1)- # exercise['setting_obj_list'].pop(-1)- # setting_text, setting_list = set_obj.reps_smart_text(exercise)- # exercise['setting_text'] = setting_text-- canonical_repr.append(- {- 'obj': set_obj,- 'exercise_list': exercise_tmp,- 'is_superset': True if len(exercise_tmp) > 1 else False,- 'settings_computed': set_obj.compute_settings,- 'muscles': {- 'back': muscles_back,- 'front': muscles_front,- 'frontsecondary': muscles_front_secondary,- 'backsecondary': muscles_front_secondary- }- }- )-- # 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': ', '.join([str(_(i.day_of_week)) for i in tmp_days_of_week]),- 'day_list': tmp_days_of_week- },- 'muscles': {- 'back': muscles_back,- 'front': muscles_front,- 'frontsecondary': muscles_front_secondary,- 'backsecondary': muscles_front_secondary- },- 'set_list': canonical_repr- }+ return outdiff --git a/wger/manager/models/workout.py b/wger/manager/models/workout.pyindex ba384624c..928478a17 100644--- a/wger/manager/models/workout.py+++ b/wger/manager/models/workout.py@@ -22,6 +22,7 @@ from django.urls import reversefrom django.utils.translation import gettext_lazy as _# wger+from wger.manager.helpers import MusclesHelperfrom wger.utils.cache import (cache_mapper,reset_workout_canonical_form,@@ -97,56 +98,11 @@ class Workout(models.Model):return self@property- 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.- """- workout_canonical_form = cache.get(cache_mapper.get_workout_canonical(self.pk))- if not workout_canonical_form:- day_canonical_repr = []- muscles_front = []- muscles_back = []- muscles_front_secondary = []- muscles_back_secondary = []-- # Sort list by weekday- day_list = [i for i in self.day_set.select_related()]- day_list.sort(key=lambda day: day.get_first_day_id)-- for day in day_list:- 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)- for i in canonical_repr_day['muscles']['frontsecondary']:- if i not in muscles_front_secondary:- muscles_front_secondary.append(i)- for i in canonical_repr_day['muscles']['backsecondary']:- if i not in muscles_back_secondary:- muscles_back_secondary.append(i)-- day_canonical_repr.append(canonical_repr_day)+ def muscles(self) -> MusclesHelper:+ """All trained muscles by this workout"""+ out = MusclesHelper()- workout_canonical_form = {- 'obj': self,- 'muscles': {- 'front': muscles_front,- 'back': muscles_back,- 'frontsecondary': muscles_front_secondary,- 'backsecondary': muscles_back_secondary- },- 'day_list': day_canonical_repr- }- # Save to cache- cache.set(cache_mapper.get_workout_canonical(self.pk), workout_canonical_form)+ for day in self.day_set.all():+ out += day.muscles- return workout_canonical_form+ return outdiff --git a/wger/manager/templates/workout/view.html b/wger/manager/templates/workout/view.htmlindex a750a9c7f..f68055eae 100644--- a/wger/manager/templates/workout/view.html+++ b/wger/manager/templates/workout/view.html@@ -60,9 +60,9 @@ $(document).ready(function () {<p>{{ workout.description }}</p>{% endif %}-{% for day in workout.canonical_representation.day_list %}- <div id="div-day-{{ day.obj.id }}">- {% render_day day.obj is_owner %}+{% for day in workout.day_set.all %}+ <div id="div-day-{{ day.id }}">+ {% render_day day is_owner %}</div>{% endfor %}@@ -102,10 +102,10 @@ $(document).ready(function () {<div class="row"><div class="col-6">- {% render_muscles muscles.front muscles.frontsecondary %}+ {% render_muscles workout.muscles.front workout.muscles.front_secondary %}</div><div class="col-6">- {% render_muscles muscles.back muscles.backsecondary %}+ {% render_muscles workout.muscles.back workout.muscles.back_secondary %}</div></div>diff --git a/wger/manager/views/workout.py b/wger/manager/views/workout.pyindex ec53b6cab..31c52024b 100644--- a/wger/manager/views/workout.py+++ b/wger/manager/views/workout.py@@ -112,7 +112,6 @@ def view(request, pk):uid, token = make_token(user)template_data['workout'] = workout- template_data['muscles'] = canonical['muscles']template_data['uid'] = uidtemplate_data['token'] = tokentemplate_data['is_owner'] = is_owner