Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Remove more old workout models

Roland Geiderd67c20645992
diff --git a/wger/core/templates/tags/render_day.html b/wger/core/templates/tags/render_day.html
deleted file mode 100644
index 5b18c0961..000000000
--- a/wger/core/templates/tags/render_day.html
+++ /dev/null
@@ -1,169 +0,0 @@
-{% load i18n static wger_extras thumbnail %}
-
-<script>
- $(document).ready(function () {
-
- // Call the setup function to allow the sets to be sortable again after loading this
- // view via AJAX
- wgerSetupSortable();
-
- // Init the modal dialog to edit the exercise
- wgerFormModalDialog();
-
- })
-</script>
-
-<table class="table table-bordered workout-table"
- id="table-day-{{ day.id }}"
- data-id="{{ day.id }}">
- <thead class="thead-light">
- <tr id="day-{{ day.id }}">
- <th colspan="2">
- {% if editable %}
- <div class="float-end">
- <div class="dropdown">
- <button class="btn btn-sm dropdown-toggle " type="button"
- id="dropdownMenuDay{{ day.id }}" data-bs-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.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.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.id %}"
- class="dropdown-item">
- <span class="{% fa_class 'trash' %}"></span>
- {% translate 'Delete' %}
- </a>
-
- </div>
- </div>
- </div>
- {% endif %}
-
- <h4>{{ day.description }}</h4>
- {{ day.days_txt }}
- </th>
- </tr>
- </thead>
- <tbody>
- {% for set in day.set_set.select_related.all %}
- <tr data-id="{{ set.id }}" id="set-{{ set.id }}">
- <td style="width: 15%;border-right-width: 0;">
- <span>#{{ forloop.counter }}</span>
-
- {% if editable %}
- <div class="dropdown float-end">
- <button class="btn btn-link btn-sm btn-block dropdown-toggle " type="button"
- id="dropdownMenuSet{{ set.id }}" data-bs-toggle="dropdown"
- aria-haspopup="true" aria-expanded="false">
- </button>
- <div class="dropdown-menu dropdown-menu-right"
- aria-labelledby="dropdownMenuSet{{ set.id }}">
- <a href="{% url 'manager:set:edit' 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.id %}"
- class="dropdown-item">
- <span class="{% fa_class 'trash' %}"></span>
- {% translate 'Delete' %}
- </a>
- </div>
- </div>
-
- {% if false and day.set_list|length > 1 %}
- <span class="editoptions">
- <span class="{% fa_class 'bars' %} dragndrop-handle"></span>
- <br>
- </span>
- {% endif %}
- {% endif %}
- </td>
- <td style="border-left-width: 0px;">
- {% if set.comment %}
- <p class="text-muted">{{ set.comment }}</p>
- {% endif %}
- <div class="exercise-list">
-
- {% for base in set.exercise_bases %}
- {% with base.get_exercise as exercise %}
-
- <div id="exercise-{{ base.id }}" class="ajax-set-edit-target">
- <div class="media">
-
- <div style="width: 64px; height: 64px;">
- <a href="{{ exercise.get_absolute_url }}">
- {% if base.main_image %}
- <img class="img-fluid"
- src="{{ base.main_image.image|thumbnail_url:'small' }}"
- alt="{{ exercise }}"
- style="max-width: 100%; max-height: 100%;">
- {% else %}
- <img class="img-fluid"
- src="{% static 'images/icons/image-placeholder.svg' %}"
- alt="{% translate 'Placeholder image for exercise' %}"
- style="opacity: 0.4;">
- {% endif %}
- </a>
- </div>
-
- <div class="media-body ml-2">
- <p class="media-heading h5">
- {{ exercise.name }}
- </p>
- <p>
- {{ base.settings }}
- </p>
-
- {% if editable %}
- {% if not base.settings %}
- <p>
- {% translate "This exercise has no repetitions." %}<br>
- <a href="{% url 'manager:set:edit' set.id %}"
- class="wger-modal-dialog">
- {% translate "Edit them now." %}
- </a>
- </p>
- {% endif %}
-
- {% if base.exercisecomment_set.all %}
- <p class="text-muted exercise-comments">
- {% for comment in base.exercisecomment_set.all %}
- {{ comment }}<br>
- {% endfor %}
- </p>
- {% endif %}
- {% endif %}
- </div>
- </div>
- </div>
- {% endwith %}
- {% endfor %} <!--for exercise in set-->
- </div>
- </td>
- </tr>
- {% endfor %} <!--for set in day-->
- {% if editable %}
- <tr>
- <td colspan="2" class="py-0">
- <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>
- {% endif %}
- </tbody>
-
-
-</table>
diff --git a/wger/core/templatetags/wger_extras.py b/wger/core/templatetags/wger_extras.py
index bc61124c3..be61cb23e 100644
--- a/wger/core/templatetags/wger_extras.py
+++ b/wger/core/templatetags/wger_extras.py
@@ -27,7 +27,6 @@ from django.utils.translation import (
)
# wger
-from wger.manager.models import Day
from wger.utils.constants import (
PAGINATION_MAX_TOTAL_PAGES,
PAGINATION_PAGES_AROUND_CURRENT,
@@ -50,18 +49,6 @@ def get_current_settings(exercise, set_id):
return exercise.exercise_base.setting_set.filter(set_id=set_id)
[email protected]_tag('tags/render_day.html')
-def render_day(day: Day, editable=True):
- """
- Renders a day as it will be displayed in the workout overview
- """
- return {
- 'day': day,
- 'workout': day.training,
- 'editable': editable,
- }
-
-
@register.inclusion_tag('tags/pagination.html')
def pagination(paginator, page):
"""
diff --git a/wger/manager/api/serializers.py b/wger/manager/api/serializers.py
index b3029aaea..7c17b2a5a 100644
--- a/wger/manager/api/serializers.py
+++ b/wger/manager/api/serializers.py
@@ -21,7 +21,6 @@ from rest_framework import serializers
# wger
from wger.core.models import DaysOfWeek
from wger.manager.models import (
- Day,
DayNg,
RepsConfig,
RestConfig,
@@ -29,7 +28,6 @@ from wger.manager.models import (
Routine,
Schedule,
ScheduleStep,
- Set,
SetsConfig,
Slot,
SlotConfig,
@@ -415,28 +413,3 @@ class ScheduleSerializer(serializers.ModelSerializer):
class Meta:
model = Schedule
exclude = ('user',)
-
-
-class DaySerializer(serializers.ModelSerializer):
- """
- Workout day serializer
- """
-
- training = serializers.PrimaryKeyRelatedField(queryset=Workout.objects.all())
- day = serializers.PrimaryKeyRelatedField(queryset=DaysOfWeek.objects.all(), many=True)
-
- class Meta:
- model = Day
- fields = ['id', 'training', 'description', 'day']
-
-
-class SetSerializer(serializers.ModelSerializer):
- """
- Workout setting serializer
- """
-
- exerciseday = serializers.PrimaryKeyRelatedField(queryset=Day.objects.all())
-
- class Meta:
- model = Set
- fields = ['id', 'exerciseday', 'sets', 'order', 'comment']
diff --git a/wger/manager/api/views.py b/wger/manager/api/views.py
index d7c34ab10..6c561b9d4 100644
--- a/wger/manager/api/views.py
+++ b/wger/manager/api/views.py
@@ -30,12 +30,10 @@ from rest_framework.response import Response
from wger.exercises.models import ExerciseBase
from wger.manager.api.serializers import (
DayNgSerializer,
- DaySerializer,
RoutineSerializer,
RoutineStructureSerializer,
ScheduleSerializer,
ScheduleStepSerializer,
- SetSerializer,
WorkoutDayDataDisplayModeSerializer,
WorkoutDayDataGymModeSerializer,
WorkoutLogSerializer,
@@ -44,12 +42,9 @@ from wger.manager.api.serializers import (
WorkoutTemplateSerializer,
)
from wger.manager.models import (
- Day,
Routine,
Schedule,
ScheduleStep,
- Set,
- Setting,
Workout,
WorkoutLog,
WorkoutSession,
@@ -346,68 +341,6 @@ class ScheduleViewSet(viewsets.ModelViewSet):
serializer.save(user=self.request.user)
-class DayViewSet(WgerOwnerObjectModelViewSet):
- """
- API endpoint for routine day objects
- """
-
- serializer_class = DaySerializer
- is_private = True
- ordering_fields = '__all__'
- filterset_fields = (
- 'description',
- 'training',
- 'day',
- )
-
- def get_queryset(self):
- """
- Only allow access to appropriate objects
- """
- # REST API generation
- if getattr(self, 'swagger_fake_view', False):
- return Day.objects.none()
-
- return Day.objects.filter(training__user=self.request.user)
-
- def get_owner_objects(self):
- """
- Return objects to check for ownership permission
- """
- return [(Workout, 'training')]
-
-
-class SetViewSet(WgerOwnerObjectModelViewSet):
- """
- API endpoint for workout set objects
- """
-
- serializer_class = SetSerializer
- is_private = True
- ordering_fields = '__all__'
- filterset_fields = (
- 'exerciseday',
- 'order',
- 'sets',
- )
-
- def get_queryset(self):
- """
- Only allow access to appropriate objects
- """
- # REST API generation
- if getattr(self, 'swagger_fake_view', False):
- return Set.objects.none()
-
- return Set.objects.filter(exerciseday__training__user=self.request.user)
-
- def get_owner_objects(self):
- """
- Return objects to check for ownership permission
- """
- return [(Day, 'exerciseday')]
-
-
class WorkoutLogViewSet(WgerOwnerObjectModelViewSet):
"""
API endpoint for workout log objects
diff --git a/wger/manager/forms.py b/wger/manager/forms.py
index c64780a13..bd2d477ca 100644
--- a/wger/manager/forms.py
+++ b/wger/manager/forms.py
@@ -49,23 +49,13 @@ from wger.core.models import (
RepetitionUnit,
WeightUnit,
)
-from wger.exercises.models import (
- Exercise,
- ExerciseBase,
-)
+from wger.exercises.models import ExerciseBase
from wger.manager.consts import RIR_OPTIONS
from wger.manager.models import (
- Day,
- Set,
- Setting,
Workout,
WorkoutLog,
WorkoutSession,
)
-from wger.utils.widgets import (
- ExerciseAjaxSelect,
- TranslatedSelectMultiple,
-)
class WorkoutForm(ModelForm):
@@ -99,21 +89,6 @@ class WorkoutCopyForm(Form):
)
-class DayForm(ModelForm):
- class Meta:
- model = Day
- exclude = ('training',)
- widgets = {'day': TranslatedSelectMultiple()}
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.helper = FormHelper()
- self.helper.layout = Layout(
- 'description',
- 'day',
- )
-
-
class OrderedModelMultipleChoiceField(ModelMultipleChoiceField):
"""Ordered multiple choice field"""
@@ -123,36 +98,6 @@ class OrderedModelMultipleChoiceField(ModelMultipleChoiceField):
return sorted(qs, key=lambda x: int_list.index(x.pk))
-class SetForm(ModelForm):
- exercises = OrderedModelMultipleChoiceField(
- queryset=ExerciseBase.objects.all(),
- label=_('Exercises'),
- required=False,
- widget=ExerciseAjaxSelect,
- help_text=_(
- 'You can search for more than one '
- 'exercise, they will be grouped '
- 'together for a superset.'
- ),
- )
-
- english_results = BooleanField(
- label=gettext_lazy('Also search for names in English'),
- initial=True,
- required=False,
- )
-
- class Meta:
- model = Set
- exclude = ('order', 'exerciseday')
-
-
-class SettingForm(ModelForm):
- class Meta:
- model = Setting
- exclude = ('set', 'exercise', 'order', 'name')
-
-
class WorkoutLogForm(ModelForm):
"""
Helper form for a WorkoutLog.
diff --git a/wger/manager/migrations/0021_flexible_routines_cleanup.py b/wger/manager/migrations/0021_flexible_routines_cleanup.py
index 67dcf0559..2647d7acf 100644
--- a/wger/manager/migrations/0021_flexible_routines_cleanup.py
+++ b/wger/manager/migrations/0021_flexible_routines_cleanup.py
@@ -22,16 +22,16 @@ class Migration(migrations.Migration):
old_name='exercise_base',
new_name='exercise',
),
- migrations.DeleteModel(
- name='Workout',
- ),
- migrations.DeleteModel(
- name='Day',
- ),
migrations.DeleteModel(
name='Setting',
),
migrations.DeleteModel(
name='Set',
),
+ migrations.DeleteModel(
+ name='Day',
+ ),
+ # migrations.DeleteModel(
+ # name='Workout',
+ # ),
]
diff --git a/wger/manager/models/__init__.py b/wger/manager/models/__init__.py
index a458ee7e8..abec1765b 100644
--- a/wger/manager/models/__init__.py
+++ b/wger/manager/models/__init__.py
@@ -16,10 +16,7 @@
# Local
from .abstract_config import AbstractChangeConfig
-from .day import (
- Day,
- DayNg,
-)
+from .day import DayNg
from .label import Label
from .log import WorkoutLog
from .reps_config import (
@@ -35,9 +32,7 @@ from .routine import Routine
from .schedule import Schedule
from .schedule_step import ScheduleStep
from .session import WorkoutSession
-from .set import Set
from .sets_config import SetsConfig
-from .setting import Setting
from .slot import Slot
from .slot_config import SlotConfig
from .weight_config import (
diff --git a/wger/manager/models/day.py b/wger/manager/models/day.py
index 39152beb7..acdd1da5e 100644
--- a/wger/manager/models/day.py
+++ b/wger/manager/models/day.py
@@ -184,50 +184,3 @@ class DayNg(models.Model):
current_slot.sets.extend([s.data for s in slot.set_data(iteration)])
return out
-
-
-class Day(models.Model):
- """
- Model for a training day
- """
-
- training = models.ForeignKey(
- 'Workout',
- verbose_name=_('Workout'),
- on_delete=models.CASCADE,
- )
-
- description = models.CharField(
- max_length=100,
- verbose_name=_('Description'),
- help_text=_(
- 'A description of what is done on this day (e.g. '
- '"Pull day") or what body parts are trained (e.g. '
- '"Arms and abs")'
- ),
- )
- day = models.ManyToManyField(DaysOfWeek, verbose_name=_('Day'))
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.description
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.training
-
- @property
- def days_txt(self):
- return ', '.join([str(_(i.day_of_week)) for i in self.day.all()])
-
- @property
- def get_first_day_id(self):
- """
- Return the PK of the first day of the week, this is used in the template
- to order the days in the template
- """
- return self.day.all()[0].pk
diff --git a/wger/manager/models/set.py b/wger/manager/models/set.py
deleted file mode 100644
index 413572f8a..000000000
--- a/wger/manager/models/set.py
+++ /dev/null
@@ -1,224 +0,0 @@
-# This file is part of wger Workout Manager <https://github.com/wger-project>.
-# Copyright (C) 2013 - 2021 wger Team
-#
-# wger Workout Manager is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# wger Workout Manager is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-# Standard Library
-from typing import List
-
-# Django
-from django.core.validators import (
- MaxValueValidator,
- MinValueValidator,
-)
-from django.db import models
-from django.utils.translation import gettext_lazy as _
-
-# wger
-from wger.exercises.models import ExerciseBase
-from wger.utils.helpers import normalize_decimal
-
-# Local
-from .day import Day
-
-
-class Set(models.Model):
- """
- Model for a set of exercises
- """
-
- DEFAULT_SETS = 4
- MAX_SETS = 10
-
- exerciseday = models.ForeignKey(
- Day,
- verbose_name=_('Exercise day'),
- on_delete=models.CASCADE,
- )
- order = models.IntegerField(
- default=1,
- null=False,
- verbose_name=_('Order'),
- )
- sets = models.IntegerField(
- validators=[MinValueValidator(0), MaxValueValidator(MAX_SETS)],
- verbose_name=_('Number of sets'),
- default=DEFAULT_SETS,
- )
-
- comment = models.CharField(max_length=200, verbose_name=_('Comment'), blank=True)
-
- # Metaclass to set some other properties
- class Meta:
- ordering = [
- 'order',
- ]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return f'Set-ID {self.id}'
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.exerciseday.training
-
- @property
- def exercise_bases(self) -> List[ExerciseBase]:
- """Returns the exercises for this set"""
- out = list(
- dict.fromkeys([s.exercise_base for s in self.setting_set.select_related().all()])
- )
- for exercise in out:
- exercise.settings = self.reps_smart_text(exercise)
-
- return out
-
- @property
- def compute_settings(self): # -> typing.List[Setting]:
- """
- Compute the synthetic settings for this set.
-
- If we have super sets the result will be an interleaved list of
- settings so the result are the exercises that have to be done, in
- order, e.g.:
-
- * Exercise 1, 10 reps, 50 kg
- * Exercise 2, 8 reps, 10 kg
- * Exercise 1, 10 reps, 50 kg
- * Exercise 2, 8 reps, 10 kg
- """
- setting_lists = []
- for base in self.exercise_bases:
- setting_lists.append(self.computed_settings_exercise(base))
-
- # Interleave all lists
- return [val for tup in zip(*setting_lists) for val in tup]
-
- def computed_settings_exercise(self, exercise_base: ExerciseBase): # -> typing.List[Setting]
- """
- Returns a computed list of settings
-
- If a set has only one set
- """
- settings = self.setting_set.filter(exercise_base=exercise_base)
-
- if settings.count() == 0:
- return []
- elif settings.count() == 1:
- setting = settings.first()
- return [setting] * self.sets
- else:
- return list(settings.all())
-
- def reps_smart_text(self, exercise_base: ExerciseBase):
- """
- "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".
- This helper also takes care to process, hide or show the different repetition
- and weight units as appropriate, e.g. "8 x 2 Plates", "10, 20, 30, ∞"
-
- :param exercise_base:
- :return setting_text, setting_list:
- """
-
- def get_rir_representation(setting):
- """
- Returns the representation for the Reps-In-Reserve for a setting
- """
-
- if setting.rir:
- rir = f'{setting.rir} RiR'
- else:
- rir = ''
- return rir
-
- def get_reps_reprentation(setting, rep_unit):
- """
- Returns the representation for the repetitions for a setting
-
- This is basically just to allow for a special representation for the
- "Until Failure" unit
- """
- if setting.repetition_unit_id != 2:
- reps = f'{setting.reps} {rep_unit}'.strip()
- else:
- reps = '∞'
- return reps
-
- def get_weight_unit_reprentation(setting):
- """
- Returns the representation for the weight unit for a setting
-
- This is basically just to allow for a special representation for the
- "Repetition" and "Until Failure" unit
- """
- if setting.repetition_unit.id not in (1, 2):
- rep_unit = _(setting.repetition_unit.name)
- else:
- rep_unit = ''
- return rep_unit
-
- def normalize_weight(setting):
- """
- The weight can be None, or a decimal. In that case, normalize so
- that we don't return e.g. '15.00', but always '15', independently of
- the database used.
- """
- if setting.weight:
- weight = normalize_decimal(setting.weight)
- else:
- weight = setting.weight
- return weight
-
- def get_setting_text(current_setting, multi=False):
- """Gets the repetition text for a complete setting"""
- rep_unit = get_weight_unit_reprentation(current_setting)
- reps = get_reps_reprentation(current_setting, rep_unit)
- weight_unit = settings[0].weight_unit.name
- weight = normalize_weight(current_setting)
- rir = get_rir_representation(current_setting)
- out = f'{self.sets} × {reps}'.strip() if not multi else reps
- if weight:
- rir_text = f', {rir}' if rir else ''
- out += f' ({weight} {weight_unit}{rir_text})'
- else:
- out += f' ({rir})' if rir else ''
-
- return out
-
- settings = self.setting_set.select_related().filter(exercise_base=exercise_base)
- setting_text = ''
-
- # Only one setting entry, this is a "compact" representation such as e.g.
- # 4x10 or similar
- if len(settings) == 1:
- setting = settings[0]
- setting_text = get_setting_text(setting)
-
- # There's more than one setting, each set can have a different combination
- # of repetitions, weight, etc. e.g. 10, 8, 8, 12
- elif len(settings) > 1:
- tmp_reps_text = []
- for setting in settings:
- tmp_reps_text.append(get_setting_text(setting, multi=True))
-
- setting_text = ' – '.join(tmp_reps_text)
-
- return setting_text
diff --git a/wger/manager/models/setting.py b/wger/manager/models/setting.py
deleted file mode 100644
index 56438fddb..000000000
--- a/wger/manager/models/setting.py
+++ /dev/null
@@ -1,137 +0,0 @@
-# This file is part of wger Workout Manager <https://github.com/wger-project>.
-# Copyright (C) 2013 - 2021 wger Team
-#
-# wger Workout Manager is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# wger Workout Manager is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-# Standard Library
-from decimal import Decimal
-
-# Django
-from django.core.validators import (
- MaxValueValidator,
- MinValueValidator,
-)
-from django.db import models
-from django.utils.translation import gettext_lazy as _
-
-# wger
-from wger.core.models import (
- RepetitionUnit,
- WeightUnit,
-)
-from wger.exercises.models import ExerciseBase
-
-# Local
-from ..consts import RIR_OPTIONS
-from .set import Set
-
-
-class Setting(models.Model):
- """
- Settings for an exercise (weight, reps, etc.)
- """
-
- set = models.ForeignKey(
- Set,
- verbose_name=_('Sets'),
- on_delete=models.CASCADE,
- )
-
- exercise_base = models.ForeignKey(
- ExerciseBase,
- verbose_name=_('Exercises'),
- on_delete=models.CASCADE,
- )
- repetition_unit = models.ForeignKey(
- RepetitionUnit,
- verbose_name=_('Unit'),
- default=1,
- on_delete=models.CASCADE,
- )
- """
- The repetition unit of a set. This can be e.g. a repetition, a minute, etc.
- """
-
- reps = models.IntegerField(
- validators=[MinValueValidator(0), MaxValueValidator(600)],
- verbose_name=_('Reps'),
- )
- """
- Amount of repetitions, minutes, etc. for a set.
-
- Note that since adding the unit field, the name is no longer correct, but is
- kept for compatibility reasons (specially for the REST API).
- """
-
- weight = models.DecimalField(
- verbose_name=_('Weight'),
- max_digits=6,
- decimal_places=2,
- blank=True,
- null=True,
- validators=[MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(1500))],
- )
- """Planed weight for the repetitions"""
-
- weight_unit = models.ForeignKey(
- WeightUnit,
- verbose_name=_('Unit'),
- default=1,
- on_delete=models.CASCADE,
- )
- """
- The weight unit of a set. This can be e.g. kg, lb, km/h, etc.
- """
-
- rir = models.CharField(
- verbose_name=_('RiR'),
- max_length=3,
- blank=True,
- null=True,
- choices=RIR_OPTIONS,
- )
- """
- Reps in reserve, RiR. The amount of reps that could realistically still be
- done in the set.
- """
-
- order = models.IntegerField(blank=True, verbose_name=_('Order'))
- comment = models.CharField(max_length=100, blank=True, verbose_name=_('Comment'))
-
- # Metaclass to set some other properties
- class Meta:
- ordering = ['order', 'id']
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return f'setting {self.id} for exercise base {self.exercise_base_id} in set {self.set_id}'
-
- def save(self, *args, **kwargs):
- """
- Reset cache
- """
-
- # If the user selected "Until Failure", do only 1 "repetition",
- # everythin else doesn't make sense.
- if self.repetition_unit == 2:
- self.reps = 1
- super(Setting, self).save(*args, **kwargs)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.set.exerciseday.training
diff --git a/wger/manager/tests/test_day.py b/wger/manager/tests/test_day.py
deleted file mode 100644
index 3cd0a8ae5..000000000
--- a/wger/manager/tests/test_day.py
+++ /dev/null
@@ -1,187 +0,0 @@
-# This file is part of wger Workout Manager.
-#
-# wger Workout Manager is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# wger Workout Manager is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-
-# Django
-from django.core.cache import cache
-from django.urls import reverse
-
-# wger
-from wger.core.tests.base_testcase import (
- WgerAddTestCase,
- WgerEditTestCase,
- WgerTestCase,
-)
-from wger.manager.models import Day
-from wger.utils.cache import cache_mapper
-
-
-class DayRepresentationTestCase(WgerTestCase):
- """
- Test the representation of a model
- """
-
- def test_representation(self):
- """
- Test that the representation of an object is correct
- """
- self.assertEqual(str(Day.objects.get(pk=1)), 'A day')
-
-
-class AddWorkoutDayTestCase(WgerAddTestCase):
- """
- Tests adding a day to a workout
- """
-
- object_class = Day
- url = reverse('manager:day:add', kwargs={'workout_pk': 3})
- user_success = 'test'
- user_fail = 'admin'
- data = {'description': 'a new day', 'day': [1, 4]}
-
-
-class DeleteWorkoutDayTestCase(WgerTestCase):
- """
- Tests deleting a day
- """
-
- def delete_day(self, fail=False):
- """
- Helper function to test deleting a day
- """
-
- # Fetch the day edit page
- count_before = Day.objects.count()
- response = self.client.get(reverse('manager:day:delete', kwargs={'pk': 5}))
- count_after = Day.objects.count()
-
- if fail:
- self.assertIn(response.status_code, (302, 404))
- self.assertTemplateUsed('login.html')
- self.assertEqual(count_before, count_after)
-
- else:
- self.assertRaises(Day.DoesNotExist, Day.objects.get, pk=5)
- self.assertEqual(response.status_code, 302)
- self.assertEqual(count_before - 1, count_after)
-
- def test_delete_day_anonymous(self):
- """
- Test deleting a day as an anonymous user
- """
-
- self.delete_day(fail=True)
-
- def test_delete_workout_owner(self):
- """
- Test deleting a day as the owner user
- """
-
- self.user_login('test')
- self.delete_day(fail=False)
-
- def test_delete_workout_other(self):
- """
- Test deleting a day as a different logged in user
- """
-
- self.user_login('admin')
- self.delete_day(fail=True)
-
-
-class EditWorkoutDayTestCase(WgerEditTestCase):
- """
- Tests editing the day of a Workout
- """
-
- object_class = Day
- url = 'manager:day:edit'
- pk = 5
- user_success = 'test'
- user_fail = 'admin'
- data = {'description': 'a different description', 'day': [1, 4]}
-
-
-class RenderWorkoutDayTestCase(WgerTestCase):
- """
- Tests rendering a single workout day
- """
-
- def render_day(self, fail=False):
- """
- Helper function to test rendering a single workout day
- """
-
- # Fetch the day edit page
- response = self.client.get(reverse('manager:day:view', kwargs={'id': 5}))
-
- if fail:
- self.assertIn(response.status_code, (302, 404))
- self.assertTemplateUsed('login.html')
-
- else:
- self.assertEqual(response.status_code, 200)
- self.assertTemplateUsed('day/view.html')
-
- def test_render_day_anonymous(self):
- """
- Test rendering a single workout day as an anonymous user
- """
-
- self.render_day(fail=True)
-
- def test_render_workout_owner(self):
- """
- Test rendering a single workout day as the owner user
- """
-
- self.user_login('test')
- self.render_day(fail=False)
-
- def test_render_workout_other(self):
- """
- Test rendering a single workout day as a different logged in user
- """
-
- self.user_login('admin')
- self.render_day(fail=True)
-
-
-class DayTestCase(WgerTestCase):
- """
- Other tests
- """
-
- def test_day_id_property(self):
- """
- Test that the attribute get_first_day_id works correctly
- """
-
- day = Day.objects.get(pk=5)
- self.assertEqual(day.get_first_day_id, 3)
-
- day = Day.objects.get(pk=3)
- self.assertEqual(day.get_first_day_id, 1)
-
-
-# class DayApiTestCase(api_base_test.ApiBaseResourceTestCase):
-# """
-# Tests the day API resource
-# """
-# pk = 5
-# resource = Day
-# private_resource = True
-# data = {"training": 3,
-# "description": "API update",
-# "day": [1, 4]
-# }
diff --git a/wger/manager/urls.py b/wger/manager/urls.py
index 936e60a3b..89217e879 100644
--- a/wger/manager/urls.py
+++ b/wger/manager/urls.py
@@ -26,13 +26,11 @@ from django.urls import (
# wger
from wger.core.views.react import ReactView
from wger.manager.views import (
- day,
ical,
log,
pdf,
schedule,
schedule_step,
- set,
workout,
workout_session,
)
@@ -230,59 +228,6 @@ patterns_session = [
),
]
-# sub patterns for workout days
-patterns_day = [
- path(
- '<int:pk>/edit',
- login_required(day.DayEditView.as_view()),
- name='edit',
- ),
- path(
- '<int:workout_pk>/add',
- login_required(day.DayCreateView.as_view()),
- name='add',
- ),
- path(
- '<int:pk>/delete',
- day.delete,
- name='delete',
- ),
- path(
- '<int:id>/view',
- day.view,
- name='view',
- ),
- path(
- '<int:pk>/log/add',
- log.add,
- name='log',
- ),
-]
-
-# sub patterns for workout sets
-patterns_set = [
- path(
- '<int:day_pk>/add',
- set.create,
- name='add',
- ),
- path(
- 'get-formset/<int:base_pk>/<int:reps>',
- set.get_formset,
- name='get-formset',
- ), # Used by JS
- path(
- '<int:pk>/delete',
- set.delete,
- name='delete',
- ),
- path(
- '<int:pk>/edit',
- set.edit,
- name='edit',
- ),
-]
-
# sub patterns for schedules
patterns_schedule = [
path(
@@ -391,8 +336,6 @@ urlpatterns = [
path('routine/', include((patterns_routine, 'routine'), namespace='routine')),
path('template/', include((patterns_templates, 'template'), namespace='template')),
path('log/', include((patterns_log, 'log'), namespace='log')),
- path('day/', include((patterns_day, 'day'), namespace='day')),
- path('set/', include((patterns_set, 'set'), namespace='set')),
path('session/', include((patterns_session, 'session'), namespace='session')),
path('schedule/', include((patterns_schedule, 'schedule'), namespace='schedule')),
path('schedule/step/', include((patterns_step, 'step'), namespace='step')),
diff --git a/wger/manager/views/day.py b/wger/manager/views/day.py
deleted file mode 100644
index 1ae28d45a..000000000
--- a/wger/manager/views/day.py
+++ /dev/null
@@ -1,144 +0,0 @@
-# -*- coding: utf-8 -*-
-
-# This file is part of wger Workout Manager.
-#
-# wger Workout Manager is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# wger Workout Manager is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-
-# Standard Library
-import logging
-
-# Django
-from django.contrib.auth.decorators import login_required
-from django.contrib.auth.mixins import LoginRequiredMixin
-from django.http import HttpResponseRedirect
-from django.shortcuts import (
- get_object_or_404,
- render,
-)
-from django.urls import reverse
-from django.utils.translation import (
- gettext as _,
- gettext_lazy,
-)
-from django.views.generic import (
- CreateView,
- UpdateView,
-)
-
-# wger
-from wger.core.models import DaysOfWeek
-from wger.manager.forms import DayForm
-from wger.manager.models import (
- Day,
- Workout,
-)
-from wger.utils.generic_views import WgerFormMixin
-
-
-logger = logging.getLogger(__name__)
-
-
-# ************************
-# Day functions
-# ************************
-class DayView(WgerFormMixin, LoginRequiredMixin):
- """
- Base generic view for exercise day
- """
-
- model = Day
- fields = ('description', 'day')
-
- def get_success_url(self):
- return reverse('manager:workout:view', kwargs={'pk': self.object.training_id})
-
- def get_form(self, form_class=DayForm):
- """
- Filter the days of the week that are already used by other days
- """
-
- # Get the form
- form = super(DayView, self).get_form(form_class)
-
- # Calculate the used days ('used' by other days in the same workout)
- if self.object:
- workout = self.object.training
- else:
- workout = Workout.objects.get(pk=self.kwargs['workout_pk'])
-
- used_days = []
- for day in workout.day_set.all():
- for weekday in day.day.all():
- if not self.object or day.id != self.object.id:
- used_days.append(weekday.id)
- used_days.sort()
-
- # Set the queryset for day
- form.fields['day'].queryset = DaysOfWeek.objects.exclude(id__in=used_days)
-
- return form
-
-
-class DayEditView(DayView, UpdateView):
- """
- Generic view to update an existing exercise day
- """
-
- # Send some additional data to the template
- def get_context_data(self, **kwargs):
- context = super(DayEditView, self).get_context_data(**kwargs)
- context['title'] = _('Edit {0}').format(self.object)
- return context
-
-
-class DayCreateView(DayView, CreateView):
- """
- Generic view to add a new exercise day
- """
-
- title = gettext_lazy('Add workout day')
- owner_object = {'pk': 'workout_pk', 'class': Workout}
-
- def form_valid(self, form):
- """
- Set the workout this day belongs to
- """
- form.instance.training = Workout.objects.get(pk=self.kwargs['workout_pk'])
- return super(DayCreateView, self).form_valid(form)
-
-
-@login_required
-def delete(request, pk):
- """
- Deletes the given day
- """
- day = get_object_or_404(Day, training__user=request.user, pk=pk)
- day.delete()
- return HttpResponseRedirect(reverse('manager:workout:view', kwargs={'pk': day.training_id}))
-
-
-@login_required
-def view(request, id):
- """
- Renders a day as shown in the workout overview.
-
- This function is to be used with AJAX calls.
- """
- template_data = {}
-
- # Load day and check if its workout belongs to the user
- day = get_object_or_404(Day, pk=id, training__user=request.user)
-
- template_data['day'] = day
-
- return render(request, 'day/view.html', template_data)
diff --git a/wger/manager/views/log.py b/wger/manager/views/log.py
index 7a6649cc6..b98dd497b 100644
--- a/wger/manager/views/log.py
+++ b/wger/manager/views/log.py
@@ -108,139 +108,7 @@ def add(request, pk):
Add a new workout log
"""
- # NOTE: This function is waaaay too complex and convoluted. While updating
- # to crispy forms, the template logic could be reduced a lot, but
- # there is still a lot of optimisations that could happen here.
-
- # Load the day and check ownership
- day = get_object_or_404(Day, pk=pk)
- if day.get_owner_object().user != request.user:
- return HttpResponseForbidden()
-
- # We need several lists here because we need to assign specific form to each
- # exercise: the entries for weight and repetitions have no indicator to which
- # exercise they belong besides the form-ID, from Django's formset
- counter = 0
- total_sets = 0
- exercise_list = {}
- form_to_exercise_base = {}
-
- for set_set in day.set_set.all():
- for exercise in set_set.exercise_bases:
- # Maximum possible values
- total_sets += int(set_set.sets)
- counter_before = counter
- counter = counter + int(set_set.sets) - 1
- form_id_range = range(counter_before, counter + 1)
-
- # Add to list
- exercise_list[exercise.id] = {
- 'obj': exercise,
- 'sets': int(set_set.sets),
- 'form_ids': form_id_range,
- }
-
- counter += 1
- # Helper mapping form-ID <--> Exercise base
- for id in form_id_range:
- form_to_exercise_base[id] = exercise
-
- # Define the formset here because now we know the value to pass to 'extra'
- WorkoutLogFormSet = modelformset_factory(
- WorkoutLog,
- form=WorkoutLogForm,
- exclude=('date', 'workout'),
- extra=total_sets,
- )
- # Process the request
- if request.method == 'POST':
- # Make a copy of the POST data and go through it. The reason for this is
- # that the form expects a value for the exercise which is not present in
- # the form (for space and usability reasons)
- post_copy = request.POST.copy()
-
- for form_id in form_to_exercise_base:
- if post_copy.get('form-%s-weight' % form_id) or post_copy.get('form-%s-reps' % form_id):
- post_copy['form-%s-exercise_base' % form_id] = form_to_exercise_base[form_id].id
-
- # Pass the new data to the forms
- formset = WorkoutLogFormSet(data=post_copy)
- session_form = HelperWorkoutSessionForm(data=post_copy)
-
- # If all the data is valid, save and redirect to log overview page
- if session_form.is_valid() and formset.is_valid():
- log_date = session_form.cleaned_data['date']
-
- if WorkoutSession.objects.filter(user=request.user, date=log_date).exists():
- session = WorkoutSession.objects.get(user=request.user, date=log_date)
- session_form = HelperWorkoutSessionForm(data=post_copy, instance=session)
-
- # Save the Workout Session only if there is not already one for this date
- log_instance = session_form.save(commit=False)
- if not WorkoutSession.objects.filter(user=request.user, date=log_date).exists():
- log_instance.date = log_date
- log_instance.user = request.user
- log_instance.workout = day.training
- else:
- session = WorkoutSession.objects.get(user=request.user, date=log_date)
- log_instance.instance = session
- log_instance.save()
-
- # Log entries (only the ones with actual content)
- log_instances = [i for i in formset.save(commit=False) if i.reps]
- for log_instance in log_instances:
- # Set the weight unit in kg
- if not hasattr(log_instance, 'weight_unit'):
- log_instance.weight_unit = WeightUnit.objects.get(pk=1)
-
- # Set the unit in reps
- if not hasattr(log_instance, 'repetition_unit'):
- log_instance.repetition_unit = RepetitionUnit.objects.get(pk=1)
-
- if not log_instance.weight:
- log_instance.weight = 0
-
- log_instance.user = request.user
- log_instance.workout = day.training
- log_instance.date = log_date
- log_instance.save()
-
- return HttpResponseRedirect(reverse('manager:log:log', kwargs={'pk': day.training_id}))
- else:
- # Initialise the formset with a queryset that won't return any objects
- # (we only add new logs here and that seems to be the fastest way)
- user_weight_unit = 1 if request.user.userprofile.use_metric else 2
- formset = WorkoutLogFormSet(
- queryset=WorkoutLog.objects.none(),
- initial=[
- {'weight_unit': user_weight_unit, 'repetition_unit': 1}
- for x in range(0, total_sets)
- ],
- )
-
- # Depending on whether there is already a workout session for today, update
- # the current one or create a new one (this will be the most usual case)
- if WorkoutSession.objects.filter(user=request.user, date=datetime.date.today()).exists():
- session = WorkoutSession.objects.get(user=request.user, date=datetime.date.today())
- session_form = HelperWorkoutSessionForm(instance=session)
- else:
- session_form = HelperWorkoutSessionForm()
-
- # Pass the correct forms to the exercise list
- for exercise in exercise_list:
- form_id_from = min(exercise_list[exercise]['form_ids'])
- form_id_to = max(exercise_list[exercise]['form_ids'])
- exercise_list[exercise]['forms'] = formset[form_id_from : form_id_to + 1]
-
- context = {
- 'day': day,
- 'exercise_list': exercise_list,
- 'formset': formset,
- 'helper': WorkoutLogFormHelper(),
- 'session_form': session_form,
- 'form': session_form,
- 'form_action': request.path,
- }
+ context = {}
return render(request, 'log/add.html', context)
diff --git a/wger/manager/views/set.py b/wger/manager/views/set.py
deleted file mode 100644
index c1aa7b128..000000000
--- a/wger/manager/views/set.py
+++ /dev/null
@@ -1,222 +0,0 @@
-# -*- coding: utf-8 -*-
-
-# This file is part of wger Workout Manager.
-#
-# wger Workout Manager is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# wger Workout Manager is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-
-# Standard Library
-import logging
-
-# Django
-from django.contrib.auth.decorators import login_required
-from django.db import models
-from django.forms.models import (
- inlineformset_factory,
- modelformset_factory,
-)
-from django.http import (
- HttpResponseForbidden,
- HttpResponseRedirect,
-)
-from django.shortcuts import (
- get_object_or_404,
- render,
-)
-from django.urls import reverse
-
-# wger
-from wger.exercises.models import ExerciseBase
-from wger.manager.forms import (
- SetForm,
- SettingForm,
- WorkoutLogFormHelper,
-)
-from wger.manager.models import (
- Day,
- Set,
- Setting,
-)
-
-
-logger = logging.getLogger(__name__)
-
-# ************************
-# Set functions
-# ************************
-SETTING_FORMSET_FIELDS = ('reps', 'repetition_unit', 'weight', 'weight_unit', 'rir')
-
-SettingFormset = modelformset_factory(
- Setting,
- form=SettingForm,
- fields=SETTING_FORMSET_FIELDS,
- can_delete=False,
- can_order=False,
- extra=1,
-)
-
-
-@login_required
-def create(request, day_pk):
- """
- Creates a new set. This view handles both the set form and the corresponding
- settings formsets
- """
- day = get_object_or_404(Day, pk=day_pk)
- if day.get_owner_object().user != request.user:
- return HttpResponseForbidden()
-
- context = {}
- formsets = []
- form = SetForm(initial={'sets': Set.DEFAULT_SETS})
-
- # If the form and all formsets validate, save them
- if request.method == 'POST':
- form = SetForm(request.POST)
- if form.is_valid():
- for base in form.cleaned_data['exercises']:
- formset = SettingFormset(
- request.POST, queryset=Setting.objects.none(), prefix=f'base{base.id}'
- )
- formsets.append({'exercise_base': base, 'formset': formset})
- all_valid = True
-
- for formset in formsets:
- if not formset['formset'].is_valid():
- all_valid = False
-
- if form.is_valid() and all_valid:
- # Manually take care of the order, TODO: better move this to the model
- max_order = day.set_set.select_related().aggregate(models.Max('order'))
- form.instance.order = (max_order['order__max'] or 0) + 1
- form.instance.exerciseday = day
- set_obj = form.save()
-
- order = 1
- for formset in formsets:
- instances = formset['formset'].save(commit=False)
- for instance in instances:
- instance.set = set_obj
- instance.order = order
- instance.exercise_base = formset['exercise_base']
- instance.save()
- order += 1
-
- return HttpResponseRedirect(
- reverse('manager:workout:view', kwargs={'pk': day.get_owner_object().id})
- )
- else:
- logger.debug(form.errors)
-
- # Other context we need
- context['form'] = form
- context['day'] = day
- context['max_sets'] = Set.MAX_SETS
- context['formsets'] = formsets
- context['helper'] = WorkoutLogFormHelper()
- return render(request, 'set/add.html', context)
-
-
-@login_required
-def get_formset(request, base_pk, reps=Set.DEFAULT_SETS):
- """
- Returns a formset. This is then rendered inside the new set template
- """
- exercise = ExerciseBase.objects.get(pk=base_pk)
- SettingFormSet = inlineformset_factory(
- Set,
- Setting,
- can_delete=False,
- extra=int(reps),
- fields=SETTING_FORMSET_FIELDS,
- )
- formset = SettingFormSet(
- queryset=Setting.objects.none(),
- prefix=f'base{base_pk}',
- )
- context = {'formset': formset, 'helper': WorkoutLogFormHelper(), 'exercise': exercise}
-
- return render(request, 'set/formset.html', context)
-
-
-@login_required
-def delete(request, pk):
- """
- Deletes the given set
- """
-
- # Load the set
- set_obj = get_object_or_404(Set, pk=pk)
-
- # Check if the user is the owner of the object
- if set_obj.get_owner_object().user == request.user:
- set_obj.delete()
- return HttpResponseRedirect(
- reverse('manager:workout:view', kwargs={'pk': set_obj.get_owner_object().id})
- )
- else:
- return HttpResponseForbidden()
-
-
-@login_required
-def edit(request, pk):
- """
- Edit a set (its settings actually)
- """
- set_obj = get_object_or_404(Set, pk=pk)
- if set_obj.get_owner_object().user != request.user:
- return HttpResponseForbidden()
-
- SettingFormsetEdit = modelformset_factory(
- Setting,
- form=SettingForm,
- fields=SETTING_FORMSET_FIELDS + ('id',),
- can_delete=False,
- can_order=True,
- extra=0,
- )
-
- formsets = []
- for base in set_obj.exercise_bases:
- queryset = Setting.objects.filter(set=set_obj, exercise_base=base)
- formset = SettingFormsetEdit(queryset=queryset, prefix=f'exercise{base.id}')
- formsets.append({'base': base, 'formset': formset})
-
- if request.method == 'POST':
- formsets = []
- for base in set_obj.exercise_bases:
- formset = SettingFormsetEdit(request.POST, prefix=f'exercise{base.id}')
- formsets.append({'base': base, 'formset': formset})
-
- # If all formsets validate, save them
- all_valid = True
- for formset in formsets:
- if not formset['formset'].is_valid():
- all_valid = False
-
- if all_valid:
- for formset in formsets:
- instances = formset['formset'].save(commit=False)
-
- for instance in instances:
- # Double check that we are allowed to edit the set
- if instance.get_owner_object().user != request.user:
- return HttpResponseForbidden()
- instance.save()
-
- return HttpResponseRedirect(
- reverse('manager:workout:view', kwargs={'pk': set_obj.get_owner_object().id})
- )
-
- # Other context we need
- context = {'formsets': formsets, 'helper': WorkoutLogFormHelper()}
- return render(request, 'set/edit.html', context)
diff --git a/wger/urls.py b/wger/urls.py
index 2ee0b83dd..ba3c7c5d2 100644
--- a/wger/urls.py
+++ b/wger/urls.py
@@ -64,7 +64,6 @@ router = routers.DefaultRouter()
# Manager app
router.register(r'day', manager_api_views.DayViewSet, basename='day')
-router.register(r'set', manager_api_views.SetViewSet, basename='Set')
router.register(r'workout', manager_api_views.WorkoutViewSet, basename='workout')
router.register(r'routine', manager_api_views.RoutineViewSet, basename='routine')
router.register(r'templates', manager_api_views.UserWorkoutTemplateViewSet, basename='templates')
diff --git a/wger/utils/widgets.py b/wger/utils/widgets.py
index 2ab2e53cd..c9648bb18 100644
--- a/wger/utils/widgets.py
+++ b/wger/utils/widgets.py
@@ -13,28 +13,20 @@
# Standard Library
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
-import logging
#
# You should have received a copy of the GNU Affero General Public License
-import uuid
-from itertools import chain
+
+# Standard Library
+import logging
# Django
from django.forms import fields
from django.forms.widgets import (
- CheckboxInput,
CheckboxSelectMultiple,
DateInput,
Select,
- SelectMultiple,
TextInput,
)
-from django.utils.encoding import force_str
-from django.utils.html import (
- conditional_escape,
- escape,
-)
-from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _
@@ -107,137 +99,11 @@ class Html5NumberInput(TextInput):
input_type = 'number'
-#
-# Others
-#
-class ExerciseAjaxSelect(SelectMultiple):
- """
- Custom widget that allows to select exercises from an autocompleter
-
- This is basically a modified MultipleSelect widget
- """
-
- def render(self, name, value, attrs=None, choices=(), renderer=None):
- if value is None:
- value = []
-
- output = [
- '<div>',
- '<input type="text" id="exercise-search" class="form-control">',
- '</div>',
- '<div id="exercise-search-log">',
- ]
-
- options = self.render_options(choices, value)
- if options:
- output.append(options)
- output.append('</div>')
-
- return mark_safe('\n'.join(output))
-
- def render_options(self, choices, selected_choices):
- # Normalize to strings.
- selected_choices = set(force_str(v) for v in selected_choices)
- output = []
- for option_value, option_label in chain(self.choices, choices):
- output.append(self.render_option(selected_choices, option_value, option_label))
- return '\n'.join(output)
-
- def render_option(self, selected_choices, option_value, option_label):
- option_value = force_str(option_value)
- if option_value in selected_choices:
- return """
- <div id="a%(div_id)s" class="ajax-exercise-select">
- <a href="#">
- <img src="/static/images/icons/status-off.svg"
- width="14"
- height="14"
- alt="Delete">
- </a> %(value)s
- <input type="hidden" name="exercises" value="%(id)s">
- </div>
- """ % {
- 'value': conditional_escape(force_str(option_label)),
- 'id': escape(option_value),
- 'div_id': uuid.uuid4(),
- }
-
- else:
- return ''
-
-
-class CheckboxChoiceInputTranslated(CheckboxInput):
- """
- Overwritten CheckboxInput
-
- This only translated the text for the select widgets
- """
-
- input_type = 'checkbox'
-
- def __init__(self, name, value, attrs, choice, index):
- choice = (choice[0], _(choice[1]))
-
- super(CheckboxChoiceInputTranslated, self).__init__(name, value, attrs, choice, index)
-
-
-class CheckboxChoiceInputTranslatedOriginal(CheckboxInput):
- """
- Overwritten CheckboxInput
-
- This only translated the text for the select widgets, showing the original
- string as well.
- """
-
- input_type = 'checkbox'
-
- def __init__(self, name, value, attrs, choice, index):
- if _(choice[1]) != choice[1]:
- choice = (choice[0], f'{choice[1]} ({_(choice[1])})')
- else:
- choice = (choice[0], _(choice[1]))
-
- super(CheckboxChoiceInputTranslatedOriginal, self).__init__(
- name, value, attrs, choice, index
- )
-
-
-class CheckboxFieldRendererTranslated(CheckboxSelectMultiple):
- choice_input_class = CheckboxChoiceInputTranslated
-
-
-class CheckboxFieldRendererTranslatedOriginal(CheckboxSelectMultiple):
- choice_input_class = CheckboxChoiceInputTranslatedOriginal
-
-
class BootstrapSelectMultiple(CheckboxSelectMultiple):
pass
# renderer = CheckboxBootstrapRenderer
-class BootstrapSelectMultipleTranslatedOriginal(CheckboxSelectMultiple):
- pass
- # renderer = CheckboxBootstrapRendererTranslatedOriginal
-
-
-class TranslatedSelectMultiple(BootstrapSelectMultiple):
- """
- A SelectMultiple widget that translates the options
- """
-
- pass
-
-
-class TranslatedOriginalSelectMultiple(BootstrapSelectMultipleTranslatedOriginal):
- """
- A SelectMultiple widget that translates the options, showing the original
- string as well. This is currently only used in the muscle list, where the
- translated muscles as well as the latin names are shown.
- """
-
- pass
-
-
class TranslatedSelect(Select):
"""
A Select widget that translates the options