id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
22,400 | image.py | wger-project_wger/wger/gallery/models/image.py | # 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
# Standard Library
import datetime
import pathlib
import uuid
# Django
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _
def gallery_upload_dir(instance, filename):
"""
Returns the upload target for exercise images
"""
return f'gallery/{instance.user.id}/{uuid.uuid4()}{pathlib.Path(filename).suffix}'
class Image(models.Model):
class Meta:
ordering = [
'-date',
]
date = models.DateField(_('Date'), default=datetime.datetime.now)
user = models.ForeignKey(
User,
verbose_name=_('User'),
on_delete=models.CASCADE,
)
image = models.ImageField(
verbose_name=_('Image'),
help_text=_('Only PNG and JPEG formats are supported'),
upload_to=gallery_upload_dir,
height_field='height',
width_field='width',
)
height = models.IntegerField(editable=False)
"""Height of the image"""
width = models.IntegerField(editable=False)
"""Width of the image"""
description = models.TextField(
verbose_name=_('Description'),
max_length=1000,
blank=True,
)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
@property
def is_landscape(self):
return self.width > self.height
@receiver(models.signals.post_delete, sender=Image)
def auto_delete_file_on_delete(sender, instance: Image, **kwargs):
"""
Deletes file from filesystem
when corresponding `MediaFile` object is deleted.
"""
if instance.image:
path = pathlib.Path(instance.image.path)
if path.exists():
path.unlink()
@receiver(models.signals.pre_save, sender=Image)
def auto_delete_file_on_change(sender, instance: Image, **kwargs):
"""
Deletes old file from filesystem
when corresponding `MediaFile` object is updated
with new file.
"""
if not instance.pk:
return False
try:
old_file = sender.objects.get(pk=instance.pk).image
except sender.DoesNotExist:
return False
new_file = instance.image
if not old_file == new_file:
path = pathlib.Path(old_file.path)
if path.is_file():
path.unlink()
| 3,106 | Python | .py | 92 | 28.5 | 86 | 0.689045 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,401 | 0001_initial.py | wger-project_wger/wger/gallery/migrations/0001_initial.py | # Generated by Django 3.1.8 on 2021-05-03 10:53
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import wger.gallery.models.image
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Image',
fields=[
(
'id',
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name='ID'
),
),
('date', models.DateField(default=datetime.datetime.now, verbose_name='Date')),
(
'image',
models.ImageField(
height_field='height',
help_text='Only PNG and JPEG formats are supported',
upload_to=wger.gallery.models.image.gallery_upload_dir,
verbose_name='Image',
width_field='width',
),
),
('height', models.IntegerField(editable=False)),
('width', models.IntegerField(editable=False)),
(
'description',
models.TextField(blank=True, max_length=1000, verbose_name='Description'),
),
(
'user',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
verbose_name='User',
),
),
],
options={
'ordering': ['-date'],
},
),
]
| 1,896 | Python | .py | 52 | 21.288462 | 95 | 0.469821 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,402 | images.py | wger-project_wger/wger/gallery/views/images.py | # -*- 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
from datetime import datetime
# Django
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.urls import (
reverse,
reverse_lazy,
)
from django.utils.translation import gettext_lazy as _
from django.views.generic import (
CreateView,
DeleteView,
UpdateView,
)
# wger
from wger.gallery.forms import ImageForm
from wger.gallery.models.image import Image
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
)
@login_required
def overview(request):
"""
An overview of all the user's images
"""
images = Image.objects.filter(user=request.user)
context = {'images': images}
return render(request, 'images/overview.html', context)
class ImageAddView(WgerFormMixin, CreateView):
"""
Generic view to add a new weight entry
"""
model = Image
form_class = ImageForm
title = _('Add')
def get_initial(self):
"""
Set the initial data for the form.
Read the comment on weight/models.py WeightEntry about why we need
to pass the user here.
"""
return {'user': self.request.user, 'date': datetime.today()}
def form_valid(self, form):
"""
Set the owner of the entry here
"""
form.instance.user = self.request.user
return super(ImageAddView, self).form_valid(form)
def get_success_url(self):
"""
Return to overview
"""
return reverse('gallery:images:overview')
class ImageUpdateView(WgerFormMixin, LoginRequiredMixin, UpdateView):
"""
Generic view to edit an existing weight entry
"""
model = Image
form_class = ImageForm
def get_context_data(self, **kwargs):
context = super(ImageUpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit')
return context
def get_success_url(self):
"""
Return to overview
"""
return reverse('gallery:images:overview')
class ImageDeleteView(WgerDeleteMixin, LoginRequiredMixin, DeleteView):
"""
View to delete an existing image
"""
model = Image
success_url = reverse_lazy('gallery:images:overview')
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(ImageDeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete {0}?').format(self.object)
return context
| 3,253 | Python | .py | 98 | 28.22449 | 78 | 0.697125 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,403 | serializers.py | wger-project_wger/wger/gallery/api/serializers.py | # Third Party
from rest_framework import serializers
# wger
from wger.gallery.models import Image
class ImageSerializer(serializers.ModelSerializer):
"""
Exercise serializer
"""
class Meta:
model = Image
fields = ['id', 'date', 'image', 'description', 'height', 'width']
| 307 | Python | .py | 11 | 23.636364 | 74 | 0.691781 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,404 | views.py | wger-project_wger/wger/gallery/api/views.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
import logging
# Third Party
from rest_framework import viewsets
from rest_framework.parsers import (
FormParser,
MultiPartParser,
)
from rest_framework.permissions import IsAuthenticated
# wger
from wger.gallery.api.serializers import ImageSerializer
from wger.gallery.models import Image
logger = logging.getLogger(__name__)
class GalleryImageViewSet(viewsets.ModelViewSet):
"""
API endpoint for gallery image
"""
parser_classes = [MultiPartParser, FormParser]
permission_classes = [IsAuthenticated]
serializer_class = ImageSerializer
is_private = True
ordering_fields = '__all__'
filterset_fields = [
'id',
'date',
'description',
]
def get_queryset(self):
"""
Only allow access to appropriate objects
"""
# REST API generation
if getattr(self, 'swagger_fake_view', False):
return Image.objects.none()
return Image.objects.filter(user=self.request.user)
def perform_create(self, serializer):
"""
Set the owner
"""
serializer.save(user=self.request.user)
| 1,897 | Python | .py | 55 | 30.145455 | 78 | 0.720219 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,405 | test_gallery_overview.py | wger-project_wger/wger/gallery/tests/test_gallery_overview.py | # 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
class GalleryAccessTestCase(WgerTestCase):
"""
Gallery tests
"""
def test_access_overview(self):
"""
Test accessing the gallery overview
"""
self.user_login('admin')
response = self.client.get(reverse('gallery:images:overview'))
self.assertEqual(response.status_code, 200)
self.user_login('test')
response = self.client.get(reverse('gallery:images:overview'))
self.assertEqual(response.status_code, 200)
self.user_logout()
response = self.client.get(reverse('gallery:images:overview'))
self.assertEqual(response.status_code, 302)
| 1,467 | Python | .py | 35 | 37.485714 | 78 | 0.732444 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,406 | test_gallery_image.py | wger-project_wger/wger/gallery/tests/test_gallery_image.py | # 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
import datetime
# wger
from wger.core.tests.base_testcase import (
WgerAddTestCase,
WgerDeleteTestCase,
)
from wger.gallery.models import Image
class AddGalleryImageTestCase(WgerAddTestCase):
"""
Tests adding an image to the gallery
"""
object_class = Image
url = 'gallery:images:add'
user_fail = False
data = {
'date': datetime.date(2021, 5, 1),
'user': 1,
'description': 'Everything going well',
'image': open('wger/exercises/tests/protestschwein.jpg', 'rb'),
}
class DeleteGalleryImageTestCase(WgerDeleteTestCase):
"""
Tests deleting a gallery image
"""
pk = 3
object_class = Image
url = 'gallery:images:delete'
user_success = 'test'
user_fail = 'admin'
# class EditGalleryImageTestCase(WgerEditTestCase):
# """
# Tests editing a gallery image
# """
#
# pk = 3
# object_class = Image
# url = 'gallery:images:edit'
# user_success = 'test'
# user_fail = 'admin'
# data = {'date': datetime.date(2021, 5, 1),
# 'user': 2,
# 'description': 'Everything going well',
# 'image': open('wger/exercises/tests/protestschwein.jpg', 'rb')}
| 1,947 | Python | .py | 58 | 30.62069 | 78 | 0.690426 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,407 | signals.py | wger-project_wger/wger/config/signals.py | # -*- 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
| 664 | Python | .py | 14 | 46.357143 | 78 | 0.781202 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,408 | urls.py | wger-project_wger/wger/config/urls.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.conf.urls import include
from django.urls import path
# wger
from wger.config.views import gym_config
# sub patterns for default gym
patterns_gym_config = [
path('edit', gym_config.GymConfigUpdateView.as_view(), name='edit'),
]
#
# Actual patterns
#
urlpatterns = [
path(
'gym-config/',
include((patterns_gym_config, 'gym_config'), namespace='gym_config'),
),
]
| 1,155 | Python | .py | 33 | 32.969697 | 78 | 0.750896 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,409 | apps.py | wger-project_wger/wger/config/apps.py | # -*- 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
# Django
from django.apps import AppConfig
class ConfigConfig(AppConfig):
name = 'wger.config'
verbose_name = 'Config'
def ready(self):
import wger.config.signals
| 851 | Python | .py | 21 | 38.333333 | 78 | 0.768485 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,410 | __init__.py | wger-project_wger/wger/config/__init__.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger import get_version
VERSION = get_version()
default_app_config = 'wger.config.apps.ConfigConfig'
| 854 | Python | .py | 19 | 43.736842 | 78 | 0.777377 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,411 | gym_config.py | wger-project_wger/wger/config/models/gym_config.py | # 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
import logging
# Django
from django.db import models
from django.utils.translation import gettext_lazy as _
# wger
from wger.core.models import UserProfile
from wger.gym.helpers import is_any_gym_admin
from wger.gym.models import (
Gym,
GymUserConfig,
)
logger = logging.getLogger(__name__)
class GymConfig(models.Model):
"""
System wide configuration for gyms
At the moment this only allows to set one gym as the default
TODO: close registration (users can only become members thorough an admin)
"""
default_gym = models.ForeignKey(
Gym,
verbose_name=_('Default gym'),
help_text=_(
'Select the default gym for this installation. '
'This will assign all new registered users to this '
'gym and update all existing users without a '
'gym.'
),
null=True,
blank=True,
on_delete=models.CASCADE,
)
"""
Default gym for the wger installation
"""
def __str__(self):
"""
Return a more human-readable representation
"""
return f'Default gym {self.default_gym}'
def save(self, *args, **kwargs):
"""
Perform additional tasks
"""
if self.default_gym:
# All users that have no gym set in the profile are edited
UserProfile.objects.filter(gym=None).update(gym=self.default_gym)
# All users in the gym must have a gym config
for profile in UserProfile.objects.filter(gym=self.default_gym):
user = profile.user
if not is_any_gym_admin(user):
try:
user.gymuserconfig
except GymUserConfig.DoesNotExist:
config = GymUserConfig()
config.gym = self.default_gym
config.user = user
config.save()
logger.debug(f'Creating GymUserConfig for user {user.username}')
return super(GymConfig, self).save(*args, **kwargs)
| 2,919 | Python | .py | 75 | 31.133333 | 88 | 0.644649 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,412 | __init__.py | wger-project_wger/wger/config/models/__init__.py | # 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/>.
# Local
from .gym_config import GymConfig
| 845 | Python | .py | 17 | 48.647059 | 79 | 0.769045 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,413 | 0003_delete_languageconfig.py | wger-project_wger/wger/config/migrations/0003_delete_languageconfig.py | # Generated by Django 4.1.7 on 2023-03-24 15:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('config', '0002_auto_20190618_1617'),
]
operations = [
migrations.DeleteModel(
name='LanguageConfig',
),
]
| 301 | Python | .py | 11 | 21.272727 | 47 | 0.636364 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,414 | 0002_auto_20190618_1617.py | wger-project_wger/wger/config/migrations/0002_auto_20190618_1617.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-06-18 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('config', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='languageconfig',
name='item',
field=models.CharField(
choices=[
('1', 'Exercises'),
('2', 'Ingredients'),
],
editable=False,
max_length=2,
),
),
]
| 594 | Python | .py | 21 | 17.952381 | 49 | 0.483304 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,415 | 0001_initial.py | wger-project_wger/wger/config/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('gym', '0001_initial'),
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='GymConfig',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'default_gym',
models.ForeignKey(
blank=True,
to='gym.Gym',
help_text='Select the default gym for this installation. This will assign all new registered users to this gym and update all existing users without a gym.',
null=True,
verbose_name='Default gym',
on_delete=models.CASCADE,
),
),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name='LanguageConfig',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'item',
models.CharField(
max_length=2,
editable=False,
choices=[(b'1', 'Exercises'), (b'2', 'Ingredients')],
),
),
('show', models.BooleanField(default=1)),
(
'language',
models.ForeignKey(
related_name='language_source',
editable=False,
to='core.Language',
on_delete=models.CASCADE,
),
),
(
'language_target',
models.ForeignKey(
related_name='language_target',
editable=False,
to='core.Language',
on_delete=models.CASCADE,
),
),
],
options={
'ordering': ['item', 'language_target'],
},
bases=(models.Model,),
),
]
| 2,594 | Python | .py | 75 | 17.053333 | 181 | 0.378926 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,416 | gym_config.py | wger-project_wger/wger/config/views/gym_config.py | # -*- 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.urls import reverse_lazy
from django.utils.translation import gettext_lazy
from django.views.generic import UpdateView
# wger
from wger.config.models import GymConfig
from wger.utils.generic_views import WgerFormMixin
logger = logging.getLogger(__name__)
class GymConfigUpdateView(WgerFormMixin, UpdateView):
"""
Generic view to edit the gym config table
"""
model = GymConfig
fields = ['default_gym']
permission_required = 'config.change_gymconfig'
success_url = reverse_lazy('gym:gym:list')
title = gettext_lazy('Edit')
def get_object(self):
"""
Return the only gym config object
"""
return GymConfig.objects.get(pk=1)
| 1,417 | Python | .py | 38 | 34.236842 | 78 | 0.756026 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,417 | test_gym_config.py | wger-project_wger/wger/config/tests/test_gym_config.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.contrib.auth.models import User
from django.urls import reverse
# wger
from wger.config.models import GymConfig
from wger.core.models import UserProfile
from wger.core.tests.base_testcase import WgerTestCase
from wger.gym.models import (
Gym,
GymUserConfig,
)
class GymConfigTestCase(WgerTestCase):
"""
Test the system wide gym configuration
"""
def test_default_gym(self):
"""
Test that newly registered users get a gym
"""
gym = Gym.objects.get(pk=2)
gym_config = GymConfig.objects.get(pk=1)
gym_config.default_gym = gym
gym_config.save()
# Register
registration_data = {
'username': 'myusername',
'password1': 'Aerieth4yuv5',
'password2': 'Aerieth4yuv5',
'email': 'my.email@example.com',
'g-recaptcha-response': 'PASSED',
}
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertEqual(response.status_code, 302)
new_user = User.objects.all().last()
self.assertEqual(new_user.userprofile.gym, gym)
self.assertEqual(new_user.gymuserconfig.gym, gym)
def test_no_default_gym(self):
"""
Test the user registration without a default gym
"""
gym_config = GymConfig.objects.get(pk=1)
gym_config.default_gym = None
gym_config.save()
# Register
registration_data = {
'username': 'myusername',
'password1': 'Iem2ahl1eizo',
'password2': 'Iem2ahl1eizo',
'email': 'my.email@example.com',
'g-recaptcha-response': 'PASSED',
}
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertEqual(response.status_code, 302)
new_user = User.objects.all().last()
self.assertEqual(new_user.userprofile.gym_id, None)
self.assertRaises(GymUserConfig.DoesNotExist, GymUserConfig.objects.get, user=new_user)
def test_update_userprofile(self):
"""
Test setting the gym for users when setting a default gym
"""
UserProfile.objects.update(gym=None)
GymUserConfig.objects.all().delete()
self.assertEqual(UserProfile.objects.exclude(gym=None).count(), 0)
gym = Gym.objects.get(pk=2)
gym_config = GymConfig.objects.get(pk=1)
gym_config.default_gym = gym
gym_config.save()
# 24 users in total
self.assertEqual(UserProfile.objects.filter(gym=gym).count(), 24)
# 13 non-managers
self.assertEqual(GymUserConfig.objects.filter(gym=gym).count(), 13)
| 3,457 | Python | .py | 86 | 33.22093 | 95 | 0.668953 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,418 | test_custom_header.py | wger-project_wger/wger/config/tests/test_custom_header.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.gym.models import Gym
class GymNameHeaderTestCase(WgerTestCase):
"""
Test case for showing gym name on application header
"""
def check_header(self, gym=None):
response = self.client.get(reverse('core:dashboard'))
self.assertEqual(response.context['custom_header'], gym)
def test_custom_header_gym_members(self):
"""
Test the custom header for gym members
"""
# Gym 1, custom header activated
gym = Gym.objects.get(pk=1)
self.assertTrue(gym.config.show_name)
for username in (
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
):
self.user_login(username)
self.check_header(gym=gym.name)
# Gym 2, custom header deactivated
gym = Gym.objects.get(pk=2)
self.assertFalse(gym.config.show_name)
for username in (
'trainer4',
'trainer5',
'demo',
'member6',
'member7',
):
self.user_login(username)
self.check_header(gym=None)
def test_custom_header_anonymous_user(self):
"""
Test the custom header for logged out users
"""
self.check_header(gym=None)
| 2,174 | Python | .py | 61 | 28.639344 | 78 | 0.647646 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,419 | models.py | wger-project_wger/wger/weight/models.py | # This file is part of wger Workout Manager <https://github.com/wger-project>.
# Copyright (C) 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.contrib.auth.models import User
from django.core.validators import (
MaxValueValidator,
MinValueValidator,
)
from django.db import models
from django.utils.translation import gettext_lazy as _
# 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
class WeightEntry(models.Model):
"""
Model for a weight point
"""
date = models.DateField(verbose_name=_('Date'))
weight = models.DecimalField(
verbose_name=_('Weight'),
max_digits=5,
decimal_places=2,
validators=[MinValueValidator(Decimal(30)), MaxValueValidator(Decimal(600))],
)
user = models.ForeignKey(
User,
verbose_name=_('User'),
on_delete=models.CASCADE,
)
"""
The user the weight entry belongs to.
NOTE: this field is neither marked as editable false nor is it excluded in
the form. This is done intentionally because otherwise it's *very* difficult
and ugly to validate the uniqueness of unique_together fields and one field
is excluded from the form. This does not pose any security risk because the
value from the form is ignored and the request's user always used.
"""
class Meta:
"""
Metaclass to set some other properties
"""
verbose_name = _('Weight entry')
ordering = [
'date',
]
get_latest_by = 'date'
unique_together = ('date', 'user')
def __str__(self):
"""
Return a more human-readable representation
"""
return '{0}: {1:.2f} kg'.format(self.date, self.weight)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
| 3,234 | Python | .py | 83 | 34.445783 | 85 | 0.708506 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,420 | urls.py | wger-project_wger/wger/weight/urls.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.contrib.auth.decorators import login_required
from django.urls import (
path,
re_path,
)
# wger
from wger.core.views.react import ReactView
from wger.weight import views
from wger.weight.forms import WeightCsvImportForm
urlpatterns = [
path(
'add/',
login_required(views.WeightAddView.as_view()),
name='add',
),
path(
'<int:pk>/edit/',
login_required(views.WeightUpdateView.as_view()),
name='edit',
),
path(
'<int:pk>/delete/',
views.WeightDeleteView.as_view(),
name='delete',
),
path(
'export-csv/',
views.export_csv,
name='export-csv',
),
path(
'import-csv/',
login_required(views.WeightCsvImportFormPreview(WeightCsvImportForm)),
name='import-csv',
),
re_path(
'overview',
ReactView.as_view(div_id='react-weight-overview'),
name='overview',
),
]
| 1,713 | Python | .py | 57 | 25.45614 | 78 | 0.6808 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,421 | __init__.py | wger-project_wger/wger/weight/__init__.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger import get_version
VERSION = get_version()
| 802 | Python | .py | 18 | 43.333333 | 78 | 0.774359 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,422 | helpers.py | wger-project_wger/wger/weight/helpers.py | # -*- 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 csv
import datetime
import decimal
import io
import json
import logging
from collections import OrderedDict
# Django
from django.core.cache import cache
# wger
from wger.manager.models import (
WorkoutLog,
WorkoutSession,
)
from wger.utils.cache import cache_mapper
from wger.utils.helpers import DecimalJsonEncoder
from wger.weight.models import WeightEntry
logger = logging.getLogger(__name__)
def parse_weight_csv(request, cleaned_data):
try:
dialect = csv.Sniffer().sniff(cleaned_data['csv_input'])
except csv.Error:
dialect = 'excel'
# csv.reader expects a file-like object, so use StringIO
parsed_csv = csv.reader(io.StringIO(cleaned_data['csv_input']), dialect)
distinct_weight_entries = []
entry_dates = set()
weight_list = []
error_list = []
MAX_ROW_COUNT = 1000
row_count = 0
# Process the CSV items first
for row in parsed_csv:
try:
parsed_date = datetime.datetime.strptime(row[0], cleaned_data['date_format'])
parsed_weight = decimal.Decimal(row[1].replace(',', '.'))
duplicate_date_in_db = WeightEntry.objects.filter(
date=parsed_date, user=request.user
).exists()
# within the list there are no duplicate dates
unique_among_csv = parsed_date not in entry_dates
# there is no existing weight entry in the database for that date
unique_in_db = not duplicate_date_in_db
if unique_among_csv and unique_in_db and parsed_weight:
distinct_weight_entries.append((parsed_date, parsed_weight))
entry_dates.add(parsed_date)
else:
error_list.append(row)
except (ValueError, IndexError, decimal.InvalidOperation):
error_list.append(row)
row_count += 1
if row_count > MAX_ROW_COUNT:
break
# Create the valid weight entries
for date, weight in distinct_weight_entries:
weight_list.append(WeightEntry(date=date, weight=weight, user=request.user))
return (weight_list, error_list)
def group_log_entries(user, year, month, day=None):
"""
Processes and regroups a list of log entries so they can be more easily
used in the different calendar pages
:param user: the user to filter the logs for
:param year: year
:param month: month
:param day: optional, day
:return: a dictionary with grouped logs by date and exercise
"""
if day:
log_hash = hash((user.pk, year, month, day))
else:
log_hash = hash((user.pk, year, month))
# There can be workout sessions without any associated log entries, so it is
# not enough so simply iterate through the logs
if day:
filter_date = datetime.date(year, month, day)
logs = WorkoutLog.objects.filter(user=user, date=filter_date)
sessions = WorkoutSession.objects.filter(user=user, date=filter_date)
else:
logs = WorkoutLog.objects.filter(user=user, date__year=year, date__month=month)
sessions = WorkoutSession.objects.filter(user=user, date__year=year, date__month=month)
logs = logs.order_by('date', 'id')
out = cache.get(cache_mapper.get_workout_log_list(log_hash))
# out = OrderedDict()
if not out:
out = OrderedDict()
# Logs
for entry in logs:
if not out.get(entry.date):
out[entry.date] = {
'date': entry.date,
'workout': entry.workout,
'session': entry.get_workout_session(),
'logs': OrderedDict(),
}
if not out[entry.date]['logs'].get(entry.exercise_base):
out[entry.date]['logs'][entry.exercise_base] = []
out[entry.date]['logs'][entry.exercise_base].append(entry)
# Sessions
for entry in sessions:
if not out.get(entry.date):
out[entry.date] = {
'date': entry.date,
'workout': entry.workout,
'session': entry,
'logs': {},
}
cache.set(cache_mapper.get_workout_log_list(log_hash), out)
return out
def process_log_entries(logs):
"""
Processes and regroups a list of log entries so they can be rendered
and passed to the D3 library to render a chart
"""
entry_log = OrderedDict()
entry_list = {}
chart_data = []
max_weight = {}
# Group by date
for entry in logs:
if not entry_log.get(entry.date):
entry_log[entry.date] = []
entry_log[entry.date].append(entry)
# Find the maximum weight per date per repetition.
# If on a day there are several entries with the same number of
# repetitions, but different weights, only the entry with the
# higher weight is shown in the chart
if not max_weight.get(entry.date):
max_weight[entry.date] = {entry.reps: entry.weight}
if not max_weight[entry.date].get(entry.reps):
max_weight[entry.date][entry.reps] = entry.weight
if entry.weight > max_weight[entry.date][entry.reps]:
max_weight[entry.date][entry.reps] = entry.weight
for entry in logs:
if not entry_list.get(entry.reps):
entry_list[entry.reps] = {'list': [], 'seen': []}
# Only add if weight is the maximum for the day
if entry.weight != max_weight[entry.date][entry.reps]:
continue
if (entry.date, entry.reps, entry.weight) in entry_list[entry.reps]['seen']:
continue
entry_list[entry.reps]['seen'].append((entry.date, entry.reps, entry.weight))
entry_list[entry.reps]['list'].append(
{'date': entry.date, 'weight': entry.weight, 'reps': entry.reps}
)
for rep in entry_list:
chart_data.append(entry_list[rep]['list'])
return entry_log, json.dumps(chart_data, cls=DecimalJsonEncoder)
def get_last_entries(user, amount=5):
"""
Get the last weight entries as well as the difference to the last
This can be used e.g. to present a list where the last entries and
their changes are presented.
"""
last_entries = WeightEntry.objects.filter(user=user).order_by('-date')[:5]
last_entries_details = []
for index, entry in enumerate(last_entries):
curr_entry = entry
prev_entry_index = index + 1
if prev_entry_index < len(last_entries):
prev_entry = last_entries[prev_entry_index]
else:
prev_entry = None
if prev_entry and curr_entry:
weight_diff = curr_entry.weight - prev_entry.weight
day_diff = (curr_entry.date - prev_entry.date).days
else:
weight_diff = day_diff = None
last_entries_details.append((curr_entry, weight_diff, day_diff))
return last_entries_details
| 7,665 | Python | .py | 184 | 33.657609 | 95 | 0.640926 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,423 | forms.py | wger-project_wger/wger/weight/forms.py | # -*- 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
# Django
from django import forms
from django.forms import (
CharField,
DateField,
Form,
ModelForm,
Textarea,
widgets,
)
from django.utils.translation import gettext as _
# Third Party
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout
# wger
from wger.utils.constants import DATE_FORMATS
from wger.utils.widgets import Html5DateInput
from wger.weight.models import WeightEntry
CSV_DATE_FORMAT = (
('%d.%m.%Y', 'DD.MM.YYYY (30.01.2012)'),
('%d.%m.%y', 'DD.MM.YY (30.01.12)'),
('%Y-%m-%d', 'YYYY-MM-DD (2012-01-30)'),
('%y-%m-%d', 'YY-MM-DD (12-01-30)'),
('%m/%d/%Y', 'MM/DD/YYYY (01/30/2012)'),
('%m/%d/%y', 'MM/DD/YY (01/30/12)'),
)
class WeightCsvImportForm(Form):
"""
A helper form with only a textarea
"""
csv_input = CharField(widget=Textarea, label=_('Input'))
date_format = forms.ChoiceField(choices=CSV_DATE_FORMAT, label=_('Date format'))
def __init__(self, *args, **kwargs):
super(WeightCsvImportForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
'csv_input',
'date_format',
)
self.helper.form_tag = False
class WeightForm(ModelForm):
date = DateField(input_formats=DATE_FORMATS, widget=Html5DateInput())
class Meta:
model = WeightEntry
exclude = []
widgets = {
'user': widgets.HiddenInput(),
}
| 2,144 | Python | .py | 62 | 30.322581 | 84 | 0.677466 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,424 | views.py | wger-project_wger/wger/weight/views.py | # -*- 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 csv
import datetime
import logging
# Django
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import (
HttpResponse,
HttpResponseRedirect,
)
from django.shortcuts import render
from django.urls import reverse
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import (
CreateView,
DeleteView,
UpdateView,
)
# Third Party
from formtools.preview import FormPreview
# wger
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
)
from wger.utils.helpers import check_access
from wger.weight import helpers
from wger.weight.forms import WeightForm
from wger.weight.models import WeightEntry
logger = logging.getLogger(__name__)
class WeightAddView(WgerFormMixin, CreateView):
"""
Generic view to add a new weight entry
"""
model = WeightEntry
form_class = WeightForm
title = gettext_lazy('Add weight entry')
def get_initial(self):
"""
Set the initial data for the form.
Read the comment on weight/models.py WeightEntry about why we need
to pass the user here.
"""
return {'user': self.request.user, 'date': datetime.date.today()}
def form_valid(self, form):
"""
Set the owner of the entry here
"""
form.instance.user = self.request.user
return super(WeightAddView, self).form_valid(form)
def get_success_url(self):
"""
Return to overview with username
"""
return reverse('weight:overview')
class WeightUpdateView(WgerFormMixin, LoginRequiredMixin, UpdateView):
"""
Generic view to edit an existing weight entry
"""
model = WeightEntry
form_class = WeightForm
def get_context_data(self, **kwargs):
context = super(WeightUpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit weight entry for the %s') % self.object.date
return context
def get_success_url(self):
"""
Return to overview with username
"""
return reverse('weight:overview')
class WeightDeleteView(WgerDeleteMixin, LoginRequiredMixin, DeleteView):
"""
Generic view to delete a weight entry
"""
model = WeightEntry
messages = gettext_lazy('Successfully deleted.')
def get_context_data(self, **kwargs):
context = super(WeightDeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete weight entry for the %s') % self.object.date
return context
def get_success_url(self):
"""
Return to overview with username
"""
return reverse('weight:overview')
@login_required
def export_csv(request):
"""
Exports the saved weight data as a CSV file
"""
# Prepare the response headers
response = HttpResponse(content_type='text/csv')
# Convert all weight data to CSV
writer = csv.writer(response)
weights = WeightEntry.objects.filter(user=request.user)
writer.writerow([_('Date'), _('Weight')])
for entry in weights:
writer.writerow([entry.date, entry.weight])
# Send the data to the browser
response['Content-Disposition'] = 'attachment; filename=Weightdata.csv'
response['Content-Length'] = len(response.content)
return response
class WeightCsvImportFormPreview(FormPreview):
preview_template = 'import_csv_preview.html'
form_template = 'import_csv_form.html'
def get_context(self, request, form):
"""
Context for template rendering.
"""
return {
'form': form,
'stage_field': self.unused_name('stage'),
'state': self.state,
}
def process_preview(self, request, form, context):
context['weight_list'], context['error_list'] = helpers.parse_weight_csv(
request, form.cleaned_data
)
return context
def done(self, request, cleaned_data):
weight_list, error_list = helpers.parse_weight_csv(request, cleaned_data)
WeightEntry.objects.bulk_create(weight_list)
return HttpResponseRedirect(reverse('weight:overview'))
| 4,933 | Python | .py | 141 | 29.602837 | 81 | 0.697097 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,425 | 0003_auto_20160416_1030.py | wger-project_wger/wger/weight/migrations/0003_auto_20160416_1030.py | # -*- coding: utf-8 -*-
from django.db import migrations, models
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('weight', '0002_auto_20150604_2139'),
]
operations = [
migrations.AlterField(
model_name='weightentry',
name='weight',
field=models.DecimalField(
decimal_places=2,
verbose_name='Weight',
validators=[
django.core.validators.MinValueValidator(30),
django.core.validators.MaxValueValidator(600),
],
max_digits=5,
),
),
]
| 682 | Python | .py | 22 | 20.363636 | 66 | 0.539634 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,426 | 0001_initial.py | wger-project_wger/wger/weight/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.conf import settings
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='WeightEntry',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('creation_date', models.DateField(verbose_name='Date')),
(
'weight',
models.DecimalField(
verbose_name='Weight',
max_digits=5,
decimal_places=2,
validators=[
django.core.validators.MinValueValidator(30),
django.core.validators.MaxValueValidator(300),
],
),
),
(
'user',
models.ForeignKey(
verbose_name='User', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE
),
),
],
options={
'ordering': ['creation_date'],
'get_latest_by': 'creation_date',
'verbose_name': 'Weight entry',
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='weightentry',
unique_together=set([('creation_date', 'user')]),
),
]
| 1,754 | Python | .py | 50 | 19.68 | 98 | 0.445882 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,427 | 0002_auto_20150604_2139.py | wger-project_wger/wger/weight/migrations/0002_auto_20150604_2139.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('weight', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='weightentry',
options={'verbose_name': 'Weight entry', 'get_latest_by': 'date', 'ordering': ['date']},
),
migrations.RenameField(
model_name='weightentry',
old_name='creation_date',
new_name='date',
),
migrations.AlterUniqueTogether(
name='weightentry',
unique_together=set([('date', 'user')]),
),
]
| 662 | Python | .py | 21 | 22.904762 | 100 | 0.55573 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,428 | serializers.py | wger-project_wger/wger/weight/api/serializers.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Third Party
from rest_framework import serializers
# wger
from wger.weight.models import WeightEntry
class WeightEntrySerializer(serializers.ModelSerializer):
"""
Weight serializer
"""
user = serializers.PrimaryKeyRelatedField(
read_only=True, default=serializers.CurrentUserDefault()
)
class Meta:
model = WeightEntry
fields = [
'id',
'date',
'weight',
'user',
]
| 1,215 | Python | .py | 34 | 31.470588 | 78 | 0.71891 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,429 | views.py | wger-project_wger/wger/weight/api/views.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Third Party
from rest_framework import viewsets
# wger
from wger.weight.api.serializers import WeightEntrySerializer
from wger.weight.models import WeightEntry
class WeightEntryViewSet(viewsets.ModelViewSet):
"""
API endpoint for nutrition plan objects
"""
serializer_class = WeightEntrySerializer
is_private = True
ordering_fields = '__all__'
filterset_fields = ('date', 'weight')
def get_queryset(self):
"""
Only allow access to appropriate objects
"""
# REST API generation
if getattr(self, 'swagger_fake_view', False):
return WeightEntry.objects.none()
return WeightEntry.objects.filter(user=self.request.user)
def perform_create(self, serializer):
"""
Set the owner
"""
serializer.save(user=self.request.user)
| 1,593 | Python | .py | 41 | 34.487805 | 78 | 0.725032 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,430 | test_email_weight_reminder.py | wger-project_wger/wger/weight/tests/test_email_weight_reminder.py | # 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
from datetime import (
datetime,
timedelta,
)
# Django
from django.contrib.auth.models import User
from django.core import mail
from django.core.management import call_command
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.weight.models import WeightEntry
class EmailWeightReminderTestCase(WgerTestCase):
def test_without_email(self):
user = User.objects.get(pk=2)
user.email = ''
user.num_days_weight_reminder = 3
user.save()
call_command('email-weight-reminder')
self.assertEqual(len(mail.outbox), 0)
def test_without_num_days_weight_reminder(self):
user = User.objects.get(pk=2)
user.email = 'test@test.com'
user.save()
user.userprofile.num_days_weight_reminder = 0
user.userprofile.save()
call_command('email-weight-reminder')
self.assertEqual(len(mail.outbox), 0)
def test_with_num_days_weight_reminder(self):
user = User.objects.get(pk=2)
user.email = 'test@test.com'
user.save()
user.userprofile.num_days_weight_reminder = 3
user.userprofile.save()
call_command('email-weight-reminder')
self.assertEqual(len(mail.outbox), 1)
def test_send_email(self):
user = User.objects.get(pk=2)
user.email = 'test@test.com'
user.save()
weightEntry = WeightEntry.objects.filter(user=user).get(pk=3)
weightEntry.date = datetime.now().date() - timedelta(days=2)
weightEntry.save()
user.userprofile.num_days_weight_reminder = 1
user.userprofile.save()
call_command('email-weight-reminder')
self.assertEqual(len(mail.outbox), 1)
def test_send_email_zero_days_diff(self):
user = User.objects.get(pk=2)
user.email = 'test@test.com'
user.save()
weightEntry = WeightEntry.objects.filter(user=user).get(pk=3)
weightEntry.date = datetime.now().date() - timedelta(days=1)
weightEntry.save()
user.userprofile.num_days_weight_reminder = 1
user.userprofile.save()
call_command('email-weight-reminder')
self.assertEqual(len(mail.outbox), 1)
def test_not_send_email(self):
user = User.objects.get(pk=2)
user.email = 'test@test.com.br'
user.save()
weightEntry = WeightEntry.objects.filter(user=user).latest()
weightEntry.date = datetime.now().date()
weightEntry.save()
user.userprofile.num_days_weight_reminder = 3
user.userprofile.save()
call_command('email-weight-reminder')
self.assertEqual(len(mail.outbox), 0)
| 3,330 | Python | .py | 82 | 34.04878 | 78 | 0.687035 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,431 | test_csv_import.py | wger-project_wger/wger/weight/tests/test_csv_import.py | # 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.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.weight.models import WeightEntry
logger = logging.getLogger(__name__)
class WeightCsvImportTestCase(WgerTestCase):
"""
Test case for the CSV import for weight entries
"""
def import_csv(self):
"""
Helper function to test the CSV import
"""
response = self.client.get(reverse('weight:import-csv'))
self.assertEqual(response.status_code, 200)
# Do a direct post request
# 1st step
count_before = WeightEntry.objects.count()
csv_input = """Datum Gewicht KJ
05.01.10 error here 111
22.01.aa 69,2 222
27.01.10 69,6 222
02.02.10 69 222
11.02.10 70,4 222
19.02.10 71 222
26.02.10 71,9 222
26.02.10 71,9 222
19.03.10 72 222"""
response = self.client.post(
reverse('weight:import-csv'),
{'stage': 1, 'csv_input': csv_input, 'date_format': '%d.%m.%y'},
)
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['weight_list']), 6)
self.assertEqual(len(response.context['error_list']), 4)
hash_value = response.context['hash_value']
# 2nd. step
response = self.client.post(
reverse('weight:import-csv'),
{'stage': 2, 'hash': hash_value, 'csv_input': csv_input, 'date_format': '%d.%m.%y'},
)
count_after = WeightEntry.objects.count()
self.assertEqual(response.status_code, 302)
self.assertGreater(count_after, count_before)
def test_import_csv_loged_in(self):
"""
Test deleting a category by a logged in user
"""
self.user_login('test')
self.import_csv()
| 2,447 | Python | .py | 66 | 31.666667 | 96 | 0.678783 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,432 | test_overview.py | wger-project_wger/wger/weight/tests/test_overview.py | # 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.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
logger = logging.getLogger(__name__)
class WeightOverviewTestCase(WgerTestCase):
"""
Test case for the weight overview page
"""
def weight_overview(self):
"""
Helper function to test the weight overview page
"""
response = self.client.get(reverse('weight:overview'))
self.assertEqual(response.status_code, 200)
def test_weight_overview_loged_in(self):
"""
Test the weight overview page by a logged in user
"""
self.user_login('test')
self.weight_overview()
class WeightExportCsvTestCase(WgerTestCase):
"""
Tests exporting the saved weight entries as a CSV file
"""
def csv_export(self):
"""
Helper function to test exporting the saved weight entries as a CSV file
"""
response = self.client.get(reverse('weight:export-csv'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'text/csv')
self.assertGreaterEqual(len(response.content), 120)
self.assertLessEqual(len(response.content), 150)
def test_csv_export_loged_in(self):
"""
Test exporting the saved weight entries as a CSV file by a logged in user
"""
self.user_login('test')
self.csv_export()
| 2,099 | Python | .py | 55 | 32.836364 | 81 | 0.705911 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,433 | test_csv_export.py | wger-project_wger/wger/weight/tests/test_csv_export.py | # 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.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
logger = logging.getLogger(__name__)
class WeightCsvExportTestCase(WgerTestCase):
"""
Test case for the CSV export for weight entries
"""
def export_csv(self):
"""
Helper function to test the CSV export
"""
response = self.client.get(reverse('weight:export-csv'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'text/csv')
self.assertEqual(response['Content-Disposition'], 'attachment; filename=Weightdata.csv')
self.assertGreaterEqual(len(response.content), 120)
self.assertLessEqual(len(response.content), 150)
def test_export_csv_logged_in(self):
"""
Test the CSV export for weight entries by a logged in user
"""
self.user_login('test')
self.export_csv()
| 1,618 | Python | .py | 40 | 35.875 | 96 | 0.728781 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,434 | test_generator.py | wger-project_wger/wger/weight/tests/test_generator.py | # 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.management import call_command
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.weight.models import WeightEntry
class WeightEntryGeneratorTestCase(WgerTestCase):
def test_generator(self):
# Arrange
WeightEntry.objects.all().delete()
# Act
call_command('dummy-generator-body-weight', '--nr-entries', 100)
# Assert
self.assertEqual(WeightEntry.objects.filter(user_id=1).count(), 100)
| 1,129 | Python | .py | 26 | 40.192308 | 78 | 0.766636 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,435 | test_entry.py | wger-project_wger/wger/weight/tests/test_entry.py | # 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 datetime
import decimal
# Django
from django.urls import reverse
# wger
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import (
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
WgerTestCase,
)
from wger.utils.constants import TWOPLACES
from wger.weight.models import WeightEntry
class MealRepresentationTestCase(WgerTestCase):
"""
Test the representation of a model
"""
def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual(str(WeightEntry.objects.get(pk=1)), '2012-10-01: 77.00 kg')
class AddWeightEntryTestCase(WgerAddTestCase):
"""
Tests adding a weight entry
"""
object_class = WeightEntry
url = 'weight:add'
user_fail = False
data = {
'weight': decimal.Decimal(81.1).quantize(TWOPLACES),
'date': datetime.date(2013, 2, 1),
'user': 1,
}
class EditWeightEntryTestCase(WgerEditTestCase):
"""
Tests editing a weight entry
"""
object_class = WeightEntry
url = 'weight:edit'
pk = 1
data = {
'weight': 100,
'date': datetime.date(2013, 2, 1),
'user': 1,
}
user_success = 'test'
user_fail = 'admin'
class DeleteWeightEntryTestCase(WgerDeleteTestCase):
"""
Tests deleting a weight entry
"""
object_class = WeightEntry
url = 'weight:delete'
pk = 1
user_success = 'test'
user_fail = 'admin'
class WeightEntryTestCase(api_base_test.ApiBaseResourceTestCase):
"""
Tests the weight entry overview resource
"""
pk = 3
resource = WeightEntry
private_resource = True
data = {'weight': 100, 'date': datetime.date(2013, 2, 1)}
| 2,429 | Python | .py | 80 | 26.0875 | 84 | 0.705277 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,436 | email-weight-reminder.py | wger-project_wger/wger/weight/management/commands/email-weight-reminder.py | # 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 datetime
# Django
from django.conf import settings
from django.contrib.sites.models import Site
from django.core import mail
from django.core.management.base import BaseCommand
from django.template import loader
from django.utils import translation
from django.utils.translation import gettext_lazy as _
# wger
from wger.core.models import UserProfile
from wger.weight.models import WeightEntry
class Command(BaseCommand):
"""
Helper admin command to send out email reminders
"""
help = 'Send out automatic emails to remind the user to enter the weight'
def handle(self, **options):
profile_list = UserProfile.objects.filter(num_days_weight_reminder__gt=0)
for profile in profile_list:
# Only continue if the user has provided an email address.
# Checking it here so we check for NULL values and emtpy strings
if not profile.user.email:
continue
today = datetime.datetime.now().date()
try:
last_entry = WeightEntry.objects.filter(user=profile.user).latest().date
datediff = (today - last_entry).days
if datediff >= profile.num_days_weight_reminder:
self.send_email(profile.user, last_entry, datediff)
except WeightEntry.DoesNotExist:
pass
@staticmethod
def send_email(user, last_entry, datediff):
"""
Notify a user to input the weight entry
:type user User
:type last_entry Date
"""
# Compose and send the email
translation.activate(user.userprofile.notification_language.short_name)
context = {
'site': Site.objects.get_current(),
'date': last_entry,
'days': datediff,
'user': user,
}
subject = _('You have to enter your weight')
message = loader.render_to_string('workout/email_weight_reminder.tpl', context)
mail.send_mail(
subject, message, settings.WGER_SETTINGS['EMAIL_FROM'], [user.email], fail_silently=True
)
| 2,779 | Python | .py | 66 | 35.106061 | 100 | 0.688172 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,437 | dummy-generator-body-weight.py | wger-project_wger/wger/weight/management/commands/dummy-generator-body-weight.py | # 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 datetime
import logging
import random
# Django
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
# wger
from wger.weight.models import WeightEntry
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Dummy generator for weight entries
"""
help = 'Dummy generator for weight entries'
def add_arguments(self, parser):
parser.add_argument(
'--nr-entries',
action='store',
default=40,
dest='nr_entries',
type=int,
help='The number of measurement entries per category (default: 40)',
)
parser.add_argument(
'--user-id',
action='store',
dest='user_id',
type=int,
help='Add only to the specified user-ID (default: all users)',
)
def handle(self, **options):
self.stdout.write(f"** Generating {options['nr_entries']} weight entries per user")
base_weight = 80
users = (
[User.objects.get(pk=options['user_id'])] if options['user_id'] else User.objects.all()
)
print(f"** Generating {options['nr_entries']} weight entries per user")
for user in users:
new_entries = []
self.stdout.write(f' - generating for {user.username}')
existing_entries = [i.date for i in WeightEntry.objects.filter(user=user)]
# Weight entries
for i in range(options['nr_entries']):
creation_date = datetime.date.today() - datetime.timedelta(days=i)
if creation_date not in existing_entries:
entry = WeightEntry(
user=user,
weight=base_weight + 0.5 * i + random.randint(1, 3),
date=creation_date,
)
new_entries.append(entry)
# Bulk-create the weight entries
WeightEntry.objects.bulk_create(new_entries)
| 2,709 | Python | .py | 67 | 31.776119 | 99 | 0.630095 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,438 | db.py | wger-project_wger/wger/utils/db.py | # 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.conf import settings
def is_postgres_db():
return 'postgres' in settings.DATABASES['default']['ENGINE']
| 771 | Python | .py | 17 | 43.941176 | 78 | 0.788282 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,439 | models.py | wger-project_wger/wger/utils/models.py | # This file is part of Workout Manager.
#
# 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.
#
# 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.db import models
from django.utils.translation import gettext_lazy as _
# wger
from wger.core.models import License
from wger.utils.constants import CC_BY_SA_4_ID
"""
Abstract model classes
"""
class AbstractLicenseModel(models.Model):
"""
Abstract class that adds license information to a model
Implements TASL (Title - Author - Source - License) for proper attribution
See also
- https://wiki.creativecommons.org/wiki/Recommended_practices_for_attribution
- https://wiki.creativecommons.org/wiki/Best_practices_for_attribution
"""
class Meta:
abstract = True
license = models.ForeignKey(
License,
verbose_name=_('License'),
default=CC_BY_SA_4_ID,
on_delete=models.CASCADE,
)
license_title = models.CharField(
verbose_name=_('The original title of this object, if available'),
max_length=300,
blank=True,
)
license_object_url = models.URLField(
verbose_name=_('Link to original object, if available'),
max_length=200,
blank=True,
)
license_author = models.TextField(
verbose_name=_('Author(s)'),
max_length=3500,
blank=True,
null=True,
help_text=_('If you are not the author, enter the name or source here.'),
)
license_author_url = models.URLField(
verbose_name=_('Link to author profile, if available'),
max_length=200,
blank=True,
)
license_derivative_source_url = models.URLField(
verbose_name=_('Link to the original source, if this is a derivative work'),
help_text=_(
'Note that a derivative work is one which is not only based on a previous '
'work, but which also contains sufficient new, creative content to entitle it '
'to its own copyright.'
),
max_length=200,
blank=True,
)
@property
def attribution_link(self):
out = ''
if self.license_object_url:
out += f'<a href="{self.license_object_url}">{self.license_title}</a>'
else:
out += self.license_title
out += ' by '
if self.license_author_url:
out += f'<a href="{self.license_author_url}">{self.license_author}</a>'
else:
out += self.license_author
out += f' is licensed under <a href="{self.license.url}">{self.license.short_name}</a>'
if self.license_derivative_source_url:
out += (
f'/ A derivative work from <a href="{self.license_derivative_source_url}">the '
f'original work</a>'
)
return out
class AbstractHistoryMixin:
"""
Abstract class used to model specific historical records.
Utilized in conjunction with simple_history's HistoricalRecords.
"""
@property
def author_history(self):
"""Author history is the unique set of license authors from historical records"""
return collect_model_author_history(self)
def collect_model_author_history(model):
"""
Get unique set of license authors from historical records from model.
"""
out = set()
for author in [h.license_author for h in set(model.history.all()) if h.license_author]:
out.add(author)
return out
def collect_models_author_history(model_list):
"""
Get unique set of license authors from historical records from models.
"""
out = set()
for model in model_list:
out = out.union(collect_model_author_history(model))
return out
| 4,226 | Python | .py | 114 | 30.587719 | 95 | 0.664462 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,440 | api_token.py | wger-project_wger/wger/utils/api_token.py | # 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
# Third Party
from rest_framework.authtoken.models import Token
logger = logging.getLogger(__name__)
def create_token(user, force_new=False):
"""
Creates a new token for a user or returns the existing one.
:param user: User object
:param force_new: forces creating a new token
"""
token = False
try:
token = Token.objects.get(user=user)
except Token.DoesNotExist:
force_new = True
if force_new:
if token:
token.delete()
token = Token.objects.create(user=user)
return token
| 1,240 | Python | .py | 34 | 32.705882 | 78 | 0.738294 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,441 | pdf.py | wger-project_wger/wger/utils/pdf.py | # 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 datetime
from os.path import join as path_join
# Django
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.utils import translation
# Third Party
from reportlab.lib import colors
from reportlab.lib.colors import HexColor
from reportlab.lib.styles import (
ParagraphStyle,
StyleSheet1,
)
from reportlab.lib.units import cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
Image,
Paragraph,
)
# wger
from wger import get_version
from wger.core.models import Language
# ************************
# Language functions
# ************************
def load_language():
"""
Returns the currently used language, e.g. to load appropriate exercises
"""
# TODO: perhaps store a language preference in the user's profile?
# Read the first part of a composite language, e.g. 'de-at'
used_language = translation.get_language().split('-')[0]
try:
language = Language.objects.get(short_name=used_language)
# No luck, load english as our fall-back language
except ObjectDoesNotExist:
language = Language.objects.get(short_name='en')
return language
def render_footer(url, date=None):
"""
Renders the footer used in the different PDFs
:return: a Paragraph object
"""
if not date:
date = datetime.date.today().strftime('%d.%m.%Y')
p = Paragraph(
f"""<para>
{date} - <a href="{url}">{url}</a> - wger Workout Manager {get_version()}
</para>""",
styleSheet['Normal'],
)
return p
def get_logo(width=1.5):
"""
Returns the wger logo
"""
image = Image(path_join(settings.SITE_ROOT, 'core/static/images/logos/logo.png'))
image.drawHeight = width * cm * image.drawHeight / image.drawWidth
image.drawWidth = width * cm
return image
# register new truetype fonts for reportlab
pdfmetrics.registerFont(
TTFont('OpenSans', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Light.ttf'))
)
pdfmetrics.registerFont(
TTFont('OpenSans-Bold', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Bold.ttf'))
)
pdfmetrics.registerFont(
TTFont(
'OpenSans-Regular', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Regular.ttf')
)
)
pdfmetrics.registerFont(
TTFont(
'OpenSans-Italic',
path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-LightItalic.ttf'),
)
)
styleSheet = StyleSheet1()
styleSheet.add(
ParagraphStyle(
name='Normal',
fontName='OpenSans',
fontSize=10,
leading=12,
)
)
styleSheet.add(
ParagraphStyle(
parent=styleSheet['Normal'],
fontSize=8,
name='Small',
)
)
styleSheet.add(
ParagraphStyle(
parent=styleSheet['Normal'],
fontSize=7,
name='ExerciseComments',
fontName='OpenSans-Italic',
)
)
styleSheet.add(
ParagraphStyle(
parent=styleSheet['Normal'],
name='HeaderBold',
fontSize=16,
fontName='OpenSans-Bold',
)
)
styleSheet.add(
ParagraphStyle(
parent=styleSheet['Normal'],
name='SubHeader',
fontName='OpenSans-Bold',
textColor=colors.white,
)
)
styleSheet.add(
ParagraphStyle(
parent=styleSheet['Normal'],
name='SubHeaderBlack',
fontName='OpenSans-Bold',
textColor=colors.black,
)
)
header_colour = HexColor(0x24416B)
row_color = HexColor(0xD1DEF0)
| 4,218 | Python | .py | 143 | 25.104895 | 99 | 0.695856 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,442 | viewsets.py | wger-project_wger/wger/utils/viewsets.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Third Party
from rest_framework import (
exceptions,
viewsets,
)
class WgerOwnerObjectModelViewSet(viewsets.ModelViewSet):
"""
Custom viewset that makes sure the user can only create objects for himself
"""
def create(self, request, *args, **kwargs):
"""
Check for creation (PUT, POST)
"""
for entry in self.get_owner_objects():
if request.data.get(entry[1]):
pk = request.data.get(entry[1])
obj = entry[0].objects.get(pk=pk)
if obj.get_owner_object().user != request.user:
raise exceptions.PermissionDenied('You are not allowed to do this')
else:
return super().create(request, *args, **kwargs)
def update(self, request, *args, **kwargs):
"""
Check for updates (PUT, PATCH)
"""
for entry in self.get_owner_objects():
if request.data.get(entry[1]):
pk = request.data.get(entry[1])
obj = entry[0].objects.get(pk=pk)
if obj.get_owner_object().user != request.user:
raise exceptions.PermissionDenied('You are not allowed to do this')
else:
return super().update(request, *args, **kwargs)
| 2,023 | Python | .py | 48 | 34.9375 | 87 | 0.648553 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,443 | language.py | wger-project_wger/wger/utils/language.py | # 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.core.cache import cache
from django.utils import translation
# wger
from wger.core.models import Language
from wger.utils.cache import cache_mapper
from wger.utils.constants import ENGLISH_SHORT_NAME
logger = logging.getLogger(__name__)
def load_language(language_code=None):
"""
Returns the currently used language, e.g. to load appropriate exercises
"""
# Read the first part of a composite language, e.g. 'de-at'
used_language = (
translation.get_language().split('-')[0] if language_code is None else language_code
)
language = cache.get(cache_mapper.get_language_key(used_language))
if language:
return language
try:
language = Language.objects.get(short_name=used_language)
except Language.DoesNotExist:
language = Language.objects.get(short_name=ENGLISH_SHORT_NAME)
cache.set(cache_mapper.get_language_key(language.short_name), language)
return language
def get_language_data(language):
return {
'name': language[1],
'code': language[0],
'path': f'images/icons/flags/{language[0]}.svg',
}
| 1,815 | Python | .py | 46 | 35.73913 | 92 | 0.745444 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,444 | constants.py | wger-project_wger/wger/utils/constants.py | # 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
from decimal import Decimal
# Navigation
WORKOUT_TAB = 'workout'
EXERCISE_TAB = 'exercises'
WEIGHT_TAB = 'weight'
NUTRITION_TAB = 'nutrition'
SOFTWARE_TAB = 'software'
USER_TAB = 'user'
# Default quantization
TWOPLACES = Decimal('0.01')
FOURPLACES = Decimal('0.0001')
# Valid date formats
DATE_FORMATS = [
'%d.%m.%Y', # '25.10.2012'
'%d.%m.%y', # '25.10.12'
'%m/%d/%Y', # '10/25/2012'
'%m/%d/%y', # '10/25/12'
'%Y-%m-%d', # '2012-10-25'
]
# Allowed tags, attributes and styles allowed in textareas edited with a JS
# editor. Everything not in these whitelists is stripped.
HTML_TAG_WHITELIST = {'b', 'i', 'strong', 'em', 'ul', 'ol', 'li', 'p'}
HTML_ATTRIBUTES_WHITELIST = {'*': 'style'}
HTML_STYLES_WHITELIST = ('text-decoration',)
# Pagination
PAGINATION_OBJECTS_PER_PAGE = 25
PAGINATION_MAX_TOTAL_PAGES = 10
PAGINATION_PAGES_AROUND_CURRENT = 5
# Important license IDs
CC_BY_SA_4_ID = 2
CC_BY_SA_3_LICENSE_ID = 1
CC_0_LICENSE_ID = 3
ODBL_LICENSE_ID = 5
# Default/fallback language
ENGLISH_SHORT_NAME = 'en'
# Possible values for ingredient image download
DOWNLOAD_INGREDIENT_WGER = 'WGER'
DOWNLOAD_INGREDIENT_OFF = 'OFF'
DOWNLOAD_INGREDIENT_NONE = 'None'
DOWNLOAD_INGREDIENT_OPTIONS = (
DOWNLOAD_INGREDIENT_WGER,
DOWNLOAD_INGREDIENT_OFF,
DOWNLOAD_INGREDIENT_NONE,
)
# API
API_MAX_ITEMS = 999
SEARCH_ALL_LANGUAGES = '*'
| 2,026 | Python | .py | 61 | 31.508197 | 78 | 0.733367 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,445 | url.py | wger-project_wger/wger/utils/url.py | # 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
from typing import (
Dict,
Optional,
)
from urllib.parse import (
urlparse,
urlunparse,
)
# Django
from django.conf import settings
def make_uri(
path: str,
id: Optional[int] = None,
object_method: Optional[str] = None,
query: Optional[Dict[str, any]] = None,
server_url: str = settings.WGER_SETTINGS['WGER_INSTANCE'],
):
uri_server = urlparse(server_url)
query = query or {}
path_list = [uri_server.path, 'api', 'v2', path]
if id is not None:
path_list.append(str(id))
if object_method is not None:
path_list.append(object_method)
uri = urlunparse(
(
uri_server.scheme,
uri_server.netloc,
'/'.join(path_list) + '/',
'',
'&'.join([f'{key}={value}' for key, value in query.items()]),
'',
)
)
return uri
| 1,540 | Python | .py | 49 | 26.755102 | 78 | 0.670263 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,446 | cache.py | wger-project_wger/wger/utils/cache.py | # 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.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
logger = logging.getLogger(__name__)
def delete_template_fragment_cache(fragment_name='', vary_on=None):
"""
Deletes a cache key created on the template with django's cache tag
"""
out = vary_on if isinstance(vary_on, (list, tuple)) else [vary_on]
cache.delete(make_template_fragment_key(fragment_name, out))
def reset_workout_canonical_form(workout_id):
cache.delete(cache_mapper.get_workout_canonical(workout_id))
def reset_exercise_api_cache(uuid: str):
cache.delete(cache_mapper.get_exercise_api_key(uuid))
def reset_workout_log(user_pk, year, month, day=None):
"""
Resets the cached workout logs
"""
log_hash = hash((user_pk, year, month))
cache.delete(cache_mapper.get_workout_log_list(log_hash))
log_hash = hash((user_pk, year, month, day))
cache.delete(cache_mapper.get_workout_log_list(log_hash))
class CacheKeyMapper:
"""
Simple class for mapping the cache keys of different objects
"""
# Keys used by the cache
LANGUAGE_CACHE_KEY = 'language-{0}'
INGREDIENT_CACHE_KEY = 'ingredient-{0}'
WORKOUT_CANONICAL_REPRESENTATION = 'workout-canonical-representation-{0}'
WORKOUT_LOG_LIST = 'workout-log-hash-{0}'
NUTRITION_CACHE_KEY = 'nutrition-cache-log-{0}'
EXERCISE_API_KEY = 'base-uuid-{0}'
def get_pk(self, param):
"""
Small helper function that returns the PK for the given parameter
"""
return param.pk if hasattr(param, 'pk') else param
def get_language_key(self, param):
"""
Return the language cache key
"""
return self.LANGUAGE_CACHE_KEY.format(self.get_pk(param))
def get_ingredient_key(self, param):
"""
Return the ingredient cache key
"""
return self.INGREDIENT_CACHE_KEY.format(self.get_pk(param))
def get_workout_canonical(self, param):
"""
Return the workout canonical representation
"""
return self.WORKOUT_CANONICAL_REPRESENTATION.format(self.get_pk(param))
def get_workout_log_list(self, hash_value):
"""
Return the workout canonical representation
"""
return self.WORKOUT_LOG_LIST.format(hash_value)
def get_nutrition_cache_by_key(self, params):
"""
get nutritional info values canonical representation using primary key.
"""
return self.NUTRITION_CACHE_KEY.format(self.get_pk(params))
@classmethod
def get_exercise_api_key(cls, base_uuid: str):
"""
get the exercise base cache key used in the API
"""
return cls.EXERCISE_API_KEY.format(base_uuid)
cache_mapper = CacheKeyMapper()
| 3,463 | Python | .py | 85 | 35.294118 | 80 | 0.700179 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,447 | __init__.py | wger-project_wger/wger/utils/__init__.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger import get_version
VERSION = get_version()
| 802 | Python | .py | 18 | 43.333333 | 78 | 0.774359 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,448 | requests.py | wger-project_wger/wger/utils/requests.py | # 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
# Third Party
import requests
# wger
from wger import get_version
def wger_user_agent():
return f'wger/{get_version()} - https://github.com/wger-project'
def wger_headers():
return {'User-Agent': wger_user_agent()}
def get_all_paginated(url: str, headers=None):
"""
Fetch all results from a paginated endpoint.
:param url: The URL to fetch from.
:param headers: Optional headers to send with the request.
:return: A list of all results.
"""
if headers is None:
headers = {}
results = []
while True:
response = requests.get(url, headers=headers).json()
url = response['next']
results.extend(response['results'])
if not url:
break
return results
def get_paginated(url: str, headers=None):
"""
Generator that iterates over a paginated endpoint
:param url: The URL to fetch from.
:param headers: Optional headers to send with the request.
:return: Generator with the contents of the 'result' key
"""
if headers is None:
headers = {}
while True:
response = requests.get(url, headers=headers).json()
for result in response['results']:
yield result
url = response['next']
if not url:
break
| 1,935 | Python | .py | 54 | 30.888889 | 78 | 0.694206 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,449 | middleware.py | wger-project_wger/wger/utils/middleware.py | # 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
"""
Custom middleware
"""
# Standard Library
import logging
# Django
from django.conf import settings
from django.contrib import auth
from django.contrib.auth import login as django_login
from django.utils.deprecation import MiddlewareMixin
from django.utils.functional import SimpleLazyObject
# wger
from wger.core.demo import create_temporary_user
logger = logging.getLogger(__name__)
SPECIAL_PATHS = ('dashboard',)
def check_current_request(request):
"""
Simple helper function that checks whether the current request hit one
of the 'special' paths (paths that need a logged in user).
"""
# Don't create guest users for requests that are accessing the site
# through the REST API
if 'api' in request.path:
return False
# Other paths
match = False
for path in SPECIAL_PATHS:
if path in request.path:
match = True
return match
def get_user(request):
if not hasattr(request, '_cached_user'):
create_user = check_current_request(request)
user = auth.get_user(request)
# Set the flag in the session
if not request.session.get('has_demo_data'):
request.session['has_demo_data'] = False
# Django didn't find a user, so create one now
if (
settings.WGER_SETTINGS['ALLOW_GUEST_USERS']
and request.method == 'GET'
and create_user
and not user.is_authenticated
):
logger.debug('creating a new guest user now')
user = create_temporary_user(request)
django_login(request, user)
request._cached_user = user
return request._cached_user
class WgerAuthenticationMiddleware(MiddlewareMixin):
"""
Small wrapper around django's own AuthenticationMiddleware. Simply creates
a new user with a temporary flag if the user hits certain URLs that need
a logged in user
"""
def process_request(self, request):
assert hasattr(request, 'session'), 'The Django authentication middleware requires '
'session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert'
"'django.contrib.sessions.middleware.SessionMiddleware'."
request.user = SimpleLazyObject(lambda: get_user(request))
class RobotsExclusionMiddleware(MiddlewareMixin):
"""
Simple middleware that sends the "X-Robots-Tag" tag for the URLs used in
our WgerAuthenticationMiddleware so that those pages are not indexed.
"""
def process_response(self, request, response):
# Don't set it if it's already in the response
if check_current_request(request) and response.get('X-Robots-Tag', None) is None:
response['X-Robots-Tag'] = 'noindex, nofollow'
return response
class JavascriptAJAXRedirectionMiddleware(MiddlewareMixin):
"""
Middleware that sends helper headers when working with AJAX.
This is used for AJAX forms due to limitations of javascript. The way it
was done before was to load the whole redirected page, then read from a DIV
in the page and redirect to that URL. This now just sends a header when the
form was called via the JS function wgerFormModalDialog() and no errors are
present.
"""
def process_response(self, request, response):
if request.META.get('HTTP_X_WGER_NO_MESSAGES') and b'has-error' not in response.content:
logger.debug('Sending X-wger-redirect')
response['X-wger-redirect'] = request.path
response.content = request.path
return response
| 4,224 | Python | .py | 98 | 37.346939 | 96 | 0.716829 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,450 | generic_views.py | wger-project_wger/wger/utils/generic_views.py | # -*- 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 import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.http import (
HttpResponseForbidden,
HttpResponseRedirect,
)
from django.urls import reverse_lazy
from django.utils.text import slugify
from django.utils.translation import gettext_lazy
from django.views.generic import TemplateView
from django.views.generic.edit import ModelFormMixin
# Third Party
import bleach
from bleach.css_sanitizer import CSSSanitizer
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
ButtonHolder,
Layout,
Submit,
)
# wger
from wger.utils.constants import (
HTML_ATTRIBUTES_WHITELIST,
HTML_STYLES_WHITELIST,
HTML_TAG_WHITELIST,
)
logger = logging.getLogger(__name__)
class WgerMultiplePermissionRequiredMixin(PermissionRequiredMixin):
"""
A PermissionRequiredMixin that checks that the user has at least one permission
instead of all of them.
"""
def has_permission(self):
for permission in self.get_permission_required():
if self.request.user.has_perm(permission):
return True
return False
class WgerPermissionMixin:
"""
Custom permission mixim
This simply checks that the user has the given permissions to access a
resource and makes writing customized generic views easier.
"""
permission_required = False
"""
The name of the permission required to access this class.
This can be a string or a tuple, in the latter case having any of the permissions
listed is enough to access the resource
"""
login_required = False
"""
Set to True to restrict view to logged in users
"""
def dispatch(self, request, *args, **kwargs):
"""
Check permissions and dispatch
"""
if self.login_required or self.permission_required:
if not request.user.is_authenticated:
return HttpResponseRedirect(
reverse_lazy('core:user:login') + f'?next={request.path}'
)
if self.permission_required:
has_permission = False
if isinstance(self.permission_required, tuple):
for permission in self.permission_required:
if request.user.has_perm(permission):
has_permission = True
elif request.user.has_perm(self.permission_required):
has_permission = True
if not has_permission:
return HttpResponseForbidden('You are not allowed to access this object')
# Dispatch normally
return super(WgerPermissionMixin, self).dispatch(request, *args, **kwargs)
# , PermissionRequiredMixin
class WgerFormMixin(ModelFormMixin):
template_name = 'form.html'
custom_js = ''
"""
Custom javascript to be executed.
"""
form_action = ''
form_action_urlname = ''
sidebar = ''
"""
Name of a template that will be included in the sidebar
"""
title = ''
"""
Title used in the form
"""
owner_object = False
"""
The object that holds the owner information. This only needs to be set if
the model doesn't provide a get_owner_object() method
"""
submit_text = gettext_lazy('Save')
"""
Text used in the submit button, default _('save')
"""
clean_html = ()
"""
List of form fields that should be passed to bleach to clean the html
"""
messages = ''
"""
A message to display on success
"""
def get_context_data(self, **kwargs):
"""
Set context data
"""
context = super(WgerFormMixin, self).get_context_data(**kwargs)
context['sidebar'] = self.sidebar
context['title'] = self.title
# Custom JS code on form (autocompleter, editor, etc.)
context['custom_js'] = self.custom_js
return context
def dispatch(self, request, *args, **kwargs):
"""
Custom dispatch method.
This basically only checks for ownerships of editable/deletable
objects and return a HttpResponseForbidden response if the user
is not the owner.
"""
# These seem to be necessary for calling get_object
self.kwargs = kwargs
self.request = request
# For new objects, we have to manually load the owner object
if self.owner_object:
owner_object = self.owner_object['class'].objects.get(
pk=kwargs[self.owner_object['pk']]
)
else:
# On CreateViews we don't have an object, so just ignore it
try:
owner_object = self.get_object().get_owner_object()
except AttributeError:
owner_object = False
# Nothing to see, please move along
if owner_object and owner_object.user != self.request.user:
return HttpResponseForbidden('You are not allowed to access this object')
# Dispatch normally
return super(WgerFormMixin, self).dispatch(request, *args, **kwargs)
def get_messages(self):
"""
Getter for success message. Can be overwritten to e.g. to provide the
name of the object.
"""
return self.messages
def get_form(self, form_class=None):
"""Return an instance of the form to be used in this view."""
form = super(WgerFormMixin, self).get_form(form_class)
if not hasattr(form, 'helper'):
form.helper = FormHelper()
form.helper.form_id = slugify(self.request.path)
form.helper.form_method = 'post'
form.helper.form_action = self.request.path
form.helper.add_input(Submit('submit', self.submit_text, css_class='btn-success btn-block'))
form.helper.form_class = 'wger-form'
return form
def form_invalid(self, form):
"""
Log form errors to the console
"""
logger.debug(form.errors)
return super(WgerFormMixin, self).form_invalid(form)
def form_valid(self, form):
"""
Pre-process the form, cleaning up the HTML code found in the fields
given in clean_html. All HTML tags, attributes and styles not in the
whitelists are stripped from the output, leaving only the text content:
<table><tr><td>foo</td></tr></table> simply becomes 'foo'
"""
for field in self.clean_html:
setattr(
form.instance,
field,
bleach.clean(
getattr(form.instance, field),
tags=HTML_TAG_WHITELIST,
attributes=HTML_ATTRIBUTES_WHITELIST,
css_sanitizer=CSSSanitizer(allowed_css_properties=HTML_STYLES_WHITELIST),
strip=True,
),
)
if self.get_messages():
messages.success(self.request, self.get_messages())
return super(WgerFormMixin, self).form_valid(form)
class WgerDeleteMixin:
form_action = ''
form_action_urlname = ''
title = ''
delete_message_extra = ''
delete_message = gettext_lazy('Yes, delete')
template_name = 'delete.html'
messages = ''
def get_context_data(self, **kwargs):
"""
Set necessary template data to correctly render the form
"""
# Call the base implementation first to get a context
context = super(WgerDeleteMixin, self).get_context_data(**kwargs)
# Set the title
context['title'] = self.title
# Additional delete message
context['delete_message'] = self.delete_message_extra
return context
def get_form(self, form_class=None):
"""Return an instance of the form to be used in this view."""
form = super(WgerDeleteMixin, self).get_form(form_class)
if not hasattr(form, 'helper'):
form.helper = FormHelper()
form.helper.form_id = slugify(self.request.path)
form.helper.form_method = 'post'
form.helper.form_action = self.request.path
form.helper.layout = Layout(
ButtonHolder(Submit('submit', self.delete_message, css_class='btn-warning btn-block'))
)
return form
def dispatch(self, request, *args, **kwargs):
"""
Custom dispatch method.
This basically only checks for ownerships of editable/deletable
objects and return a HttpResponseForbidden response if the user
is not the owner.
"""
# These seem to be necessary if for calling get_object
self.kwargs = kwargs
self.request = request
owner_object = self.get_object().get_owner_object()
# Nothing to see, please move along
if owner_object and owner_object.user != self.request.user:
return HttpResponseForbidden()
# Dispatch normally
return super(WgerDeleteMixin, self).dispatch(request, *args, **kwargs)
def get_messages(self):
"""
Getter for success message. Can be overwritten to e.g. to provide the
name of the object.
"""
return self.messages
def delete(self, request, *args, **kwargs):
"""
Show a message on successful delete
"""
if self.get_messages():
messages.success(request, self.get_messages())
return super(WgerDeleteMixin, self).delete(request, *args, **kwargs)
class TextTemplateView(TemplateView):
"""
A regular templateView that sets the mime type as text/plain
"""
def dispatch(self, request, *args, **kwargs):
resp = super().dispatch(request, args, kwargs)
resp['Content-Type'] = 'text/plain'
return resp
| 10,527 | Python | .py | 274 | 30.430657 | 100 | 0.644807 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,451 | units.py | wger-project_wger/wger/utils/units.py | # 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
from decimal import Decimal
# wger
from wger.utils.constants import FOURPLACES
logger = logging.getLogger(__name__)
"""
Weight and height unit classes
"""
class AbstractWeight:
"""
Helper class to use when working with sensible (kg) or imperial units.
Internally, all values are stored as kilograms and are converted only if
needed. For consistency, all results are converted to python decimal and
quantized to four places
"""
KG_IN_LBS = Decimal(2.20462262)
LB_IN_KG = Decimal(0.45359237)
weight = 0
is_kg = True
def __init__(self, weight, mode='kg'):
"""
:param weight: the numerical weight
:param mode: the mode, values 'kg' (default), 'g', 'lb' and 'oz' are supported
"""
weight = self.normalize(weight)
if mode == 'g':
weight /= Decimal(1000)
elif mode == 'oz':
weight /= Decimal(16.0)
self.weight = weight
self.is_kg = mode in ('kg', 'g')
def __add__(self, other):
"""
Implement adding abstract weights.
For simplicity, the sum always occurs in kg
"""
return AbstractWeight(self.kg + other.kg)
@staticmethod
def normalize(value):
"""
Helper method that returns quantized
:param value:
:return: a quantized value to four decimal places
"""
return Decimal(value).quantize(FOURPLACES)
@property
def kg(self):
"""
Return the weight in kilograms
:return: decimal
"""
if self.is_kg:
return self.normalize(self.weight)
else:
return self.normalize(self.weight * self.LB_IN_KG)
@property
def g(self):
"""
Return the weight in grams
:return: decimal
"""
return self.normalize(self.kg * 1000)
@property
def lb(self):
"""
Return the weight in pounds
:return: decimal
"""
if self.is_kg:
return self.normalize(self.weight * self.KG_IN_LBS)
else:
return self.normalize(self.weight)
@property
def oz(self):
"""
Return the weight in ounces
:return: decimal
"""
return self.normalize(self.lb * 16)
class AbstractHeight(object):
"""
Helper class to use when working with sensible (cm) or imperial units.
Internally, all values are stored as cm and are converted only if
needed. For consistency, all results are converted to python decimal and
quantized to four places
"""
CM_IN_INCHES = Decimal(0.393701)
INCHES_IN_CM = Decimal(2.5400)
height = 0
is_cm = True
def __init__(self, height, mode='cm'):
"""
:param height: the numerical height
:param mode: the mode, values 'cm' (default), 'inches' are supported
"""
height = self.normalize(height)
self.height = height
self.is_cm = mode == 'cm'
@staticmethod
def normalize(value):
"""
Helper method that returns quantized
:param value:
:return: a quantized value to four decimal places
"""
return Decimal(value).quantize(FOURPLACES)
@property
def cm(self):
"""
Return the height in cm
:return: decimal
"""
if self.is_cm:
return self.normalize(self.height)
else:
return self.normalize(self.height * self.INCHES_IN_CM)
@property
def inches(self):
"""
Return the height in inches
:return: decimal
"""
if self.is_cm:
return self.normalize(self.height * self.CM_IN_INCHES)
else:
return self.normalize(self.height)
| 4,464 | Python | .py | 140 | 24.821429 | 86 | 0.625379 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,452 | widgets.py | wger-project_wger/wger/utils/widgets.py | # -*- 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
# 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
# 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 _
logger = logging.getLogger(__name__)
#
# Date and time related fields
#
class Html5DateInput(DateInput):
"""
Custom Input class that is rendered with an HTML5 type="date"
"""
template_name = 'forms/html5_date.html'
input_type = 'date'
def get_context(self, name, value, attrs):
"""Pass the value as a date to the template. This is necessary because
django's default behaviour is to convert it to a string, where it can't
be formatted anymore."""
context = super(Html5DateInput, self).get_context(name, value, attrs)
context['widget']['orig_value'] = value
return context
class Html5FormDateField(fields.DateField):
"""
HTML5 form date field
"""
widget = Html5DateInput
class Html5TimeInput(TextInput):
"""
Custom Input class that is rendered with an HTML5 type="time"
This is specially useful in mobile devices and not available
with older versions of django.
"""
input_type = 'time'
class Html5FormTimeField(fields.TimeField):
"""
HTML5 form time field
"""
widget = Html5TimeInput
#
# Number related fields
#
class Html5NumberInput(TextInput):
"""
Custom Input class that is rendered with an HTML5 type="number"
This is specially useful in mobile devices and not available
with older versions of django.
"""
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
"""
def render_option(self, selected_choices, option_value, option_label):
return super(TranslatedSelect, self).render_option(
selected_choices, option_value, _(option_label)
)
| 6,752 | Python | .py | 182 | 30.351648 | 94 | 0.673382 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,453 | context_processor.py | wger-project_wger/wger/utils/context_processor.py | # 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.conf import settings
from django.templatetags.static import static
from django.utils.translation import get_language
# wger
from wger.config.models import GymConfig
from wger.utils import constants
from wger.utils.constants import ENGLISH_SHORT_NAME
from wger.utils.language import get_language_data
def processor(request):
languages_dict = dict(settings.AVAILABLE_LANGUAGES)
full_path = request.get_full_path()
i18n_path = {}
static_path = static('images/logos/logo-social.png')
is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
for lang in settings.AVAILABLE_LANGUAGES:
i18n_path[lang[0]] = '/{0}/{1}'.format(lang[0], '/'.join(full_path.split('/')[2:]))
# yapf: disable
context = {
'mastodon': settings.WGER_SETTINGS['MASTODON'],
'twitter': settings.WGER_SETTINGS['TWITTER'],
# Languages
'i18n_language':
get_language_data(
(get_language(), languages_dict.get(get_language(), ENGLISH_SHORT_NAME)),
),
'languages': settings.AVAILABLE_LANGUAGES,
# The current path
'request_full_path': full_path,
# The current full path with host
'request_absolute_path': request.build_absolute_uri(),
'image_absolute_path': request.build_absolute_uri(static_path),
# Translation links
'i18n_path': i18n_path,
'is_api_path': '/api/' in request.build_absolute_uri(),
# Flag for guest users
'has_demo_data': request.session.get('has_demo_data', False),
# Don't show messages on AJAX requests (they are deleted if shown)
'no_messages': request.META.get('HTTP_X_WGER_NO_MESSAGES', False),
# Default cache time for template fragment caching
'cache_timeout': settings.CACHES['default']['TIMEOUT'],
# Used for logged in trainers
'trainer_identity': request.session.get('trainer.identity'),
# current gym, if available
'custom_header': get_custom_header(request),
# Template to extend in forms, kinda ugly but will be removed in the future
'extend_template': 'base_empty.html' if is_ajax else 'base.html',
}
# yapf: enable
# Pseudo-intelligent navigation here
if (
'/software/' in request.get_full_path()
or '/contact' in request.get_full_path()
or '/api/v2' in request.get_full_path()
):
context['active_tab'] = constants.SOFTWARE_TAB
elif '/exercise/' in request.get_full_path():
context['active_tab'] = constants.WORKOUT_TAB
elif '/nutrition/' in request.get_full_path():
context['active_tab'] = constants.NUTRITION_TAB
elif '/weight/' in request.get_full_path():
context['active_tab'] = constants.WEIGHT_TAB
elif '/workout/' in request.get_full_path():
context['active_tab'] = constants.WORKOUT_TAB
return context
def get_custom_header(request):
"""
Loads the custom header for the application, if available
Currently the header can only be overwritten to use the user's current gym
"""
# Current gym
current_gym = None
if request.user.is_authenticated and request.user.userprofile.gym:
current_gym = request.user.userprofile.gym
else:
global_gymconfig = GymConfig.objects.get(pk=1)
if global_gymconfig.default_gym:
current_gym = global_gymconfig.default_gym
# Put the custom header together
custom_header = None
if current_gym and current_gym.config.show_name:
custom_header = current_gym.name
return custom_header
| 4,356 | Python | .py | 97 | 38.721649 | 91 | 0.689036 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,454 | fields.py | wger-project_wger/wger/utils/fields.py | # 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.db import models
# wger
from wger.utils.widgets import (
Html5FormDateField,
Html5FormTimeField,
)
logger = logging.getLogger(__name__)
class Html5TimeField(models.TimeField):
"""
Custom Time field that uses the Html5TimeInput widget
"""
def formfield(self, **kwargs):
"""
Use our custom field
"""
defaults = {'form_class': Html5FormTimeField}
defaults.update(kwargs)
return super(Html5TimeField, self).formfield(**defaults)
class Html5DateField(models.DateField):
"""
Custom Time field that uses the Html5DateInput widget
"""
def formfield(self, **kwargs):
"""
Use our custom field
"""
defaults = {'form_class': Html5FormDateField}
defaults.update(kwargs)
return super(Html5DateField, self).formfield(**defaults)
| 1,555 | Python | .py | 45 | 30.288889 | 78 | 0.72515 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,455 | helpers.py | wger-project_wger/wger/utils/helpers.py | # -*- 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 datetime
import decimal
import json
import logging
import os
import random
import string
from functools import wraps
# Django
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.encoding import force_bytes
from django.utils.http import (
urlsafe_base64_decode,
urlsafe_base64_encode,
)
logger = logging.getLogger(__name__)
class EmailAuthBackend:
def authenticate(self, request, username=None, password=None):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
return None
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
class DecimalJsonEncoder(json.JSONEncoder):
"""
Custom JSON encoder.
This class is needed because we store some data as a decimal (e.g. the
individual weight entries in the workout log) and they need to be
processed, json.dumps() doesn't work on them
"""
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return str(obj)
if isinstance(obj, datetime.date):
return str(obj)
return json.JSONEncoder.default(self, obj)
def disable_for_loaddata(signal_handler):
"""
Decorator to prevent clashes when loading data with loaddata and
post_connect signals. See also:
http://stackoverflow.com/questions/3499791/how-do-i-prevent-fixtures-from-conflicting
"""
@wraps(signal_handler)
def wrapper(*args, **kwargs):
if kwargs['raw']:
return
signal_handler(*args, **kwargs)
return wrapper
def next_weekday(date, weekday):
"""
Helper function to find the next weekday after a given date,
e.g. the first Monday after the 2013-12-05
See link for more details:
* http://stackoverflow.com/questions/6558535/python-find-the-date-for-the-first-monday-after-a
:param date: the start date
:param weekday: weekday (0, Monday, 1 Tuesday, 2 Wednesday)
:type date: datetime.date
:type weekday int
:return: datetime.date
"""
days_ahead = weekday - date.weekday()
if days_ahead <= 0:
days_ahead += 7
return date + datetime.timedelta(days_ahead)
def make_uid(input):
"""
Small wrapper to generate a UID, usually used in URLs to allow for
anonymous access
"""
return urlsafe_base64_encode(force_bytes(input))
def make_token(user):
"""
Convenience function that generates the UID and token for a user
:param user: a user object
:return: the uid and the token
"""
uid = make_uid(user.pk)
token = default_token_generator.make_token(user)
return uid, token
def check_token(uidb64, token):
"""
Checks that the user token is correct.
:param uidb:
:param token:
:return: True on success, False in all other situations
"""
if uidb64 is not None and token is not None:
try:
uid = int(urlsafe_base64_decode(uidb64))
except ValueError as e:
logger.info(f'Could not decode UID: {e}')
return False
try:
user = User.objects.get(pk=uid)
if user is not None and default_token_generator.check_token(user, token):
return True
except User.DoesNotExist:
return False
return False
def password_generator(length=15):
"""
A simple password generator
Also removes some 'problematic' characters like O and 0
:param length: the length of the password
:return: the generated password
"""
chars = string.ascii_letters + string.digits
random.seed = os.urandom(1024)
for char in ('I', '1', 'l', 'O', '0', 'o'):
chars = chars.replace(char, '')
return ''.join(random.choice(chars) for i in range(length))
def check_access(request_user, username=None):
"""
Small helper function to check that the current (possibly unauthenticated)
user can access a URL that the owner user shared the link.
Raises Http404 in case of error (no read-only access allowed)
:param request_user: the user in the current request
:param username: the username
:return: a tuple: (is_owner, user)
"""
if username:
user = get_object_or_404(User, username=username)
if request_user.username == username:
user = request_user
elif not user.userprofile.ro_access:
raise Http404('You are not allowed to access this page.')
# If there is no user_pk, just show the user his own data
else:
if not request_user.is_authenticated:
raise Http404('You are not allowed to access this page.')
user = request_user
is_owner = request_user == user
return is_owner, user
def normalize_decimal(d):
"""
Normalizes a decimal input
This simply performs a more "human" normalization, since python's decimal
normalize() converts "100" into "1e2", which is not a format usually used
when writing workout plans.
:param d: decimal to convert
:return: normalized decimal
"""
normalized = d.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent > 0:
return decimal.Decimal((sign, digits + (0,) * exponent, 0))
else:
return normalized
def random_string(length=32):
"""
Generates a random string
"""
return ''.join(random.choice(string.ascii_uppercase) for i in range(length))
class BaseImage:
def save_image(self, retrieved_image, json_data: dict):
# Save the downloaded image
# http://stackoverflow.com/questions/1308386/programmatically-saving-image-to
if os.name == 'nt':
img_temp = NamedTemporaryFile()
else:
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(retrieved_image.content)
img_temp.flush()
self.image.save(
os.path.basename(json_data['image']),
File(img_temp),
)
@classmethod
def from_json(cls, connect_to, retrieved_image, json_data: dict, generate_uuid: bool = False):
image: cls = cls()
if not generate_uuid:
image.uuid = json_data['uuid']
return image
| 7,281 | Python | .py | 200 | 30.36 | 98 | 0.681417 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,456 | permissions.py | wger-project_wger/wger/utils/permissions.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Third Party
from rest_framework import permissions
class WgerPermission(permissions.BasePermission):
"""
Checks that the user has access to the object
If the object has a 'owner_object' method, only allow access for the owner
user. For the other objects (system-wide objects like exercises, etc.) allow
only safe methods (GET, HEAD or OPTIONS)
"""
def has_permission(self, request, view):
"""
Access to public resources is allowed for all, for others, the user
has to be authenticated
The is_public flag is not present in all views, e.g. the special APIRoot
view. If it is not present, treat is as a public endpoint
"""
if hasattr(view, 'is_private') and view.is_private:
return request.user and request.user.is_authenticated
return True
def has_object_permission(self, request, view, obj):
"""
Perform the check
"""
owner_object = obj.get_owner_object() if hasattr(obj, 'get_owner_object') else False
# Owner
if owner_object and owner_object.user == request.user:
return True
# 'global' objects only for GET, HEAD or OPTIONS
if not owner_object and request.method in permissions.SAFE_METHODS:
return True
# Everything else is a no-no
return False
class CreateOnlyPermission(permissions.BasePermission):
"""
Custom permission that permits read access the resource but limits the
write operations to creating (POSTing) new objects only and does not
allow editing them. This is currently used for exercises and their
images.
"""
def has_permission(self, request, view):
return request.method in ['GET', 'HEAD', 'OPTIONS'] or (
request.user and request.user.is_authenticated and request.method == 'POST'
)
class UpdateOnlyPermission(permissions.BasePermission):
"""
Custom permission that restricts write operations to PATCH. This is currently
used for the user profile.
"""
def has_permission(self, request, view):
return (
request.user
and request.user.is_authenticated
and request.method in ['GET', 'HEAD', 'OPTIONS', 'PATCH']
)
| 3,026 | Python | .py | 69 | 37.681159 | 92 | 0.696259 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,457 | test_make_token.py | wger-project_wger/wger/utils/tests/test_make_token.py | # 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.contrib.auth.models import User
# Third Party
from rest_framework.authtoken.models import Token
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.utils.api_token import create_token
class TokenHelperTestCase(WgerTestCase):
"""
Tests the create_token helper
"""
def test_make_token(self):
"""
Test that create_token returns the user's existing token
"""
user = User.objects.get(pk=2)
self.assertEqual(Token.objects.filter(user=user).count(), 1)
token_before = Token.objects.get(user=user).key
token = create_token(user).key
token_after = Token.objects.get(user=user).key
self.assertEqual(token_before, token_after)
self.assertEqual(token_before, token)
def test_make_token_force_new(self):
"""
Test that create_token returns the user's existing token
"""
user = User.objects.get(pk=2)
self.assertEqual(Token.objects.filter(user=user).count(), 1)
token_before = Token.objects.get(user=user).key
token = create_token(user, force_new=True).key
token_after = Token.objects.get(user=user).key
self.assertNotEqual(token_before, token_after)
self.assertEqual(token, token_after)
def test_make_token_new(self):
"""
Test that create_token creates a token for users that don't have one
"""
user = User.objects.get(pk=2)
Token.objects.filter(user=user).delete()
self.assertEqual(Token.objects.filter(user=user).count(), 0)
create_token(user)
self.assertEqual(Token.objects.filter(user=user).count(), 1)
| 2,334 | Python | .py | 55 | 36.690909 | 78 | 0.706531 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,458 | test_unit_conversion.py | wger-project_wger/wger/utils/tests/test_unit_conversion.py | # 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
from decimal import Decimal
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.utils.constants import FOURPLACES
from wger.utils.units import AbstractWeight
class WeightConversionTestCase(WgerTestCase):
"""
Test the abstract weight class
"""
def test_conversion(self):
"""
Test the weight conversion
"""
tmp = AbstractWeight(10)
self.assertEqual(tmp.kg, 10)
self.assertEqual(tmp.lb, Decimal(22.0462).quantize(FOURPLACES))
tmp = AbstractWeight(10, 'lb')
self.assertEqual(tmp.lb, 10)
self.assertEqual(tmp.kg, Decimal(4.5359).quantize(FOURPLACES))
tmp = AbstractWeight(0.4536)
self.assertEqual(tmp.lb, Decimal(1))
self.assertEqual(tmp.kg, Decimal(0.4536).quantize(FOURPLACES))
tmp = AbstractWeight(80)
self.assertEqual(tmp.lb, Decimal(176.3698).quantize(FOURPLACES))
self.assertEqual(tmp.kg, 80)
tmp = AbstractWeight(80, 'kg')
self.assertEqual(tmp.lb, Decimal(176.3698).quantize(FOURPLACES))
self.assertEqual(tmp.kg, 80)
def test_conversion_subunits(self):
"""
Test the weight conversion with "subunits" (grams, ounces)
"""
tmp = AbstractWeight(100.1, 'g')
self.assertEqual(tmp.kg, Decimal(0.1001).quantize(FOURPLACES))
tmp = AbstractWeight(100, 'g')
self.assertEqual(tmp.kg, Decimal(0.1).quantize(FOURPLACES))
tmp = AbstractWeight(1000, 'g')
self.assertEqual(tmp.kg, 1)
tmp = AbstractWeight(1.5, 'oz')
self.assertEqual(tmp.lb, Decimal(0.0938).quantize(FOURPLACES))
tmp = AbstractWeight(2, 'oz')
self.assertEqual(tmp.lb, Decimal(0.125).quantize(FOURPLACES))
tmp = AbstractWeight(4, 'oz')
self.assertEqual(tmp.lb, Decimal(0.25).quantize(FOURPLACES))
tmp = AbstractWeight(8, 'oz')
self.assertEqual(tmp.lb, Decimal(0.5).quantize(FOURPLACES))
tmp = AbstractWeight(16, 'oz')
self.assertEqual(tmp.lb, 1)
def test_sum(self):
"""
Tests adding two abstract weights
"""
weight1 = AbstractWeight(80, 'kg')
weight2 = AbstractWeight(10, 'kg')
sum = weight1 + weight2
self.assertEqual(sum.kg, 90)
weight1 = AbstractWeight(80, 'kg')
weight2 = AbstractWeight(10, 'lb')
sum = weight1 + weight2
self.assertEqual(sum.kg, Decimal(84.5359).quantize(FOURPLACES))
weight1 = AbstractWeight(80, 'lb')
weight2 = AbstractWeight(10, 'lb')
sum = weight1 + weight2
self.assertEqual(sum.lb, Decimal(90))
def test_subunits(self):
"""
Test weight subunit calculations
"""
tmp = AbstractWeight(10)
self.assertEqual(tmp.g, 10000)
tmp = AbstractWeight(2, 'lb')
self.assertEqual(tmp.oz, 32)
| 3,555 | Python | .py | 86 | 34.232558 | 78 | 0.668118 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,459 | test_url.py | wger-project_wger/wger/utils/tests/test_url.py | # 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 unittest
# wger
from wger.utils.url import make_uri
class TestMakeUri(unittest.TestCase):
def test_make_uri(self):
# Test default server_url
self.assertEqual(
make_uri('test'),
'https://wger.de/api/v2/test/',
)
# Test custom server_url
self.assertEqual(
make_uri('test', server_url='https://api.example.com'),
'https://api.example.com/api/v2/test/',
)
# Test with id
self.assertEqual(
make_uri('test', id=123),
'https://wger.de/api/v2/test/123/',
)
# Test with object_method
self.assertEqual(
make_uri('test', object_method='create'),
'https://wger.de/api/v2/test/create/',
)
# Test with query parameters
self.assertEqual(
make_uri('endpoint', query={'key1': 'value1', 'key2': 'value2'}),
'https://wger.de/api/v2/endpoint/?key1=value1&key2=value2',
)
# Test with all parameters
self.assertEqual(
make_uri('test', id=123, object_method='create', query={'key1': 'value1'}),
'https://wger.de/api/v2/test/123/create/?key1=value1',
)
if __name__ == '__main__':
unittest.main()
| 1,944 | Python | .py | 51 | 31.098039 | 87 | 0.635494 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,460 | test_check_access.py | wger-project_wger/wger/utils/tests/test_check_access.py | # 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.contrib.auth.models import (
AnonymousUser,
User,
)
from django.http import Http404
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.utils.helpers import check_access
class CheckAccessTestCase(WgerTestCase):
"""
Test the "check_access" helper function
"""
def test_helper(self):
"""
Test the helper function
"""
user_share = User.objects.get(pk=1)
self.assertTrue(user_share.userprofile.ro_access)
user_no_share = User.objects.get(pk=2)
self.assertFalse(user_no_share.userprofile.ro_access)
anon = AnonymousUser()
# Logged out user
self.assertEqual(check_access(anon, 'admin'), (False, user_share))
self.assertRaises(Http404, check_access, anon, 'test')
self.assertRaises(Http404, check_access, anon, 'not_a_username')
self.assertRaises(Http404, check_access, anon)
# Logged in user
self.assertEqual(check_access(user_share, 'admin'), (True, user_share))
self.assertRaises(Http404, check_access, user_share, 'test')
self.assertEqual(check_access(user_share), (True, user_share))
self.assertRaises(Http404, check_access, user_share, 'not_a_username')
self.assertEqual(check_access(user_no_share, 'admin'), (False, user_share))
self.assertEqual(check_access(user_no_share, 'test'), (True, user_no_share))
self.assertEqual(check_access(user_no_share), (True, user_no_share))
self.assertRaises(Http404, check_access, user_no_share, 'not_a_username')
| 2,240 | Python | .py | 49 | 40.408163 | 84 | 0.715596 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,461 | test_middleware.py | wger-project_wger/wger/utils/tests/test_middleware.py | # 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.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
class RobotsExclusionMiddlewareTestCase(WgerTestCase):
"""
Tests the robots exclusion middleware
"""
def test_middleware_manager(self):
"""
Test the middleware on URLs from manager app
"""
response = self.client.get(reverse('core:dashboard'))
self.assertTrue(response.get('X-Robots-Tag'))
response = self.client.get(reverse('manager:workout:overview'))
self.assertFalse(response.get('X-Robots-Tag'))
response = self.client.get(reverse('manager:schedule:overview'))
self.assertFalse(response.get('X-Robots-Tag'))
response = self.client.get(reverse('core:feedback'))
self.assertFalse(response.get('X-Robots-Tag'))
response = self.client.get(reverse('core:imprint'))
self.assertFalse(response.get('X-Robots-Tag'))
def test_middleware_software(self):
"""
Test the middleware on URLs from software app
"""
for i in ('features', 'tos', 'about-us'):
response = self.client.get(reverse(f'software:{i}'))
self.assertFalse(response.get('X-Robots-Tag'))
def test_middleware_nutrition(self):
"""
Test the middleware on URLs from nutrition app
"""
response = self.client.get(reverse('nutrition:ingredient:list'))
self.assertFalse(response.get('X-Robots-Tag'))
response = self.client.get(reverse('nutrition:ingredient:view', kwargs={'pk': 1}))
self.assertFalse(response.get('X-Robots-Tag'))
response = self.client.get(reverse('nutrition:plan:overview'))
self.assertFalse(response.get('X-Robots-Tag'))
def test_middleware_exercises(self):
"""
Test the middleware on URLs from exercises app
"""
response = self.client.get(reverse('exercise:exercise:overview'))
self.assertFalse(response.get('X-Robots-Tag'))
response = self.client.get(reverse('exercise:exercise:view-base', kwargs={'pk': 1}))
self.assertFalse(response.get('X-Robots-Tag'))
| 2,801 | Python | .py | 60 | 40.1 | 92 | 0.692506 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,462 | signals.py | wger-project_wger/wger/manager/signals.py | # -*- 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
# Django
from django.db.models.signals import post_save
# wger
from wger.gym.helpers import get_user_last_activity
from wger.manager.models import (
WorkoutLog,
WorkoutSession,
)
def update_activity_cache(sender, instance, **kwargs):
"""
Update the user's cached last activity date
"""
user = instance.user
user.usercache.last_activity = get_user_last_activity(user)
user.usercache.save()
post_save.connect(update_activity_cache, sender=WorkoutSession)
post_save.connect(update_activity_cache, sender=WorkoutLog)
| 1,216 | Python | .py | 31 | 36.935484 | 78 | 0.775701 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,463 | urls.py | wger-project_wger/wger/manager/urls.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.conf.urls import include
from django.contrib.auth.decorators import login_required
from django.urls import (
path,
re_path,
)
# wger
from wger.core.views.react import ReactView
from wger.manager.views import (
day,
ical,
log,
pdf,
schedule,
schedule_step,
set,
workout,
workout_session,
)
# sub patterns for workout logs
patterns_log = [
path(
'<int:pk>/view',
ReactView.as_view(login_required=True),
name='log',
),
path(
'<int:pk>/edit', # JS
log.WorkoutLogUpdateView.as_view(),
name='edit',
),
path(
'<int:pk>/delete',
log.WorkoutLogDeleteView.as_view(),
name='delete',
),
]
# sub patterns for templates
patterns_templates = [
path(
'overview',
workout.template_overview,
name='overview',
),
path(
'public',
workout.public_template_overview,
name='public',
),
path(
'<int:pk>/view',
workout.template_view,
name='view',
),
path(
'<int:pk>/make-workout',
workout.make_workout,
name='make-workout',
),
]
# sub patterns for workouts
patterns_workout = [
path(
'overview',
ReactView.as_view(login_required=True),
name='overview',
),
path(
'add',
workout.add,
name='add',
),
path(
'<int:pk>/copy',
workout.copy_workout,
name='copy',
),
path(
'<int:pk>/edit',
workout.WorkoutEditView.as_view(),
name='edit',
),
path(
'<int:pk>/make-template',
workout.WorkoutMarkAsTemplateView.as_view(),
name='make-template',
),
path(
'<int:pk>/delete',
workout.WorkoutDeleteView.as_view(),
name='delete',
),
path(
'<int:pk>/view',
# ReactView.as_view(login_required=True),
workout.view,
name='view',
),
re_path(
r'^calendar/(?P<username>[\w.@+-]+)$',
log.calendar,
name='calendar',
),
path(
'calendar',
log.calendar,
name='calendar',
),
re_path(
r'^calendar/(?P<username>[\w.@+-]+)/(?P<year>\d{4})/(?P<month>\d{1,2})$',
log.calendar,
name='calendar',
),
re_path(
r'^calendar/(?P<year>\d{4})/(?P<month>\d{1,2})$',
log.calendar,
name='calendar',
),
re_path(
r'^calendar/(?P<username>[\w.@+-]+)/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})$',
log.day,
name='calendar-day',
),
re_path(
r'^(?P<pk>\d+)/ical/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
ical.export,
name='ical',
),
path(
'<int:pk>/ical',
ical.export,
name='ical',
),
re_path(
r'^(?P<id>\d+)/pdf/log/(?P<images>[01]+)/(?P<comments>[01]+)/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
pdf.workout_log,
name='pdf-log',
), # JS!
re_path(
r'^(?P<id>\d+)/pdf/log/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
pdf.workout_log,
name='pdf-log',
),
re_path(
r'^(?P<id>\d+)/pdf/log/(?P<images>[01]+)/(?P<comments>[01]+)$',
pdf.workout_log,
name='pdf-log',
),
path(
'<int:id>/pdf/log',
pdf.workout_log,
name='pdf-log',
),
re_path(
r'^(?P<id>\d+)/pdf/table/(?P<images>[01]+)/(?P<comments>[01]+)/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
pdf.workout_view,
name='pdf-table',
), # JS!
re_path(
r'^(?P<id>\d+)/pdf/table/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
pdf.workout_view,
name='pdf-table',
),
re_path(
r'^(?P<id>\d+)/pdf/table/(?P<images>[01]+)/(?P<comments>[01]+)$',
pdf.workout_view,
name='pdf-table',
),
path(
'<int:id>/pdf/table',
pdf.workout_view,
name='pdf-table',
),
]
# sub patterns for workout sessions
patterns_session = [
re_path(
r'^(?P<workout_pk>\d+)/add/(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$',
workout_session.WorkoutSessionAddView.as_view(),
name='add',
),
path(
'<int:pk>/edit',
workout_session.WorkoutSessionUpdateView.as_view(),
name='edit',
),
re_path(
r'^(?P<pk>\d+)/delete/(?P<logs>session|logs)?$',
workout_session.WorkoutSessionDeleteView.as_view(),
name='delete',
),
]
# 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(
'overview',
schedule.overview,
name='overview',
),
path(
'add',
schedule.ScheduleCreateView.as_view(),
name='add',
),
path(
'<int:pk>/view',
schedule.view,
name='view',
),
path(
'<int:pk>/start',
schedule.start,
name='start',
),
path(
'<int:pk>/edit',
schedule.ScheduleEditView.as_view(),
name='edit',
),
path(
'<int:pk>/delete',
schedule.ScheduleDeleteView.as_view(),
name='delete',
),
re_path(
r'^(?P<pk>\d+)/ical/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
ical.export_schedule,
name='ical',
),
path(
'<int:pk>/ical',
ical.export_schedule,
name='ical',
),
re_path(
r'^(?P<pk>\d+)/pdf/log/(?P<images>[01]+)/(?P<comments>[01]+)/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
schedule.export_pdf_log,
name='pdf-log',
), # JS!
re_path(
r'^(?P<pk>\d+)/pdf/log/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
schedule.export_pdf_log,
name='pdf-log',
),
re_path(
r'^(?P<pk>\d+)/pdf/log/(?P<images>[01]+)/(?P<comments>[01]+)$',
schedule.export_pdf_log,
name='pdf-log',
),
path(
'<int:pk>/pdf/log',
schedule.export_pdf_log,
name='pdf-log',
),
re_path(
r'^(?P<pk>\d+)/pdf/table/(?P<images>[01]+)/(?P<comments>[01]+)/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
schedule.export_pdf_table,
name='pdf-table',
), # JS!
re_path(
r'^(?P<pk>\d+)/pdf/table/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
schedule.export_pdf_table,
name='pdf-table',
),
re_path(
r'^(?P<pk>\d+)/pdf/table/(?P<images>[01]+)/(?P<comments>[01]+)$',
schedule.export_pdf_table,
name='pdf-table',
),
path(
'<int:pk>/pdf/table',
schedule.export_pdf_table,
name='pdf-table',
),
]
# sub patterns for schedule steps
patterns_step = [
path(
'<int:schedule_pk>/step/add',
schedule_step.StepCreateView.as_view(),
name='add',
),
path(
'<int:pk>/edit',
schedule_step.StepEditView.as_view(),
name='edit',
),
path(
'<int:pk>/delete',
schedule_step.StepDeleteView.as_view(),
name='delete',
),
]
urlpatterns = [
path('', include((patterns_workout, 'workout'), namespace='workout')),
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')),
]
| 9,742 | Python | .py | 370 | 19.878378 | 148 | 0.528903 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,464 | apps.py | wger-project_wger/wger/manager/apps.py | # -*- 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
# Django
from django.apps import AppConfig
class ManagerConfig(AppConfig):
name = 'wger.manager'
verbose_name = 'Manager'
def ready(self):
import wger.manager.signals
| 855 | Python | .py | 21 | 38.52381 | 78 | 0.769602 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,465 | __init__.py | wger-project_wger/wger/manager/__init__.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger import get_version
VERSION = get_version()
default_app_config = 'wger.manager.apps.ManagerConfig'
| 857 | Python | .py | 19 | 43.894737 | 78 | 0.776978 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,466 | consts.py | wger-project_wger/wger/manager/consts.py | # 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/>.
RIR_OPTIONS = [
(None, '------'),
('0', 0),
('0.5', 0.5),
('1', 1),
('1.5', 1.5),
('2', 2),
('2.5', 2.5),
('3', 3),
('3.5', 3.5),
('4', 4),
]
| 985 | Python | .py | 27 | 33.962963 | 79 | 0.671891 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,467 | helpers.py | wger-project_wger/wger/manager/helpers.py | # -*- 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
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
import datetime
from calendar import HTMLCalendar
# Django
from django.urls import reverse
from django.utils.translation import gettext as _
# Third Party
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.platypus import (
Image,
KeepTogether,
ListFlowable,
ListItem,
Paragraph,
Table,
)
# wger
from wger.utils.pdf import (
header_colour,
row_color,
styleSheet,
)
def render_workout_day(day, nr_of_weeks=7, images=False, comments=False, only_table=False):
"""
Render a table with reportlab with the contents of the training day
:param day: a workout day object
:param nr_of_weeks: the numbrer of weeks to render, default is 7
:param images: boolean indicating whether to also draw exercise images
in the PDF (actually only the main image)
:param comments: boolean indicathing whether the exercise comments will
be rendered as well
:param only_table: boolean indicating whether to draw a table with space
for weight logs or just a list of the exercises
"""
# If rendering only the table, reset the nr of weeks, since these columns
# will not be rendered anyway.
if only_table:
nr_of_weeks = 0
data = []
# Init some counters and markers, this will be used after the iteration to
# set different borders and colours
day_markers = []
group_exercise_marker = {}
set_count = 1
day_markers.append(len(data))
p = Paragraph(
'<para align="center">%(days)s: %(description)s</para>'
% {'days': day.days_txt, 'description': day.description},
styleSheet['SubHeader'],
)
data.append([p])
# Note: the _('Date') will be on the 3rd cell, but since we make a span
# over 3 cells, the value has to be on the 1st one
data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)
data.append([_('Nr.'), _('Exercise'), _('Reps')] + [_('Weight')] * nr_of_weeks)
# Sets
exercise_start = len(data)
for set_obj in day.set_set.all():
group_exercise_marker[set_obj.id] = {'start': len(data), 'end': len(data)}
# Exercises
for base in set_obj.exercise_bases:
exercise = base.get_translation()
group_exercise_marker[set_obj.id]['end'] = len(data)
# Process the settings
setting_out = []
for i in set_obj.reps_smart_text(base).split('–'):
setting_out.append(Paragraph(i, styleSheet['Small'], bulletText=''))
# Collect a list of the exercise comments
item_list = [Paragraph('', styleSheet['Small'])]
if comments:
item_list = [
ListItem(Paragraph(i.comment, style=styleSheet['ExerciseComments']))
for i in exercise.exercisecomment_set.all()
]
# Add the exercise's main image
image = Paragraph('', styleSheet['Small'])
if images:
if base.main_image:
# Make the images somewhat larger when printing only the workout and not
# also the columns for weight logs
if only_table:
image_size = 2
else:
image_size = 1.5
image = Image(base.main_image.image)
image.drawHeight = image_size * cm * image.drawHeight / image.drawWidth
image.drawWidth = image_size * cm
# Put the name and images and comments together
exercise_content = [
Paragraph(exercise.name, styleSheet['Small']),
image,
ListFlowable(
item_list,
bulletType='bullet',
leftIndent=5,
spaceBefore=7,
bulletOffsetY=-3,
bulletFontSize=3,
start='square',
),
]
data.append([f'#{set_count}', exercise_content, setting_out] + [''] * nr_of_weeks)
set_count += 1
table_style = [
('FONT', (0, 0), (-1, -1), 'OpenSans'),
('FONTSIZE', (0, 0), (-1, -1), 8),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('LEFTPADDING', (0, 0), (-1, -1), 2),
('RIGHTPADDING', (0, 0), (-1, -1), 0),
('TOPPADDING', (0, 0), (-1, -1), 3),
('BOTTOMPADDING', (0, 0), (-1, -1), 2),
('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
# Header
('BACKGROUND', (0, 0), (-1, 0), header_colour),
('BOX', (0, 0), (-1, -1), 1.25, colors.black),
('BOX', (0, 1), (-1, -1), 1.25, colors.black),
('SPAN', (0, 0), (-1, 0)),
# Cell with 'date'
('SPAN', (0, 1), (2, 1)),
('ALIGN', (0, 1), (2, 1), 'RIGHT'),
]
# Combine the cells for exercises on the same superset
for marker in group_exercise_marker:
start_marker = group_exercise_marker[marker]['start']
end_marker = group_exercise_marker[marker]['end']
table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
table_style.append(('SPAN', (0, start_marker), (0, end_marker)))
# Set an alternating background colour for rows with exercises.
# The rows with exercises range from exercise_start till the end of the data
# list
for i in range(exercise_start, len(data) + 1):
if not i % 2:
table_style.append(('BACKGROUND', (0, i - 1), (-1, i - 1), row_color))
# Put everything together and manually set some of the widths
t = Table(data, style=table_style)
if len(t._argW) > 1:
if only_table:
t._argW[0] = 0.6 * cm # Numbering
t._argW[1] = 8 * cm # Exercise
t._argW[2] = 3.5 * cm # Repetitions
else:
t._argW[0] = 0.6 * cm # Numbering
t._argW[1] = 4 * cm # Exercise
t._argW[2] = 3 * cm # Repetitions
return KeepTogether(t)
class WorkoutCalendar(HTMLCalendar):
"""
A calendar renderer, see this blog entry for details:
* http://uggedal.com/journal/creating-a-flexible-monthly-calendar-in-django/
"""
def __init__(self, workout_logs, *args, **kwargs):
super(WorkoutCalendar, self).__init__(*args, **kwargs)
self.workout_logs = workout_logs
def formatday(self, day, weekday):
# days belonging to last or next month are rendered empty
if day == 0:
return self.day_cell('noday', ' ')
date_obj = datetime.date(self.year, self.month, day)
cssclass = self.cssclasses[weekday]
if datetime.date.today() == date_obj:
cssclass += ' today'
# There are no logs for this day, doesn't need special attention
if date_obj not in self.workout_logs:
return self.day_cell(cssclass, day)
# Day with a log, set background and link
entry = self.workout_logs.get(date_obj)
# Note: due to circular imports we use can't import the workout session
# model to access the impression values directly, so they are hard coded
# here.
if entry['session']:
# Bad
if entry['session'].impression == '1':
background_css = 'btn-danger'
# Good
elif entry['session'].impression == '3':
background_css = 'btn-success'
# Neutral
else:
background_css = 'btn-warning'
else:
background_css = 'btn-warning'
url = reverse('manager:log:log', kwargs={'pk': entry['workout'].id})
formatted_date = date_obj.strftime('%Y-%m-%d')
body = []
body.append(
f'<a href="{url}" '
f'data-log="log-{formatted_date}" '
f'class="btn btn-block {background_css} calendar-link">'
)
body.append(repr(day))
body.append('</a>')
return self.day_cell(cssclass, ''.join(body))
def formatmonth(self, year, month):
"""
Format the table header. This is basically the same code from python's
calendar module but with additional bootstrap classes
"""
self.year, self.month = year, month
out = []
out.append('<table class="month table table-bordered">\n')
out.append(self.formatmonthname(year, month))
out.append('\n')
out.append(self.formatweekheader())
out.append('\n')
for week in self.monthdays2calendar(year, month):
out.append(self.formatweek(week))
out.append('\n')
out.append('</table>\n')
return ''.join(out)
def day_cell(self, cssclass, body):
"""
Renders a day cell
"""
return f'<td class="{cssclass}" style="vertical-align: middle;">{body}</td>'
| 9,688 | Python | .py | 230 | 32.973913 | 94 | 0.581502 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,468 | forms.py | wger-project_wger/wger/manager/forms.py | # -*- 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
"""
This file contains forms used in the application
"""
# Django
from django.forms import (
BooleanField,
CharField,
ChoiceField,
DecimalField,
Form,
IntegerField,
ModelChoiceField,
ModelForm,
ModelMultipleChoiceField,
widgets,
)
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
# Third Party
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
Column,
Layout,
Row,
Submit,
)
# wger
from wger.core.models import (
RepetitionUnit,
WeightUnit,
)
from wger.exercises.models import (
Exercise,
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):
class Meta:
model = Workout
fields = (
'name',
'description',
)
class WorkoutMakeTemplateForm(ModelForm):
class Meta:
model = Workout
fields = (
'is_template',
'is_public',
)
class WorkoutCopyForm(Form):
name = CharField(max_length=100, help_text=_('The name of the workout'), required=False)
description = CharField(
max_length=1000,
help_text=_(
'A short description or goal of the workout. For '
"example 'Focus on back' or 'Week 1 of program xy'."
),
widget=widgets.Textarea,
required=False,
)
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"""
def clean(self, value):
int_list = [int(i) for i in value]
qs = super(OrderedModelMultipleChoiceField, self).clean(int_list)
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.
These fields are re-defined here only to make them optional. Otherwise
all the entries in the formset would be required, which is not really what
we want. This form is one prime candidate to rework with some modern JS
framework, there is a ton of ugly logic like this just to make it work.
"""
repetition_unit = ModelChoiceField(
queryset=RepetitionUnit.objects.all(),
label=_('Unit'),
required=False,
)
weight_unit = ModelChoiceField(
queryset=WeightUnit.objects.all(),
label=_('Unit'),
required=False,
)
exercise_base = ModelChoiceField(
queryset=ExerciseBase.objects.all(),
label=_('Exercise'),
required=False,
)
reps = IntegerField(
label=_('Repetitions'),
required=False,
)
weight = DecimalField(
label=_('Weight'),
initial=0,
required=False,
)
rir = ChoiceField(
label=_('RiR'),
choices=RIR_OPTIONS,
required=False,
)
class Meta:
model = WorkoutLog
exclude = ('workout',)
class WorkoutLogFormHelper(FormHelper):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.form_method = 'post'
self.layout = Layout(
'id',
Row(
Column('reps', css_class='col-2'),
Column('repetition_unit', css_class='col-3'),
Column('weight', css_class='col-2'),
Column('weight_unit', css_class='col-3'),
Column('rir', css_class='col-2'),
css_class='form-row',
),
)
self.form_show_labels = False
self.form_tag = False
self.disable_csrf = True
self.render_required_fields = True
class HelperWorkoutSessionForm(ModelForm):
"""
A helper form used in the workout log view
"""
class Meta:
model = WorkoutSession
exclude = ('user', 'workout')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Row(
Column('date', css_class='col-6'),
Column('impression', css_class='col-6'),
css_class='form-row',
),
'notes',
Row(
Column('time_start', css_class='col-6'),
Column('time_end', css_class='col-6'),
css_class='form-row',
),
)
self.helper.form_tag = False
class WorkoutSessionForm(ModelForm):
"""
Workout Session form
"""
class Meta:
model = WorkoutSession
exclude = ('user', 'workout', 'date')
def __init__(self, *args, **kwargs):
super(WorkoutSessionForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
'impression',
'notes',
Row(
Column('time_start', css_class='col-6'),
Column('time_end', css_class='col-6'),
css_class='form-row',
),
)
class WorkoutScheduleDownloadForm(Form):
"""
Form for the workout schedule download
"""
pdf_type = ChoiceField(
label=gettext_lazy('Type'),
choices=(('log', gettext_lazy('Log')), ('table', gettext_lazy('Table'))),
)
images = BooleanField(label=gettext_lazy('with images'), required=False)
comments = BooleanField(label=gettext_lazy('with comments'), required=False)
def __init__(self):
super(WorkoutScheduleDownloadForm, self).__init__()
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.add_input(
Submit(
'submit',
_('Download'),
css_class='btn-success btn-block',
css_id='download-pdf-button-schedule',
)
)
| 7,747 | Python | .py | 255 | 23.023529 | 92 | 0.603141 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,469 | managers.py | wger-project_wger/wger/manager/managers.py | # 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/>.
# Django
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
class ScheduleManager(models.Manager):
"""
Custom manager for workout schedules
"""
def get_current_workout(self, user):
"""
Finds the currently active workout for the user, by checking the schedules
and the workouts
:rtype : list
"""
# wger
from wger.manager.models import (
Schedule,
Workout,
)
# Try first to find an active schedule that has steps
try:
schedule = Schedule.objects.filter(user=user).get(is_active=True)
if schedule.schedulestep_set.count():
# The schedule might exist and have steps, but if it's too far in
# the past and is not a loop, we won't use it. Doing it like this
# is kind of wrong, but lets us continue to the correct place
if not schedule.get_current_scheduled_workout():
raise ObjectDoesNotExist
active_workout = schedule.get_current_scheduled_workout().workout
else:
# same as above
raise ObjectDoesNotExist
# there are no active schedules, just return the last workout
except ObjectDoesNotExist:
schedule = False
try:
active_workout = Workout.objects.filter(user=user).latest('creation_date')
# no luck, there aren't even workouts for the user
except ObjectDoesNotExist:
active_workout = False
return active_workout, schedule
class WorkoutManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_template=False)
class WorkoutTemplateManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_template=True)
class WorkoutAndTemplateManager(models.Manager):
def get_queryset(self):
return super().get_queryset()
| 2,843 | Python | .py | 64 | 36.5 | 90 | 0.672576 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,470 | set.py | wger-project_wger/wger/manager/models/set.py | # 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
import typing
# 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.cache import reset_workout_canonical_form
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
def save(self, *args, **kwargs):
"""
Reset all cached infos
"""
reset_workout_canonical_form(self.exerciseday.training_id)
super(Set, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Reset all cached infos
"""
reset_workout_canonical_form(self.exerciseday.training_id)
super(Set, self).delete(*args, **kwargs)
@property
def exercise_bases(self) -> typing.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
| 7,889 | Python | .py | 199 | 30.537688 | 97 | 0.607905 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,471 | setting.py | wger-project_wger/wger/manager/models/setting.py | # 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 (
Exercise,
ExerciseBase,
)
from wger.utils.cache import reset_workout_canonical_form
# 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
"""
reset_workout_canonical_form(self.set.exerciseday.training_id)
# 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 delete(self, *args, **kwargs):
"""
Reset cache
"""
reset_workout_canonical_form(self.set.exerciseday.training_id)
super(Setting, self).delete(*args, **kwargs)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self.set.exerciseday.training
| 4,251 | Python | .py | 129 | 27.20155 | 98 | 0.657888 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,472 | workout.py | wger-project_wger/wger/manager/models/workout.py | # 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/>.
# Django
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
# wger
from wger.manager.managers import (
WorkoutAndTemplateManager,
WorkoutManager,
WorkoutTemplateManager,
)
from wger.utils.cache import (
cache_mapper,
reset_workout_canonical_form,
)
class Workout(models.Model):
"""
Model for a training schedule
"""
objects = WorkoutManager()
templates = WorkoutTemplateManager()
both = WorkoutAndTemplateManager()
class Meta:
"""
Meta class to set some other properties
"""
ordering = [
'-creation_date',
]
creation_date = models.DateField(_('Creation date'), auto_now_add=True)
name = models.CharField(
verbose_name=_('Name'),
max_length=100,
blank=True,
help_text=_('The name of the workout'),
)
description = models.TextField(
verbose_name=_('Description'),
max_length=1000,
blank=True,
help_text=_(
'A short description or goal of the workout. For '
"example 'Focus on back' or 'Week 1 of program "
"xy'."
),
)
is_template = models.BooleanField(
verbose_name=_('Workout template'),
help_text=_(
'Marking a workout as a template will freeze it and allow you to ' 'make copies of it'
),
default=False,
null=False,
)
is_public = models.BooleanField(
verbose_name=_('Public template'),
help_text=_('A public template is available to other users'),
default=False,
null=False,
)
user = models.ForeignKey(
User,
verbose_name=_('User'),
on_delete=models.CASCADE,
)
def get_absolute_url(self):
"""
Returns the canonical URL to view a workout
"""
return reverse(
'manager:template:view' if self.is_template else 'manager:workout:view',
kwargs={'pk': self.id},
)
def __str__(self):
"""
Return a more human-readable representation
"""
if self.name:
return self.name
else:
return f'{_("Workout")} ({self.creation_date})'
def clean(self):
if self.is_public and not self.is_template:
raise ValidationError(
_('You must mark this workout as a template before declaring it public')
)
def save(self, *args, **kwargs):
"""
Reset all cached infos
"""
reset_workout_canonical_form(self.id)
super(Workout, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Reset all cached infos
"""
reset_workout_canonical_form(self.id)
super(Workout, self).delete(*args, **kwargs)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
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)
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)
return workout_canonical_form
| 6,201 | Python | .py | 167 | 27.97006 | 98 | 0.601897 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,473 | schedule.py | wger-project_wger/wger/manager/models/schedule.py | # 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
import datetime
# Django
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
# wger
from wger.manager.managers import ScheduleManager
from wger.utils.fields import Html5DateField
class Schedule(models.Model):
"""
Model for a workout schedule.
A schedule is a collection of workous that are done for a certain time.
E.g. workouts A, B, C, A, B, C, and so on.
"""
objects = ScheduleManager()
"""Custom manager"""
user = models.ForeignKey(
User,
verbose_name=_('User'),
editable=False,
on_delete=models.CASCADE,
)
"""
The user this schedule belongs to. This could be accessed through a step
that points to a workout, that points to a user, but this is more straight
forward and performant
"""
name = models.CharField(
verbose_name=_('Name'),
max_length=100,
help_text=_('Name or short description of the schedule. ' "For example 'Program XYZ'."),
)
"""Name or short description of the schedule."""
start_date = Html5DateField(verbose_name=_('Start date'), default=datetime.date.today)
"""The start date of this schedule"""
is_active = models.BooleanField(
verbose_name=_('Schedule active'),
default=True,
help_text=_(
'Tick the box if you want to mark this schedule '
'as your active one (will be shown e.g. on your '
'dashboard). All other schedules will then be '
'marked as inactive'
),
)
"""A flag indicating whether the schedule is active (needed for dashboard)"""
is_loop = models.BooleanField(
verbose_name=_('Is a loop'),
default=False,
help_text=_(
'Tick the box if you want to repeat the schedules '
'in a loop (i.e. A, B, C, A, B, C, and so on)'
),
)
"""A flag indicating whether the schedule should act as a loop"""
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def get_absolute_url(self):
return reverse('manager:schedule:view', kwargs={'pk': self.id})
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
def save(self, *args, **kwargs):
"""
Only one schedule can be marked as active at a time
"""
if self.is_active:
Schedule.objects.filter(user=self.user).update(is_active=False)
self.is_active = True
super(Schedule, self).save(*args, **kwargs)
def get_current_scheduled_workout(self):
"""
Returns the currently active schedule step for a user
"""
steps = self.schedulestep_set.all()
start_date = self.start_date
found = False
if not steps:
return False
while not found:
for step in steps:
current_limit = start_date + datetime.timedelta(weeks=step.duration)
if current_limit >= datetime.date.today():
found = True
return step
start_date = current_limit
# If it's not a loop, there's no workout that matches, return
if not self.is_loop:
return False
def get_end_date(self):
"""
Calculates the date when the schedule is over or None is the schedule
is a loop.
"""
if self.is_loop:
return None
end_date = self.start_date
for step in self.schedulestep_set.all():
end_date = end_date + datetime.timedelta(weeks=step.duration)
return end_date
| 4,640 | Python | .py | 122 | 30.663934 | 96 | 0.636647 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,474 | __init__.py | wger-project_wger/wger/manager/models/__init__.py | # 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/>.
# Local
from .day import Day
from .log import WorkoutLog
from .schedule import Schedule
from .schedule_step import ScheduleStep
from .session import WorkoutSession
from .set import Set
from .setting import Setting
from .workout import Workout
| 1,046 | Python | .py | 24 | 42.541667 | 79 | 0.785504 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,475 | log.py | wger-project_wger/wger/manager/models/log.py | # 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/>.
# Django
from django.contrib.auth.models import User
from django.core.validators import 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
from wger.utils.cache import reset_workout_log
from wger.utils.fields import Html5DateField
# Local
from ..consts import RIR_OPTIONS
from .session import WorkoutSession
from .workout import Workout
class WorkoutLog(models.Model):
"""
A log entry for an exercise
"""
user = models.ForeignKey(
User,
verbose_name=_('User'),
editable=False,
on_delete=models.CASCADE,
)
exercise_base = models.ForeignKey(
ExerciseBase,
verbose_name=_('Exercise'),
on_delete=models.CASCADE,
)
workout = models.ForeignKey(
Workout,
verbose_name=_('Workout'),
on_delete=models.CASCADE,
)
repetition_unit = models.ForeignKey(
RepetitionUnit,
verbose_name=_('Unit'),
default=1,
on_delete=models.CASCADE,
)
"""
The unit of the log. This can be e.g. a repetition, a minute, etc.
"""
reps = models.IntegerField(
verbose_name=_('Repetitions'),
validators=[MinValueValidator(0)],
)
"""
Amount of repetitions, minutes, etc.
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(
decimal_places=2,
max_digits=5,
verbose_name=_('Weight'),
validators=[MinValueValidator(0)],
)
weight_unit = models.ForeignKey(
WeightUnit,
verbose_name=_('Unit'),
default=1,
on_delete=models.CASCADE,
)
"""
The weight unit of the log. This can be e.g. kg, lb, km/h, etc.
"""
date = Html5DateField(verbose_name=_('Date'))
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.
"""
# Metaclass to set some other properties
class Meta:
ordering = ['date', 'reps']
def __str__(self):
"""
Return a more human-readable representation
"""
return f'Log entry: {self.reps} - {self.weight} kg on {self.date}'
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
def get_workout_session(self, date=None):
"""
Returns the corresponding workout session
:return the WorkoutSession object or None if nothing was found
"""
if not date:
date = self.date
try:
return WorkoutSession.objects.filter(user=self.user).get(date=date)
except WorkoutSession.DoesNotExist:
return None
def save(self, *args, **kwargs):
"""
Reset cache
"""
reset_workout_log(self.user_id, self.date.year, self.date.month, self.date.day)
# 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(WorkoutLog, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Reset cache
"""
reset_workout_log(self.user_id, self.date.year, self.date.month, self.date.day)
super(WorkoutLog, self).delete(*args, **kwargs)
| 4,537 | Python | .py | 137 | 26.919708 | 87 | 0.651737 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,476 | schedule_step.py | wger-project_wger/wger/manager/models/schedule_step.py | # 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
import datetime
# Django
from django.core.validators import (
MaxValueValidator,
MinValueValidator,
)
from django.db import models
from django.utils.translation import gettext_lazy as _
# Local
from .schedule import Schedule
from .workout import Workout
class ScheduleStep(models.Model):
"""
Model for a step in a workout schedule.
A step is basically a workout a with a bit of metadata (next and previous
steps, duration, etc.)
"""
class Meta:
"""
Set default ordering
"""
ordering = [
'order',
]
schedule = models.ForeignKey(Schedule, verbose_name=_('schedule'), on_delete=models.CASCADE)
"""The schedule is step belongs to"""
workout = models.ForeignKey(Workout, on_delete=models.CASCADE)
"""The workout this step manages"""
duration = models.IntegerField(
verbose_name=_('Duration'),
help_text=_('The duration in weeks'),
default=4,
validators=[MinValueValidator(1), MaxValueValidator(25)],
)
"""The duration in weeks"""
order = models.IntegerField(verbose_name=_('Order'), default=1)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self.workout
def __str__(self):
"""
Return a more human-readable representation
"""
return self.workout.name
def get_dates(self):
"""
Calculate the start and end date for this step
"""
steps = self.schedule.schedulestep_set.all()
start_date = end_date = self.schedule.start_date
previous = 0
if not steps:
return False
for step in steps:
start_date += datetime.timedelta(weeks=previous)
end_date += datetime.timedelta(weeks=step.duration)
previous = step.duration
if step == self:
return start_date, end_date
| 2,791 | Python | .py | 77 | 30.272727 | 96 | 0.671985 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,477 | day.py | wger-project_wger/wger/manager/models/day.py | # 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/>.
# Django
from django.db import models
from django.utils.translation import gettext_lazy as _
# wger
from wger.core.models import DaysOfWeek
from wger.utils.cache import reset_workout_canonical_form
# Local
from .workout import Workout
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
def save(self, *args, **kwargs):
"""
Reset all cached infos
"""
reset_workout_canonical_form(self.training_id)
super(Day, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Reset all cached infos
"""
reset_workout_canonical_form(self.training_id)
super(Day, self).delete(*args, **kwargs)
@property
def canonical_representation(self):
"""
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
"""
# Local
from .setting import Setting
canonical_repr = []
muscles_front = []
muscles_back = []
muscles_front_secondary = []
muscles_back_secondary = []
for set_obj in self.set_set.select_related():
exercise_tmp = []
for base in set_obj.exercise_bases:
setting_tmp = []
exercise_images_tmp = []
# Muscles for this set
for muscle in base.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)
for muscle in base.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_base=base).order_by(
'order', 'id'
):
setting_tmp.append(setting)
# "Smart" textual representation
setting_text = set_obj.reps_smart_text(base)
# Exercise comments
comment_list = []
# for i in base.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 base.exerciseimage_set.all():
exercise_images_tmp.append(
{
'image': image.image.url,
'is_main': image.is_main,
}
)
# Put it all together
exercise_tmp.append(
{
'obj': base,
'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,
}
| 7,863 | Python | .py | 188 | 29.324468 | 96 | 0.537495 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,478 | session.py | wger-project_wger/wger/manager/models/session.py | # 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/>.
# Django
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext_lazy as _
# wger
from wger.utils.cache import reset_workout_log
from wger.utils.fields import Html5DateField
# Local
from .workout import Workout
class WorkoutSession(models.Model):
"""
Model for a workout session
"""
# Note: values hardcoded in manager.helpers.WorkoutCalendar
IMPRESSION_BAD = '1'
IMPRESSION_NEUTRAL = '2'
IMPRESSION_GOOD = '3'
IMPRESSION = (
(IMPRESSION_BAD, _('Bad')),
(IMPRESSION_NEUTRAL, _('Neutral')),
(IMPRESSION_GOOD, _('Good')),
)
user = models.ForeignKey(
User,
verbose_name=_('User'),
on_delete=models.CASCADE,
)
"""
The user the workout session belongs to
See note in weight.models.WeightEntry about why this is not editable=False
"""
workout = models.ForeignKey(
Workout,
verbose_name=_('Workout'),
on_delete=models.CASCADE,
)
"""
The workout the session belongs to
"""
date = Html5DateField(verbose_name=_('Date'))
"""
The date the workout session was performed
"""
notes = models.TextField(
verbose_name=_('Notes'),
null=True,
blank=True,
help_text=_('Any notes you might want to save about this workout ' 'session.'),
)
"""
User notes about the workout
"""
impression = models.CharField(
verbose_name=_('General impression'),
max_length=2,
choices=IMPRESSION,
default=IMPRESSION_NEUTRAL,
help_text=_(
'Your impression about this workout session. ' 'Did you exercise as well as you could?'
),
)
"""
The user's general impression of workout
"""
time_start = models.TimeField(verbose_name=_('Start time'), blank=True, null=True)
"""
Time the workout session started
"""
time_end = models.TimeField(verbose_name=_('Finish time'), blank=True, null=True)
"""
Time the workout session ended
"""
def __str__(self):
"""
Return a more human-readable representation
"""
return f'{self.workout} - {self.date}'
class Meta:
"""
Set other properties
"""
ordering = [
'date',
]
unique_together = ('date', 'user')
def clean(self):
"""
Perform some additional validations
"""
if (not self.time_end and self.time_start) or (self.time_end and not self.time_start):
raise ValidationError(_('If you enter a time, you must enter both start and end time.'))
if self.time_end and self.time_start and self.time_start > self.time_end:
raise ValidationError(_('The start time cannot be after the end time.'))
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
def save(self, *args, **kwargs):
"""
Reset cache
"""
reset_workout_log(self.user_id, self.date.year, self.date.month)
super(WorkoutSession, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Reset cache
"""
reset_workout_log(self.user_id, self.date.year, self.date.month)
super(WorkoutSession, self).delete(*args, **kwargs)
| 4,276 | Python | .py | 126 | 27.793651 | 100 | 0.645419 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,479 | 0010_auto_20210102_1446.py | wger-project_wger/wger/manager/migrations/0010_auto_20210102_1446.py | # Generated by Django 3.1.3 on 2021-01-02 13:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0009_auto_20201202_1559'),
]
operations = [
migrations.AlterField(
model_name='setting',
name='rir',
field=models.CharField(
blank=True,
choices=[
(None, '------'),
('0', 0),
('0.5', 0.5),
('1', 1),
('1.5', 1.5),
('2', 2),
('2.5', 2.5),
('3', 3),
('3.5', 3.5),
('4', 4),
],
max_length=3,
null=True,
verbose_name='RiR',
),
),
migrations.AlterField(
model_name='workoutlog',
name='rir',
field=models.CharField(
blank=True,
choices=[
(None, '------'),
('0', 0),
('0.5', 0.5),
('1', 1),
('1.5', 1.5),
('2', 2),
('2.5', 2.5),
('3', 3),
('3.5', 3.5),
('4', 4),
],
max_length=3,
null=True,
verbose_name='RiR',
),
),
]
| 1,517 | Python | .py | 52 | 13.788462 | 47 | 0.297741 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,480 | 0008_auto_20190618_1617.py | wger-project_wger/wger/manager/migrations/0008_auto_20190618_1617.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-06-18 16:17
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0007_auto_20160311_2258'),
]
operations = [
migrations.AlterField(
model_name='setting',
name='reps',
field=models.IntegerField(
validators=[
django.core.validators.MinValueValidator(0),
django.core.validators.MaxValueValidator(600),
],
verbose_name='Amount',
),
),
]
| 662 | Python | .py | 21 | 21.952381 | 66 | 0.565149 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,481 | 0016_move_to_exercise_base.py | wger-project_wger/wger/manager/migrations/0016_move_to_exercise_base.py | # Generated by Django 3.2.10 on 2022-04-20 12:39
from django.db import migrations, models
import django.db.models.deletion
"""
Migration script to move foreign keys in Settings and WorkoutLog from
Exercise to ExerciseBase. We first add a nullable FK to ExerciseBase,
then we migrate the data.
"""
def migrate_setting_to_exercise_base(apps, schema_editor):
Setting = apps.get_model('manager', 'Setting')
settings = Setting.objects.all()
for setting in settings:
setting.exercise_base = setting.exercise.exercise_base
Setting.objects.bulk_update(settings, ['exercise_base'], batch_size=1000)
def migrate_log_to_exercise_base(apps, schema_editor):
WorkoutLog = apps.get_model('manager', 'WorkoutLog')
logs = WorkoutLog.objects.all()
for log in logs:
log.exercise_base = log.exercise.exercise_base
WorkoutLog.objects.bulk_update(logs, ['exercise_base'], batch_size=1000)
class Migration(migrations.Migration):
dependencies = [
('exercises', '0019_exercise_crowdsourcing_changes'),
('manager', '0015_auto_20211028_1113'),
]
operations = [
# Settings
migrations.AddField(
model_name='setting',
name='exercise_base',
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercisebase',
verbose_name='Exercises',
),
),
migrations.RunPython(migrate_setting_to_exercise_base),
migrations.AlterField(
model_name='setting',
name='exercise_base',
field=models.ForeignKey(
null=False,
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercisebase',
verbose_name='Exercises',
),
),
migrations.RemoveField(
model_name='setting',
name='exercise',
),
# WorkoutLog
migrations.AddField(
model_name='workoutlog',
name='exercise_base',
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercisebase',
verbose_name='Exercises',
),
),
migrations.RunPython(migrate_log_to_exercise_base),
migrations.AlterField(
model_name='workoutlog',
name='exercise_base',
field=models.ForeignKey(
null=False,
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercisebase',
verbose_name='Exercises',
),
),
migrations.RemoveField(
model_name='workoutlog',
name='exercise',
),
]
| 2,858 | Python | .py | 79 | 26.126582 | 77 | 0.597182 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,482 | 0011_remove_set_exercises.py | wger-project_wger/wger/manager/migrations/0011_remove_set_exercises.py | # Generated by Django 3.1.5 on 2021-02-28 14:10
from django.db import migrations
def increment_order(apps, schema_editor):
"""
Increment the oder in settings so ensure the order is preserved
Otherwise, and depending on the database, when a set has supersets, the
exercises could be ordered alphabetically.
"""
WorkoutSet = apps.get_model('manager', 'Set')
for workout_set in WorkoutSet.objects.all():
counter = 1
for exercise in workout_set.exercises.all():
for setting in workout_set.setting_set.filter(exercise=exercise):
setting.order = counter
setting.save()
counter += 1
class Migration(migrations.Migration):
dependencies = [
('manager', '0010_auto_20210102_1446'),
]
operations = [
migrations.RunPython(increment_order),
migrations.RemoveField(
model_name='set',
name='exercises',
),
]
| 978 | Python | .py | 27 | 28.37037 | 77 | 0.642251 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,483 | 0013_set_comment.py | wger-project_wger/wger/manager/migrations/0013_set_comment.py | # Generated by Django 3.2.3 on 2021-07-15 16:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0012_auto_20210430_1449'),
]
operations = [
migrations.AddField(
model_name='set',
name='comment',
field=models.CharField(blank=True, max_length=200, verbose_name='Comment'),
),
]
| 418 | Python | .py | 13 | 25 | 87 | 0.623441 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,484 | 0004_auto_20150609_1603.py | wger-project_wger/wger/manager/migrations/0004_auto_20150609_1603.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('manager', '0002_auto_20150202_2040'),
]
operations = [
migrations.AddField(
model_name='setting',
name='weight',
field=models.DecimalField(
decimal_places=2,
validators=[
django.core.validators.MinValueValidator(0),
django.core.validators.MaxValueValidator(1500),
],
max_digits=6,
blank=True,
null=True,
verbose_name='Weight',
),
preserve_default=True,
),
]
| 767 | Python | .py | 25 | 19.44 | 67 | 0.52168 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,485 | 0012_auto_20210430_1449.py | wger-project_wger/wger/manager/migrations/0012_auto_20210430_1449.py | # Generated by Django 3.1.8 on 2021-04-30 12:49
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0011_remove_set_exercises'),
]
operations = [
migrations.RenameField(model_name='workout', old_name='comment', new_name='name'),
migrations.AddField(
model_name='workout',
name='description',
field=models.TextField(
blank=True,
help_text='A short description or goal of the workout. For '
"example 'Focus on back' or 'Week 1 of program xy'.",
max_length=1000,
verbose_name='Description',
),
),
migrations.AlterField(
model_name='workout',
name='name',
field=models.CharField(
blank=True, help_text='The name of the workout', max_length=100, verbose_name='Name'
),
),
migrations.AlterField(
model_name='setting',
name='reps',
field=models.IntegerField(
validators=[
django.core.validators.MinValueValidator(0),
django.core.validators.MaxValueValidator(600),
],
verbose_name='Reps',
),
),
]
| 1,389 | Python | .py | 39 | 24.051282 | 100 | 0.543834 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,486 | 0006_auto_20160303_2138.py | wger-project_wger/wger/manager/migrations/0006_auto_20160303_2138.py | # -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20160303_2340'),
('manager', '0005_auto_20160303_2008'),
]
operations = [
migrations.RenameField(
model_name='setting',
old_name='unit',
new_name='repetition_unit',
),
migrations.RenameField(
model_name='workoutlog',
old_name='unit',
new_name='repetition_unit',
),
migrations.AddField(
model_name='setting',
name='weight_unit',
field=models.ForeignKey(
verbose_name='Unit', to='core.WeightUnit', default=1, on_delete=models.CASCADE
),
),
migrations.AddField(
model_name='workoutlog',
name='weight_unit',
field=models.ForeignKey(
verbose_name='Unit', to='core.WeightUnit', default=1, on_delete=models.CASCADE
),
),
]
| 1,057 | Python | .py | 33 | 21.939394 | 94 | 0.541176 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,487 | 0001_initial.py | wger-project_wger/wger/manager/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
import wger.utils.fields
import datetime
from django.conf import settings
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('exercises', '0001_initial'),
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Day',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'description',
models.CharField(
help_text='Ususally a description about what parts are trained, like "Arms" or "Pull Day"',
max_length=100,
verbose_name='Description',
),
),
('day', models.ManyToManyField(to='core.DaysOfWeek', verbose_name='Day')),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name='Schedule',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'name',
models.CharField(
help_text="Name or short description of the schedule. For example 'Program XYZ'.",
max_length=100,
verbose_name='Name',
),
),
(
'start_date',
wger.utils.fields.Html5DateField(
default=datetime.date.today, verbose_name='Start date'
),
),
(
'is_active',
models.BooleanField(
default=True,
help_text='Tick the box if you want to mark this schedule as your active one (will be shown e.g. on your dashboard). All other schedules will then be marked as inactive',
verbose_name='Schedule active',
),
),
(
'is_loop',
models.BooleanField(
default=False,
help_text='Tick the box if you want to repeat the schedules in a loop (i.e. A, B, C, A, B, C, and so on)',
verbose_name='Is loop',
),
),
(
'user',
models.ForeignKey(
editable=False,
to=settings.AUTH_USER_MODEL,
verbose_name='User',
on_delete=models.CASCADE,
),
),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name='ScheduleStep',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'duration',
models.IntegerField(
default=4,
help_text='The duration in weeks',
verbose_name='Duration',
validators=[
django.core.validators.MinValueValidator(1),
django.core.validators.MaxValueValidator(25),
],
),
),
('order', models.IntegerField(default=1, max_length=1, verbose_name='Order')),
(
'schedule',
models.ForeignKey(
verbose_name='schedule', to='manager.Schedule', on_delete=models.CASCADE
),
),
],
options={
'ordering': ['order'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Set',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('order', models.IntegerField(null=True, verbose_name='Order', blank=True)),
(
'sets',
models.IntegerField(
default=4,
verbose_name='Number of sets',
validators=[
django.core.validators.MinValueValidator(0),
django.core.validators.MaxValueValidator(10),
],
),
),
(
'exerciseday',
models.ForeignKey(
verbose_name='Exercise day', to='manager.Day', on_delete=models.CASCADE
),
),
(
'exercises',
models.ManyToManyField(to='exercises.Exercise', verbose_name='Exercises'),
),
],
options={
'ordering': ['order'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Setting',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'reps',
models.IntegerField(
verbose_name='Repetitions',
validators=[
django.core.validators.MinValueValidator(0),
django.core.validators.MaxValueValidator(100),
],
),
),
('order', models.IntegerField(verbose_name='Order', blank=True)),
('comment', models.CharField(max_length=100, verbose_name='Comment', blank=True)),
(
'exercise',
models.ForeignKey(
verbose_name='Exercises', to='exercises.Exercise', on_delete=models.CASCADE
),
),
(
'set',
models.ForeignKey(
verbose_name='Sets', to='manager.Set', on_delete=models.CASCADE
),
),
],
options={
'ordering': ['order', 'id'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Workout',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'creation_date',
models.DateField(auto_now_add=True, verbose_name='Creation date'),
),
(
'comment',
models.CharField(
help_text="A short description or goal of the workout. For example 'Focus on back' or 'Week 1 of program xy'.",
max_length=100,
verbose_name='Description',
blank=True,
),
),
(
'user',
models.ForeignKey(
verbose_name='User', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE
),
),
],
options={
'ordering': ['-creation_date'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='WorkoutLog',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'reps',
models.IntegerField(
verbose_name='Repetitions',
validators=[django.core.validators.MinValueValidator(0)],
),
),
(
'weight',
models.DecimalField(
verbose_name='Weight',
max_digits=5,
decimal_places=2,
validators=[django.core.validators.MinValueValidator(0)],
),
),
('date', wger.utils.fields.Html5DateField(verbose_name='Date')),
(
'exercise',
models.ForeignKey(
verbose_name='Exercise', to='exercises.Exercise', on_delete=models.CASCADE
),
),
(
'user',
models.ForeignKey(
editable=False,
to=settings.AUTH_USER_MODEL,
verbose_name='User',
on_delete=models.CASCADE,
),
),
(
'workout',
models.ForeignKey(
verbose_name='Workout', to='manager.Workout', on_delete=models.CASCADE
),
),
],
options={
'ordering': ['date', 'reps'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='WorkoutSession',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('date', wger.utils.fields.Html5DateField(verbose_name='Date')),
(
'notes',
models.TextField(
help_text='Any notes you might want to save about this workout session.',
null=True,
verbose_name='Notes',
blank=True,
),
),
(
'impression',
models.CharField(
default=b'2',
help_text='Your impression about this workout session. Did you exercise as well as you could?',
max_length=2,
verbose_name='General impression',
choices=[(b'1', 'Bad'), (b'2', 'Neutral'), (b'3', 'Good')],
),
),
('time_start', models.TimeField(null=True, verbose_name='Start time', blank=True)),
('time_end', models.TimeField(null=True, verbose_name='Finish time', blank=True)),
(
'user',
models.ForeignKey(
verbose_name='User', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE
),
),
(
'workout',
models.ForeignKey(
verbose_name='Workout', to='manager.Workout', on_delete=models.CASCADE
),
),
],
options={
'ordering': ['date'],
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='workoutsession',
unique_together=set([('date', 'user')]),
),
migrations.AddField(
model_name='schedulestep',
name='workout',
field=models.ForeignKey(to='manager.Workout', on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AddField(
model_name='day',
name='training',
field=models.ForeignKey(
verbose_name='Workout', to='manager.Workout', on_delete=models.CASCADE
),
preserve_default=True,
),
]
| 13,062 | Python | .py | 352 | 18.857955 | 194 | 0.394144 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,488 | 0015_auto_20211028_1113.py | wger-project_wger/wger/manager/migrations/0015_auto_20211028_1113.py | # Generated by Django 3.2.3 on 2021-10-28 09:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0014_auto_20210717_1858'),
]
operations = [
migrations.AlterField(
model_name='set',
name='order',
field=models.IntegerField(default=1, verbose_name='Order'),
),
migrations.AlterField(
model_name='workout',
name='is_public',
field=models.BooleanField(
default=False,
help_text='A public template is available to other users',
verbose_name='Public template',
),
),
migrations.AlterField(
model_name='workout',
name='is_template',
field=models.BooleanField(
default=False,
help_text='Marking a workout as a template will freeze it and allow you to make copies of it',
verbose_name='Workout template',
),
),
]
| 1,069 | Python | .py | 31 | 23.677419 | 110 | 0.55706 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,489 | 0009_auto_20201202_1559.py | wger-project_wger/wger/manager/migrations/0009_auto_20201202_1559.py | # Generated by Django 3.1.3 on 2020-12-02 14:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0008_auto_20190618_1617'),
]
operations = [
migrations.AddField(
model_name='setting',
name='rir',
field=models.DecimalField(
blank=True,
choices=[
(None, '------'),
(0, 0),
(0.5, 0.5),
(1, 1),
(1.5, 1.5),
(2, 2),
(2.5, 2.5),
(3, 3),
(3.5, 3.5),
(4, 4),
],
decimal_places=1,
max_digits=3,
null=True,
verbose_name='RiR',
),
),
migrations.AddField(
model_name='workoutlog',
name='rir',
field=models.DecimalField(
blank=True,
choices=[
(None, '------'),
(0, 0),
(0.5, 0.5),
(1, 1),
(1.5, 1.5),
(2, 2),
(2.5, 2.5),
(3, 3),
(3.5, 3.5),
(4, 4),
],
decimal_places=1,
max_digits=3,
null=True,
verbose_name='RiR',
),
),
]
| 1,551 | Python | .py | 54 | 13.277778 | 47 | 0.311453 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,490 | 0017_alter_workoutlog_exercise_base.py | wger-project_wger/wger/manager/migrations/0017_alter_workoutlog_exercise_base.py | # Generated by Django 3.2.13 on 2022-05-28 22:29
from django.db import migrations, models
import django.db.models.deletion
# Mapping of bases that should be migrated
# -> (old_base, new_base)
base_mapping = [
(
'201edd07-93f8-474b-8db0-e13e5283ee2b',
'1b9ed9da-46d1-4484-8acc-236379ee823c',
), # Kabelziehen Über Kreuz
('b7b690a7-2e65-40f9-a9cb-e61501a72fed', 'b16e3e5d-8401-4d2b-919c-15b536f9ec5e'), # Kabelzug
('713ee452-2775-4a68-8a7c-f1d22b5cd469', '00fcf603-b0d0-48d2-9b5e-c7f0d510d46c'), # Rudern eng
(
'4ceb1ba5-1ce1-4fe3-b60a-5d0e173a2ab3',
'61950a59-be4e-43cc-abc1-cb52abd15354',
), # Leg extension
(
'27d322ba-cbf5-44fa-a3bc-1999c6711757',
'058945bb-7fa8-4724-95fb-51ee8df20929',
), # Beinstrecker
(
'557ae429-100d-4d5b-a173-e5186fa2d9bc',
'13234b53-ea0c-41f1-9069-776865ea8eff',
), # Trizepsdrücken KH Über Kopf
(
'455fc17f-dc4c-4516-a335-8286958e7a7b',
'09dd3e3c-e53a-4e2c-a2e3-645d334f53e2',
), # Triceps Dips
(
'a1d4f524-b6ca-4dd3-9998-41200f01b634',
'3db63138-a047-4a4d-b616-1a0b7dfca105',
), # Close-grip Bench Press
(
'69378ddf-377d-4624-b500-3406682a84e4',
'275fb49f-975c-4d6e-9d63-2c86ed740f40',
), # Incline Bench Press
(
'64d772ea-f21a-47c1-8660-d6b9366d1900',
'57e17672-52b9-43cf-8d0d-4b3f06a0c0d0',
), # Incline Bench Press - Dumbbell
('6a496c73-721d-4ed2-9f7f-337e8ad2b388', '09dd3e3c-e53a-4e2c-a2e3-645d334f53e2'), # Dips
(
'133f7a01-dd9f-45d5-af67-1d1af134d99b',
'4af6dbd9-8991-484b-9810-68f117c21edf',
), # Bent Over Barbell Row
(
'8f7b6fce-4a75-42fc-b217-efe44e349fdc',
'94a5c406-7bcd-47f3-9687-bdf92a763932',
), # Einarmiges Rudern KH
('7a69e726-cdb2-4f0a-b9bd-a9c560d04a03', '7ce443b6-eb84-4f65-b05f-461c1cc8bcc0'), # Calf raises
(
'c323d8a4-310f-4381-925c-3893ef5f8422',
'63fbb8e5-6ebc-4def-8844-3e65e097213b',
), # Latzug Eng im Untergriff Zur Brust
(
'c29884c8-a4fd-4491-8bfd-2dac88aa7184',
'34fc154f-cc8d-4e52-adb7-ff0dad2d0770',
), # Latzug Breit Zur Brust
(
'9e694c44-2462-430d-8108-6982fd681ade',
'63fbb8e5-6ebc-4def-8844-3e65e097213b',
), # Lat Pulldown
('2d806ebb-9aa3-449b-9056-218f5bbbc7f8', 'a2f5b6ef-b780-49c0-8d96-fdaff23e27ce'), # Squat
('a2f5b6ef-b780-49c0-8d96-fdaff23e27ce', 'a2f5b6ef-b780-49c0-8d96-fdaff23e27ce'), # Squat
(
'5912d7ed-6a0e-4b4c-b30a-fc9f3f890fc1',
'5912d7ed-6a0e-4b4c-b30a-fc9f3f890fc1',
), # Shoulder Press, on Machine
('9b210eb3-6ff0-4a57-8e26-e89da8751c19', '63375f5b-2d81-471c-bea4-fc3d207e96cb'), # Side Raise
('39ba20a7-14c7-44fe-b6c8-6ce9c83b4c38', '52dec48d-25a4-4a78-b66b-ad6a773e143a'), # Power Clean
(
'058945bb-7fa8-4724-95fb-51ee8df20929',
'058945bb-7fa8-4724-95fb-51ee8df20929',
), # Leg Extension
(
'49859097-644a-417a-8cb7-491b7d8bc383',
'53906cd1-61f1-4d56-ac60-e4fcc5824861',
), # Adduktoren Maschine
(
'b955b629-5c57-4f98-b200-e96e138c300f',
'5f514f9e-6bd9-408e-85b2-c25eb04af33b',
), # Beinheben Aufrecht
(
'5f8370d9-aa89-4dcc-9d97-d9da86a2f183',
'9b993e99-8701-43f0-84d6-689123183880',
), # Beinheben im Hang
(
'5b14e0f0-1131-4ad9-9821-5703f1370bc5',
'9e34bc01-9cec-4ee2-a9bb-9c937a471c24',
), # Beinheben Liegend
(
'e878ecf3-fbb2-4f0e-a546-9769c7ff3241',
'2e7ffff9-e603-4b28-98c8-31d1a6ce8cd9',
), # Rumänisches Kreuzheben
(
'24b62fb4-0158-486e-89f1-9a5f1db234ef',
'32c129f7-cc28-4ebc-8465-e4fa62e220b1',
), # T-Bar Rudern (breit)
(
'515cb39c-fead-4b59-a4ba-a10c5b0b8c84',
'9c35594c-bbcc-4656-bdcb-376814c90e96',
), # Frontheben am Kabel
(
'cfeedd4f-84e3-402c-a105-ec985658c927',
'591992cb-48ee-4b39-b790-e05b4a2c11e3',
), # Weighted Step
(
'6c86a314-bf0e-4b31-aea7-40891fa5288a',
'2f7149c3-77ce-4313-a59c-aef82b5a730a',
), # Lat-Ziehen Mit Gesteckten Armen am Seilzug
(
'09ed42ad-5523-424d-bd64-c439694a65fe',
'63375f5b-2d81-471c-bea4-fc3d207e96cb',
), # Shoulder Fly
(
'73405d63-a539-486e-996e-1e72572fbe5d',
'6e00afb6-272d-44a2-8ae3-e7fa41b50f06',
), # Pull-Over KH
(
'9ae8772d-570c-4d16-abd4-34f5d5081e4e',
'6f79b381-98a4-40d5-8a45-3bb0558be6fe',
), # Seitheben Kurzhantel Vorgebeugt
(
'31f51ab6-94a6-436f-9d41-632d85b7e01f',
'141bc870-56be-4749-a3b9-e56d5d5618b4',
), # Frontdrücken MP
(
'a68c991c-ac42-47c8-9a84-9b288a4a7a76',
'5d40c67d-be59-4092-9c9c-301ca5310e2b',
), # Rudern Aufrecht ß-Stange
]
def migrate_bases(apps, schema_editor):
"""
Migrates the used bases
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
WorkoutLog = apps.get_model('manager', 'WorkoutLog')
Setting = apps.get_model('manager', 'Setting')
Base = apps.get_model('exercises', 'ExerciseBase')
for mapping in base_mapping:
try:
base_old = Base.objects.get(uuid=mapping[0])
base_new = Base.objects.get(uuid=mapping[1])
except Base.DoesNotExist:
# print(f'Could not load base {base_old} or {base_new}')
continue
WorkoutLog.objects.filter(exercise_base=base_old).update(exercise_base=base_new)
Setting.objects.filter(exercise_base=base_old).update(exercise_base=base_new)
class Migration(migrations.Migration):
dependencies = [
('exercises', '0019_exercise_crowdsourcing_changes'),
('manager', '0016_move_to_exercise_base'),
]
operations = [
migrations.AlterField(
model_name='workoutlog',
name='exercise_base',
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercisebase',
verbose_name='Exercise',
),
),
migrations.RunPython(migrate_bases),
]
| 6,233 | Python | .py | 166 | 30.457831 | 100 | 0.650033 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,491 | 0007_auto_20160311_2258.py | wger-project_wger/wger/manager/migrations/0007_auto_20160311_2258.py | # -*- coding: utf-8 -*-
from django.db import migrations, models
def convert_logs(apps, schema_editor):
"""
Adds a unit to users who have imperial units in the profile
"""
WorkoutLog = apps.get_model('manager', 'WorkoutLog')
UserProfile = apps.get_model('core', 'UserProfile')
for profile in UserProfile.objects.filter(weight_unit='lb'):
WorkoutLog.objects.filter(user=profile.user).update(weight_unit=2)
def convert_settings(apps, schema_editor):
"""
Adds a unit to workout settings that have 99 for 'until failure'
"""
Setting = apps.get_model('manager', 'Setting')
Setting.objects.filter(reps=99).update(reps=1, repetition_unit=2)
class Migration(migrations.Migration):
dependencies = [
('manager', '0006_auto_20160303_2138'),
]
operations = [
migrations.RunPython(convert_logs, reverse_code=migrations.RunPython.noop),
migrations.RunPython(convert_settings, reverse_code=migrations.RunPython.noop),
]
| 1,008 | Python | .py | 24 | 36.708333 | 87 | 0.705036 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,492 | 0014_auto_20210717_1858.py | wger-project_wger/wger/manager/migrations/0014_auto_20210717_1858.py | # Generated by Django 3.2.3 on 2021-07-17 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0013_set_comment'),
]
operations = [
migrations.AddField(
model_name='workout',
name='is_public',
field=models.BooleanField(default=False, help_text='', verbose_name='Public Template'),
),
migrations.AddField(
model_name='workout',
name='is_template',
field=models.BooleanField(default=False, help_text='', verbose_name='Workout Template'),
),
]
| 636 | Python | .py | 18 | 27 | 100 | 0.610749 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,493 | 0002_auto_20150202_2040.py | wger-project_wger/wger/manager/migrations/0002_auto_20150202_2040.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from sortedm2m.operations import AlterSortedManyToManyField
import sortedm2m.fields
class Migration(migrations.Migration):
dependencies = [
('manager', '0001_initial'),
]
operations = [
AlterSortedManyToManyField(
model_name='set',
name='exercises',
field=sortedm2m.fields.SortedManyToManyField(
help_text=None, to='exercises.Exercise', verbose_name='Exercises'
),
preserve_default=True,
)
]
| 577 | Python | .py | 18 | 24.388889 | 81 | 0.63964 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,494 | 0005_auto_20160303_2008.py | wger-project_wger/wger/manager/migrations/0005_auto_20160303_2008.py | # -*- coding: utf-8 -*-
from django.db import migrations, models
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('core', '0007_repetitionunit'),
('manager', '0004_auto_20150609_1603'),
]
operations = [
migrations.AddField(
model_name='setting',
name='unit',
field=models.ForeignKey(
verbose_name='Unit', default=1, to='core.RepetitionUnit', on_delete=models.CASCADE
),
),
migrations.AddField(
model_name='workoutlog',
name='unit',
field=models.ForeignKey(
verbose_name='Unit', default=1, to='core.RepetitionUnit', on_delete=models.CASCADE
),
),
migrations.AlterField(
model_name='day',
name='description',
field=models.CharField(
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")',
max_length=100,
),
),
migrations.AlterField(
model_name='schedule',
name='is_loop',
field=models.BooleanField(
verbose_name='Is a loop',
default=False,
help_text='Tick the box if you want to repeat the schedules in a loop (i.e. A, B, C, A, B, C, and so on)',
),
),
migrations.AlterField(
model_name='schedulestep',
name='order',
field=models.IntegerField(verbose_name='Order', default=1),
),
migrations.AlterField(
model_name='setting',
name='reps',
field=models.IntegerField(
verbose_name='Amount',
validators=[
django.core.validators.MinValueValidator(0),
django.core.validators.MaxValueValidator(100),
],
),
),
migrations.AlterField(
model_name='workoutsession',
name='impression',
field=models.CharField(
verbose_name='General impression',
default='2',
choices=[('1', 'Bad'), ('2', 'Neutral'), ('3', 'Good')],
help_text='Your impression about this workout session. Did you exercise as well as you could?',
max_length=2,
),
),
]
| 2,523 | Python | .py | 69 | 24.434783 | 141 | 0.522041 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,495 | ical.py | wger-project_wger/wger/manager/views/ical.py | # -*- 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 datetime
import logging
# Django
from django.contrib.sites.models import Site
from django.http import (
HttpResponse,
HttpResponseForbidden,
)
from django.shortcuts import get_object_or_404
# Third Party
from icalendar import (
Calendar,
Event,
)
from icalendar.tools import UIDGenerator
# wger
from wger import get_version
from wger.manager.models import (
Schedule,
Workout,
)
from wger.utils.helpers import (
check_token,
next_weekday,
)
logger = logging.getLogger(__name__)
"""
Exports workouts and schedules as an iCal file that can be imported to a
calendaring application.
The icalendar module has atrocious documentation, to get the slightest chance
to make this work, looking at the module test files or the official RF is
*really* the only way....
* https://tools.ietf.org/html/rfc5545
* https://github.com/collective/icalendar/tree/master/src/icalendar/tests
"""
# Helper functions
def get_calendar():
"""
Creates and returns a calendar object
:return: Calendar
"""
calendar = Calendar()
calendar.add('prodid', '-//wger Workout Manager//wger.de//')
calendar.add('version', get_version())
return calendar
def get_events_workout(calendar, workout, duration, start_date=None):
"""
Creates all necessary events from the given workout and adds them to
the calendar. Each event's occurrence ist set to weekly (one event for
each training day).
:param calendar: calendar to add events to
:param workout: Workout
:param duration: duration in weeks
:param start_date: start date, default: profile default
:return: None
"""
start_date = start_date if start_date else workout.creation_date
end_date = start_date + datetime.timedelta(weeks=duration)
generator = UIDGenerator()
site = Site.objects.get_current()
for day in workout.day_set.all():
# Make the description of the event with the day's exercises
description_list = []
for set_obj in day.set_set.all():
for base in set_obj.exercise_bases:
description_list.append(str(base.get_translation()))
description = ', '.join(description_list) if description_list else day.description
# Make an event for each weekday
for weekday in day.day.all():
event = Event()
event.add('summary', day.description)
event.add('description', description)
event.add('dtstart', next_weekday(start_date, weekday.id - 1))
event.add('dtend', next_weekday(start_date, weekday.id - 1))
event.add('rrule', {'freq': 'weekly', 'until': end_date})
event['uid'] = generator.uid(host_name=site.domain)
event.add('priority', 5)
calendar.add_component(event)
# Views
def export(request, pk, uidb64=None, token=None):
"""
Export the current workout as an iCal file
"""
# Load the workout
if uidb64 is not None and token is not None:
if check_token(uidb64, token):
workout = get_object_or_404(Workout, pk=pk)
else:
return HttpResponseForbidden()
else:
if request.user.is_anonymous:
return HttpResponseForbidden()
workout = get_object_or_404(Workout, pk=pk, user=request.user)
# Create the calendar
calendar = get_calendar()
# Create the events and add them to the calendar
get_events_workout(calendar, workout, workout.user.userprofile.workout_duration)
# Send the file to the user
response = HttpResponse(content_type='text/calendar')
response['Content-Disposition'] = f'attachment; filename=Calendar-workout-{workout.pk}.ics'
response.write(calendar.to_ical())
response['Content-Length'] = len(response.content)
return response
def export_schedule(request, pk, uidb64=None, token=None):
"""
Export the current schedule as an iCal file
"""
# Load the schedule
if uidb64 is not None and token is not None:
if check_token(uidb64, token):
schedule = get_object_or_404(Schedule, pk=pk)
else:
return HttpResponseForbidden()
else:
if request.user.is_anonymous:
return HttpResponseForbidden()
schedule = get_object_or_404(Schedule, pk=pk, user=request.user)
# Create the calendar
calendar = get_calendar()
# Create the events and add them to the calendar
start_date = datetime.date.today()
for step in schedule.schedulestep_set.all():
get_events_workout(calendar, step.workout, step.duration, start_date)
start_date = start_date + datetime.timedelta(weeks=step.duration)
# Send the file to the user
response = HttpResponse(content_type='text/calendar')
response['Content-Disposition'] = f'attachment; filename=Calendar-schedule-{schedule.pk}.ics'
response.write(calendar.to_ical())
response['Content-Length'] = len(response.content)
return response
| 5,670 | Python | .py | 145 | 33.813793 | 97 | 0.703549 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,496 | pdf.py | wger-project_wger/wger/manager/views/pdf.py | # -*- 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.http import (
HttpResponse,
HttpResponseForbidden,
)
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _
# Third Party
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.platypus import (
Paragraph,
SimpleDocTemplate,
Spacer,
)
# wger
from wger.manager.helpers import render_workout_day
from wger.manager.models import Workout
from wger.utils.helpers import check_token
from wger.utils.pdf import (
get_logo,
render_footer,
styleSheet,
)
logger = logging.getLogger(__name__)
def workout_log(request, id, images=False, comments=False, uidb64=None, token=None):
"""
Generates a PDF with the contents of the given workout
See also
* http://www.blog.pythonlibrary.org/2010/09/21/reportlab
* http://www.reportlab.com/apis/reportlab/dev/platypus.html
"""
comments = bool(int(comments))
images = bool(int(images))
# Load the workout
if uidb64 is not None and token is not None:
if check_token(uidb64, token):
workout = get_object_or_404(Workout, pk=id)
else:
return HttpResponseForbidden()
else:
if request.user.is_anonymous:
return HttpResponseForbidden()
workout = get_object_or_404(Workout, pk=id, user=request.user)
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
# Create the PDF object, using the response object as its "file."
doc = SimpleDocTemplate(
response,
pagesize=A4,
# pagesize = landscape(A4),
leftMargin=cm,
rightMargin=cm,
topMargin=0.5 * cm,
bottomMargin=0.5 * cm,
title=_('Workout'),
author='wger Workout Manager',
subject=_('Workout for %s') % request.user.username,
)
# container for the 'Flowable' objects
elements = []
# Add site logo
elements.append(get_logo())
elements.append(Spacer(10 * cm, 0.5 * cm))
# Set the title
p = Paragraph(
f'<para align="center"><strong>{workout.name}</strong></para>', styleSheet['HeaderBold']
)
elements.append(p)
elements.append(Spacer(10 * cm, 0.5 * cm))
if workout.description:
p = Paragraph(f'<para align="center">{workout.description}</para>')
elements.append(p)
elements.append(Spacer(10 * cm, 1.5 * cm))
# Iterate through the Workout and render the training days
for day in workout.day_set.all():
elements.append(render_workout_day(day, images=images, comments=comments))
elements.append(Spacer(10 * cm, 0.5 * cm))
# Footer, date and info
elements.append(Spacer(10 * cm, 0.5 * cm))
elements.append(render_footer(request.build_absolute_uri(workout.get_absolute_url())))
# write the document and send the response to the browser
doc.build(elements)
# Create the HttpResponse object with the appropriate PDF headers.
response['Content-Disposition'] = f'attachment; filename=Workout-{id}-log.pdf'
response['Content-Length'] = len(response.content)
return response
def workout_view(request, id, images=False, comments=False, uidb64=None, token=None):
"""
Generates a PDF with the contents of the workout, without table for logs
"""
"""
Generates a PDF with the contents of the given workout
See also
* http://www.blog.pythonlibrary.org/2010/09/21/reportlab
* http://www.reportlab.com/apis/reportlab/dev/platypus.html
"""
comments = bool(int(comments))
images = bool(int(images))
# Load the workout
if uidb64 is not None and token is not None:
if check_token(uidb64, token):
workout = get_object_or_404(Workout, pk=id)
else:
return HttpResponseForbidden()
else:
if request.user.is_anonymous:
return HttpResponseForbidden()
workout = get_object_or_404(Workout, pk=id, user=request.user)
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
# Create the PDF object, using the response object as its "file."
doc = SimpleDocTemplate(
response,
pagesize=A4,
leftMargin=cm,
rightMargin=cm,
topMargin=0.5 * cm,
bottomMargin=0.5 * cm,
title=_('Workout'),
author='wger Workout Manager',
subject=_('Workout for %s') % request.user.username,
)
# container for the 'Flowable' objects
elements = []
# Add site logo
elements.append(get_logo())
elements.append(Spacer(10 * cm, 0.5 * cm))
# Set the title
p = Paragraph(
'<para align="center"><strong>%(description)s</strong></para>' % {'description': workout},
styleSheet['HeaderBold'],
)
elements.append(p)
elements.append(Spacer(10 * cm, 1.5 * cm))
# Iterate through the Workout and render the training days
for day in workout.day_set.all():
elements.append(render_workout_day(day, images=images, comments=comments, only_table=True))
elements.append(Spacer(10 * cm, 0.5 * cm))
# Footer, date and info
elements.append(Spacer(10 * cm, 0.5 * cm))
elements.append(render_footer(request.build_absolute_uri(workout.get_absolute_url())))
# write the document and send the response to the browser
doc.build(elements)
# Create the HttpResponse object with the appropriate PDF headers.
response['Content-Disposition'] = f'attachment; filename=Workout-{id}-table.pdf'
response['Content-Length'] = len(response.content)
return response
| 6,401 | Python | .py | 164 | 33.493902 | 99 | 0.690572 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,497 | set.py | wger-project_wger/wger/manager/views/set.py | # -*- 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)
| 6,801 | Python | .py | 188 | 28.888298 | 93 | 0.635203 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,498 | workout_session.py | wger-project_wger/wger/manager/views/workout_session.py | # -*- 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 datetime
import logging
# Django
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import (
HttpResponseBadRequest,
HttpResponseForbidden,
)
from django.urls import (
reverse,
reverse_lazy,
)
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import (
CreateView,
DeleteView,
UpdateView,
)
# wger
from wger.manager.forms import WorkoutSessionForm
from wger.manager.models import (
Workout,
WorkoutLog,
WorkoutSession,
)
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
)
logger = logging.getLogger(__name__)
"""
Workout session
"""
class WorkoutSessionUpdateView(WgerFormMixin, LoginRequiredMixin, UpdateView):
"""
Generic view to edit an existing workout session entry
"""
model = WorkoutSession
form_class = WorkoutSessionForm
def get_context_data(self, **kwargs):
context = super(WorkoutSessionUpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit workout impression for {0}').format(self.object.date)
return context
def get_success_url(self):
return reverse('manager:workout:calendar')
class WorkoutSessionAddView(WgerFormMixin, LoginRequiredMixin, CreateView):
"""
Generic view to add a new workout session entry
"""
model = WorkoutSession
form_class = WorkoutSessionForm
def get_date(self):
"""
Returns a date object from the URL parameters or None if no date
could be created
"""
try:
date = datetime.date(
int(self.kwargs['year']),
int(self.kwargs['month']),
int(self.kwargs['day']),
)
except ValueError:
date = None
return date
def dispatch(self, request, *args, **kwargs):
"""
Check for ownership
"""
workout = Workout.objects.get(pk=kwargs['workout_pk'])
if workout.get_owner_object().user != request.user:
return HttpResponseForbidden()
if not self.get_date():
return HttpResponseBadRequest('You need to use a valid date')
return super(WorkoutSessionAddView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(WorkoutSessionAddView, self).get_context_data(**kwargs)
context['title'] = _('New workout impression for the {0}'.format(self.get_date()))
return context
def get_success_url(self):
return reverse('manager:workout:calendar')
def form_valid(self, form):
"""
Set the workout and the user
"""
workout = Workout.objects.get(pk=self.kwargs['workout_pk'])
form.instance.workout = workout
form.instance.user = self.request.user
form.instance.date = self.get_date()
return super(WorkoutSessionAddView, self).form_valid(form)
class WorkoutSessionDeleteView(WgerDeleteMixin, LoginRequiredMixin, DeleteView):
"""
Generic view to delete a workout routine
"""
model = WorkoutSession
success_url = reverse_lazy('manager:workout:overview')
messages = gettext_lazy('Successfully deleted')
def form_valid(self, form):
"""
Delete the workout session and, if wished, all associated weight logs as well
"""
if self.kwargs.get('logs') == 'logs':
WorkoutLog.objects.filter(user=self.request.user, date=self.get_object().date).delete()
return super().form_valid(form)
def get_context_data(self, **kwargs):
logs = '' if not self.kwargs.get('logs') else self.kwargs['logs']
context = super(WorkoutSessionDeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete {0}?').format(self.object)
if logs == 'logs':
self.delete_message_extra = _('This will delete all weight logs for this day as well.')
return context
| 4,703 | Python | .py | 129 | 30.511628 | 99 | 0.682658 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,499 | workout.py | wger-project_wger/wger/manager/views/workout.py | # -*- 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 copy
import logging
# Django
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import (
HttpResponseForbidden,
HttpResponseRedirect,
)
from django.shortcuts import (
get_object_or_404,
render,
)
from django.template.context_processors import csrf
from django.urls import (
reverse,
reverse_lazy,
)
from django.utils.text import slugify
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import (
DeleteView,
UpdateView,
)
# Third Party
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
# wger
from wger.manager.forms import (
WorkoutCopyForm,
WorkoutForm,
WorkoutMakeTemplateForm,
)
from wger.manager.models import (
Schedule,
Workout,
WorkoutLog,
)
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
)
from wger.utils.helpers import make_token
logger = logging.getLogger(__name__)
# ************************
# Workout functions
# ************************
@login_required
def template_overview(request):
""" """
return render(
request,
'workout/overview.html',
{
'workouts': Workout.templates.filter(user=request.user),
'title': _('Your templates'),
'template_overview': True,
},
)
@login_required
def public_template_overview(request):
""" """
return render(
request,
'workout/overview.html',
{
'workouts': Workout.templates.filter(is_public=True),
'title': _('Public templates'),
'template_overview': True,
},
)
def view(request, pk):
"""
Show the workout with the given ID
"""
workout = get_object_or_404(Workout, pk=pk)
user = workout.user
is_owner = request.user == user
if not is_owner and not user.userprofile.ro_access:
return HttpResponseForbidden()
uid, token = make_token(user)
context = {
'workout': workout,
'uid': uid,
'token': token,
'is_owner': is_owner,
'owner_user': user,
}
return render(request, 'workout/view.html', context)
@login_required()
def template_view(request, pk):
"""
Show the template with the given ID
"""
template = get_object_or_404(Workout.templates, pk=pk)
if not template.is_public and request.user != template.user:
return HttpResponseForbidden()
context = {
'workout': template,
'muscles': template.canonical_representation['muscles'],
'is_owner': template.user == request.user,
'owner_user': template.user,
}
return render(request, 'workout/template_view.html', context)
@login_required
def copy_workout(request, pk):
"""
Makes a copy of a workout
"""
workout = get_object_or_404(Workout.both, pk=pk)
if not workout.is_public and request.user != workout.user:
return HttpResponseForbidden()
# Process request
if request.method == 'POST':
workout_form = WorkoutCopyForm(request.POST)
if workout_form.is_valid():
# Copy workout
workout_copy: Workout = copy.copy(workout)
workout_copy.pk = None
workout_copy.name = workout_form.cleaned_data['name']
workout_copy.user = request.user
workout_copy.is_template = False
workout_copy.is_public = False
workout_copy.save()
# Copy the days
for day in workout.day_set.all():
day_copy = copy.copy(day)
day_copy.pk = None
day_copy.training = workout_copy
day_copy.save()
for i in day.day.all():
day_copy.day.add(i)
day_copy.save()
# Copy the sets
for current_set in day.set_set.all():
current_set_copy = copy.copy(current_set)
current_set_copy.pk = None
current_set_copy.exerciseday = day_copy
current_set_copy.save()
# Copy the settings
for current_setting in current_set.setting_set.all():
setting_copy = copy.copy(current_setting)
setting_copy.pk = None
setting_copy.set = current_set_copy
setting_copy.save()
return HttpResponseRedirect(workout_copy.get_absolute_url())
else:
workout_form = WorkoutCopyForm({'name': workout.name, 'description': workout.description})
workout_form.helper = FormHelper()
workout_form.helper.form_id = slugify(request.path)
workout_form.helper.form_method = 'post'
workout_form.helper.form_action = request.path
workout_form.helper.add_input(
Submit('submit', _('Save'), css_class='btn-success btn-block')
)
workout_form.helper.form_class = 'wger-form'
template_data = {}
template_data.update(csrf(request))
template_data['title'] = _('Copy workout')
template_data['form'] = workout_form
template_data['form_fields'] = [workout_form['name']]
template_data['submit_text'] = _('Copy')
return render(request, 'form.html', template_data)
def make_workout(request, pk):
workout = get_object_or_404(Workout.both, pk=pk)
if request.user != workout.user:
return HttpResponseForbidden()
workout.is_template = False
workout.is_public = False
workout.save()
return HttpResponseRedirect(workout.get_absolute_url())
@login_required
def add(request):
"""
Add a new workout and redirect to its page
"""
workout = Workout()
workout.user = request.user
workout.save()
return HttpResponseRedirect(workout.get_absolute_url())
class WorkoutDeleteView(WgerDeleteMixin, LoginRequiredMixin, DeleteView):
"""
Generic view to delete a workout routine
"""
model = Workout
success_url = reverse_lazy('manager:workout:overview')
messages = gettext_lazy('Successfully deleted')
def get_context_data(self, **kwargs):
context = super(WorkoutDeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete {0}?').format(self.object)
return context
class WorkoutEditView(WgerFormMixin, LoginRequiredMixin, UpdateView):
"""
Generic view to update an existing workout routine
"""
model = Workout
form_class = WorkoutForm
def get_context_data(self, **kwargs):
context = super(WorkoutEditView, self).get_context_data(**kwargs)
context['title'] = _('Edit {0}').format(self.object)
return context
class WorkoutMarkAsTemplateView(WgerFormMixin, LoginRequiredMixin, UpdateView):
"""
Generic view to update an existing workout routine
"""
model = Workout
form_class = WorkoutMakeTemplateForm
def get_context_data(self, **kwargs):
context = super(WorkoutMarkAsTemplateView, self).get_context_data(**kwargs)
context['title'] = _('Mark as template')
return context
| 7,951 | Python | .py | 229 | 27.864629 | 98 | 0.648194 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |