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,600 | test_sync.py | wger-project_wger/wger/nutrition/tests/test_sync.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
from unittest.mock import patch
from uuid import UUID
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.nutrition.models import Ingredient
from wger.nutrition.sync import sync_ingredients
from wger.utils.requests import wger_headers
class MockIngredientResponse:
def __init__(self):
self.status_code = 200
self.content = b'1234'
# yapf: disable
@staticmethod
def json():
return {
"count": 2,
"next": None,
"previous": None,
"results": [
{
"id": 1,
"uuid": "7908c204-907f-4b1e-ad4e-f482e9769ade",
"code": "0013087245950",
"name": "Gâteau double chocolat",
"created": "2020-12-20T01:00:00+01:00",
"last_update": "2020-12-20T01:00:00+01:00",
"energy": 360,
"protein": "5.000",
"carbohydrates": "45.000",
"carbohydrates_sugar": "27.000",
"fat": "18.000",
"fat_saturated": "4.500",
"fiber": "2.000",
"sodium": "0.356",
"license": 5,
"license_title": " Gâteau double chocolat ",
"license_object_url": "",
"license_author": "Open Food Facts",
"license_author_url": "",
"license_derivative_source_url": "",
"language": 2
},
{
"id": 22634,
"uuid": "582f1b7f-a8bd-4951-9edd-247bc68b28f4",
"code": "3181238941963",
"name": "Maxi Hot Dog New York Style",
"created": "2020-12-20T01:00:00+01:00",
"last_update": "2020-12-20T01:00:00+01:00",
"energy": 256,
"protein": "11.000",
"carbohydrates": "27.000",
"carbohydrates_sugar": "5.600",
"fat": "11.000",
"fat_saturated": "4.600",
"fiber": None,
"sodium": "0.820",
"license": 5,
"license_title": " Maxi Hot Dog New York Style",
"license_object_url": "",
"license_author": "Open Food Facts",
"license_author_url": "",
"license_derivative_source_url": "",
"language": 3
},
]
}
# yapf: enable
class TestSyncMethods(WgerTestCase):
@patch('requests.get', return_value=MockIngredientResponse())
def test_ingredient_sync(self, mock_request):
# Arrange
ingredient = Ingredient.objects.get(pk=1)
self.assertEqual(Ingredient.objects.count(), 14)
self.assertEqual(ingredient.name, 'Test ingredient 1')
self.assertEqual(ingredient.energy, 176)
self.assertAlmostEqual(ingredient.protein, Decimal(25.63), 2)
self.assertEqual(ingredient.code, '1234567890987654321')
# Act
sync_ingredients(lambda x: x)
mock_request.assert_called_with(
'https://wger.de/api/v2/ingredient/?limit=999',
headers=wger_headers(),
)
# Assert
self.assertEqual(Ingredient.objects.count(), 15)
ingredient = Ingredient.objects.get(pk=1)
self.assertEqual(ingredient.name, 'Gâteau double chocolat')
self.assertEqual(ingredient.energy, 360)
self.assertAlmostEqual(ingredient.protein, Decimal(5), 2)
self.assertEqual(ingredient.code, '0013087245950')
self.assertEqual(ingredient.license.pk, 5)
self.assertEqual(ingredient.uuid, UUID('7908c204-907f-4b1e-ad4e-f482e9769ade'))
new_ingredient = Ingredient.objects.get(uuid='582f1b7f-a8bd-4951-9edd-247bc68b28f4')
self.assertEqual(new_ingredient.name, 'Maxi Hot Dog New York Style')
self.assertEqual(new_ingredient.energy, 256)
self.assertAlmostEqual(new_ingredient.protein, Decimal(11), 2)
self.assertEqual(new_ingredient.code, '3181238941963')
| 4,949 | Python | .py | 113 | 31.619469 | 92 | 0.567517 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,601 | test_nutritional_calculations.py | wger-project_wger/wger/nutrition/tests/test_nutritional_calculations.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 logging
from decimal import Decimal
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.nutrition import models
from wger.utils.constants import TWOPLACES
logger = logging.getLogger(__name__)
class NutritionalValuesCalculationsTestCase(WgerTestCase):
"""
Tests the nutritional values calculators in the different models
"""
def test_calculations(self):
plan = models.NutritionPlan(user_id=1)
plan.save()
meal = models.Meal(order=1)
meal.plan = plan
meal.save()
ingredient = models.Ingredient.objects.get(pk=1)
ingredient2 = models.Ingredient.objects.get(pk=2)
ingredient3 = models.Ingredient.objects.get(pk=2)
# One ingredient, 100 gr
item = models.MealItem()
item.meal = meal
item.ingredient = ingredient
item.weight_unit_id = None
item.amount = 100
item.order = 1
item.save()
item_values = item.get_nutritional_values()
self.assertAlmostEqual(item_values.energy, ingredient.energy, 2)
self.assertAlmostEqual(item_values.carbohydrates, ingredient.carbohydrates, 2)
self.assertAlmostEqual(item_values.carbohydrates_sugar, None, 2)
self.assertAlmostEqual(item_values.fat, ingredient.fat, 2)
self.assertAlmostEqual(item_values.fat_saturated, ingredient.fat_saturated, 2)
self.assertAlmostEqual(item_values.sodium, ingredient.sodium, 2)
self.assertAlmostEqual(item_values.fiber, None, 2)
meal_nutritional_values = meal.get_nutritional_values()
self.assertEqual(item_values, meal_nutritional_values)
plan_nutritional_values = plan.get_nutritional_values()
self.assertEqual(meal_nutritional_values.energy, plan_nutritional_values['total'].energy)
# One ingredient, 1 x unit 3
item.delete()
item = models.MealItem()
item.meal = meal
item.ingredient = ingredient
item.order = 1
item.amount = 1
item.weight_unit_id = 3
item.save()
item_values = item.get_nutritional_values()
self.assertAlmostEqual(item_values.energy, ingredient.energy * Decimal(12.0) / 100, 2)
meal_nutritional_values = meal.get_nutritional_values()
self.assertEqual(item_values, meal_nutritional_values)
plan_nutritional_values = plan.get_nutritional_values()
self.assertEqual(meal_nutritional_values, plan_nutritional_values['total'])
# Add another ingredient, 200 gr
item2 = models.MealItem()
item2.meal = meal
item2.ingredient = ingredient2
item2.weight_unit_id = None
item2.amount = 200
item2.order = 1
item2.save()
item2_values = item2.get_nutritional_values()
# result_total = {}
self.assertAlmostEqual(item2_values.energy, 2 * ingredient2.energy)
self.assertAlmostEqual(item2_values.carbohydrates, 2 * ingredient2.carbohydrates)
self.assertAlmostEqual(item2_values.fat, 2 * ingredient2.fat)
self.assertAlmostEqual(item2_values.protein, 2 * ingredient2.protein)
meal_nutritional_values = meal.get_nutritional_values()
plan_nutritional_values = plan.get_nutritional_values()
self.assertEqual(meal_nutritional_values, plan_nutritional_values['total'])
# Add another ingredient, 20 gr
item3 = models.MealItem()
item3.meal = meal
item3.ingredient = ingredient3
item3.weight_unit_id = None
item3.amount = 20
item3.order = 1
item3.save()
item3_values = item3.get_nutritional_values()
self.assertAlmostEqual(item3_values.energy, ingredient3.energy * Decimal(20.0) / 100, 2)
self.assertAlmostEqual(item3_values.protein, ingredient3.protein * Decimal(20.0) / 100, 2)
self.assertAlmostEqual(
item3_values.carbohydrates,
ingredient3.carbohydrates * Decimal(20.0) / 100,
2,
)
self.assertAlmostEqual(item3_values.fat, ingredient3.fat * Decimal(20.0) / 100, 2)
meal_nutritional_values = meal.get_nutritional_values()
plan_nutritional_values = plan.get_nutritional_values()
self.assertEqual(meal_nutritional_values, plan_nutritional_values['total'])
def test_calculations_user(self):
"""
Tests the calculations
:return:
"""
self.user_login('test')
plan = models.NutritionPlan.objects.get(pk=4)
values = plan.get_nutritional_values()
self.assertAlmostEqual(values['percent']['carbohydrates'], Decimal(29.79), 2)
self.assertAlmostEqual(values['percent']['fat'], Decimal(20.36), 2)
self.assertAlmostEqual(values['percent']['protein'], Decimal(26.06), 2)
self.assertAlmostEqual(values['per_kg']['carbohydrates'], Decimal(4.96), 2)
self.assertAlmostEqual(values['per_kg']['fat'], Decimal(1.51), 2)
self.assertAlmostEqual(values['per_kg']['protein'], Decimal(4.33), 2)
| 5,782 | Python | .py | 121 | 40.115702 | 98 | 0.690053 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,602 | products.py | wger-project_wger/wger/nutrition/management/products.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 enum
import json
import logging
import os
import tempfile
from collections import Counter
from gzip import GzipFile
from json import JSONDecodeError
from typing import Optional
# Django
from django.core.management.base import BaseCommand
# Third Party
import requests
from tqdm import tqdm
# wger
from wger.nutrition.dataclasses import IngredientData
from wger.nutrition.models import Ingredient
from wger.utils.requests import wger_headers
logger = logging.getLogger(__name__)
# Mode for this script. When using 'insert', the script will bulk-insert the new
# ingredients, which is very efficient. Importing the whole database will require
# barely a minute. When using 'update', existing ingredients will be updated, which
# requires two queries per product and is needed when there are already existing
# entries in the local ingredient table.
class Mode(enum.Enum):
INSERT = enum.auto()
UPDATE = enum.auto()
class ImportProductCommand(BaseCommand):
"""
Import an Open Food facts Dump
"""
mode = Mode.UPDATE
bulk_update_bucket: list[Ingredient] = []
bulk_size = 500
counter: Counter
help = "Don't run this command directly. Use either import-off-products or import-usda-products"
def __init__(self, stdout=None, stderr=None, no_color=False, force_color=False):
super().__init__(stdout, stderr, no_color, force_color)
self.counter = Counter()
def add_arguments(self, parser):
parser.add_argument(
'--set-mode',
action='store',
default='update',
dest='mode',
type=str,
help=(
'Script mode, "insert" or "update". Insert will insert the ingredients as new '
'entries in the database, while update will try to update them if they are '
'already present. Default: update'
),
)
parser.add_argument(
'--folder',
action='store',
default='',
dest='folder',
type=str,
help=(
'Controls whether to use a temporary folder created by python (the default) or '
'the path provided for storing the downloaded dataset. If there are already '
'downloaded or extracted files here, they will be used instead of fetching them '
'again.'
),
)
def handle(self, **options):
raise NotImplementedError('Do not run this command on its own!')
def process_ingredient(self, ingredient_data: IngredientData):
#
# Add entries as new products
if self.mode == Mode.INSERT:
self.bulk_update_bucket.append(Ingredient(**ingredient_data.dict()))
if len(self.bulk_update_bucket) > self.bulk_size:
try:
Ingredient.objects.bulk_create(self.bulk_update_bucket)
self.stdout.write('***** Bulk adding products *****')
except Exception as e:
self.stdout.write(
'--> Error while saving the product bucket. Saving individually'
)
self.stdout.write(e)
# Try saving the ingredients individually as most will be correct
for ingredient in self.bulk_update_bucket:
try:
ingredient.save()
# ¯\_(ツ)_/¯
except Exception as e:
self.stdout.write('--> Error while saving the product individually')
self.stdout.write(e)
self.counter['new'] += self.bulk_size
self.bulk_update_bucket = []
# Update existing entries
else:
try:
# Update an existing product (look-up key is the code) or create a new
# one. While this might not be the most efficient query (there will always
# be a SELECT first), it's ok because this script is run very rarely.
obj, created = Ingredient.objects.update_or_create(
remote_id=ingredient_data.remote_id,
defaults=ingredient_data.dict(),
)
if created:
self.counter['new'] += 1
# self.stdout.write('-> added to the database')
else:
self.counter['edited'] += 1
# self.stdout.write('-> updated')
except Exception as e:
self.stdout.write(f'--> Error while performing update_or_create: {e}')
self.stdout.write(repr(ingredient_data))
self.counter['error'] += 1
def get_download_folder(self, folder: str) -> tuple[str, Optional[tempfile.TemporaryDirectory]]:
if folder:
tmp_folder = None
download_folder = folder
# Check whether the folder exists
if not os.path.exists(download_folder):
self.stdout.write(self.style.ERROR(f'Folder {download_folder} does not exist!'))
raise Exception('Folder does not exist')
else:
tmp_folder = tempfile.TemporaryDirectory()
download_folder = tmp_folder.name
self.stdout.write(f'Using folder {download_folder} for storing downloaded files')
return download_folder, tmp_folder
def iterate_gz_file_contents(self, path: str, languages: list[str]):
with GzipFile(path, 'rb') as gzid:
for line in gzid:
try:
product = json.loads(line)
if not product.get('lang') in languages:
continue
yield product
except JSONDecodeError:
self.stdout.write(f' Error parsing and/or filtering json record, skipping')
continue
def download_file(self, url: str, destination: str) -> None:
if os.path.exists(destination):
self.stdout.write(f'File already downloaded at {destination}')
return
self.stdout.write(f'Downloading {url}... (this may take a while)')
response = requests.get(url, stream=True, headers=wger_headers())
total_size = int(response.headers.get('content-length', 0))
if response.status_code == 404:
raise Exception(f'Could not open {url}!')
with open(destination, 'wb') as fid:
with tqdm(total=total_size, unit='B', unit_scale=True, desc='Downloading') as pbar:
for chunk in response.iter_content(chunk_size=50 * 1024):
fid.write(chunk)
pbar.update(len(chunk))
| 7,465 | Python | .py | 163 | 34.644172 | 100 | 0.607266 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,603 | __init__.py | wger-project_wger/wger/nutrition/management/__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/>.
| 802 | Python | .py | 15 | 52.466667 | 79 | 0.766201 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,604 | dummy-generator-nutrition.py | wger-project_wger/wger/nutrition/management/commands/dummy-generator-nutrition.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
from random import (
choice,
randint,
)
from uuid import uuid4
# Django
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone
# wger
from wger.nutrition.models import (
Ingredient,
LogItem,
Meal,
MealItem,
NutritionPlan,
)
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Dummy generator for nutritional plans
"""
help = 'Dummy generator for nutritional plans'
def add_arguments(self, parser):
parser.add_argument(
'--plans',
action='store',
default=10,
dest='nr_plans',
type=int,
help='The number of nutritional plans to create per user (default: 10)',
)
parser.add_argument(
'--diary-entries',
action='store',
default=20,
dest='nr_diary_entries',
type=int,
help='The number of nutrition logs to create per day (default: 20)',
)
parser.add_argument(
'--diary-dates',
action='store',
default=30,
dest='nr_diary_dates',
type=int,
help='Number of dates in which to create logs (default: 30)',
)
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_plans']} dummy nutritional plan(s) per user")
users = (
[User.objects.get(pk=options['user_id'])] if options['user_id'] else User.objects.all()
)
ingredients = [i for i in Ingredient.objects.order_by('?').all()[:100]]
meals_per_plan = 4
for user in users:
diary_entries = []
self.stdout.write(f'- processing user {user.username}')
# Add plan
for _ in range(0, options['nr_plans']):
uid = str(uuid4()).split('-')
start_date = datetime.date.today() - datetime.timedelta(days=randint(0, 100))
plan = NutritionPlan(
description=f'Dummy nutritional plan - {uid[1]}',
creation_date=start_date,
user=user,
)
plan.save()
if int(options['verbosity']) >= 2:
self.stdout.write(f' created plan {plan.description}')
# Add meals
for i in range(0, meals_per_plan):
order = 1
meal = Meal(
plan=plan,
order=order,
name=f'Dummy meal {i}',
time=datetime.time(hour=randint(0, 23), minute=randint(0, 59)),
)
meal.save()
# Add meal items
for _ in range(0, randint(1, 5)):
meal_item = MealItem(
meal=meal,
ingredient=choice(ingredients),
weight_unit=None,
order=order,
amount=randint(10, 250),
)
meal_item.save()
order = order + 1
# Add diary entries
for _ in range(0, options['nr_diary_dates']):
date = timezone.now() - datetime.timedelta(
days=randint(0, 100),
hours=randint(0, 12),
minutes=randint(0, 59),
)
for _ in range(0, options['nr_diary_entries']):
log = LogItem(
plan=plan,
datetime=date,
ingredient=choice(ingredients),
weight_unit=None,
amount=randint(10, 300),
)
diary_entries.append(log)
if int(options['verbosity']) >= 2:
self.stdout.write(f" created {options['nr_diary_dates']} diary entries")
LogItem.objects.bulk_create(diary_entries)
| 5,131 | Python | .py | 133 | 25.526316 | 100 | 0.517775 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,605 | import-usda-products.py | wger-project_wger/wger/nutrition/management/commands/import-usda-products.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 json
import logging
import os
from json import JSONDecodeError
from zipfile import ZipFile
# wger
from wger.core.models import Language
from wger.nutrition.management.products import (
ImportProductCommand,
Mode,
)
from wger.nutrition.usda import extract_info_from_usda
from wger.utils.constants import ENGLISH_SHORT_NAME
logger = logging.getLogger(__name__)
class Command(ImportProductCommand):
"""
Import an USDA dataset
"""
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
'--dataset',
action='store',
default='FoodData_Central_branded_food_json_2024-04-18.zip',
dest='dataset',
type=str,
help='What dataset to download, this value will be appended to '
'"https://fdc.nal.usda.gov/fdc-datasets/". Consult '
'https://fdc.nal.usda.gov/download-datasets.html for current file names',
)
def handle(self, **options):
if options['mode'] == 'insert':
self.mode = Mode.INSERT
dataset_url = f'https://fdc.nal.usda.gov/fdc-datasets/{options["dataset"]}'
download_folder, tmp_folder = self.get_download_folder(options['folder'])
self.stdout.write('Importing entries from USDA')
self.stdout.write(f' - {self.mode}')
self.stdout.write(f' - dataset: {dataset_url}')
self.stdout.write(f' - download folder: {download_folder}')
self.stdout.write('')
english = Language.objects.get(short_name=ENGLISH_SHORT_NAME)
# Download the dataset
zip_file_path = os.path.join(download_folder, options['dataset'])
self.download_file(dataset_url, zip_file_path)
# Extract the first file from the ZIP archive
with ZipFile(zip_file_path, 'r') as zip_ref:
file_list = zip_ref.namelist()
if not file_list:
raise Exception('No files found in the ZIP archive')
first_file = file_list[0]
# If the file was already extracted to the download folder, skip
extracted_file_path = os.path.join(download_folder, first_file)
if os.path.exists(extracted_file_path):
self.stdout.write(f'File {first_file} already extracted, skipping...')
else:
self.stdout.write(f'Extracting {first_file}...')
extracted_file_path = zip_ref.extract(first_file, path=download_folder)
# Since the file is almost JSONL, just process each line individually
self.stdout.write('Start processing...')
with open(extracted_file_path, 'r') as extracted_file:
for line in extracted_file.readlines():
# Try to skip the first and last lines in the file
if 'FoundationFoods' in line or 'BrandedFoods' in line:
continue
if line.strip() == '}':
continue
try:
json_data = json.loads(line.strip().strip(','))
except JSONDecodeError as e:
self.stdout.write(f'--> Error while decoding JSON: {e}')
continue
try:
ingredient_data = extract_info_from_usda(json_data, english.pk)
except KeyError as e:
self.stdout.write(f'--> KeyError while extracting ingredient info: {e}')
self.counter['skipped'] += 1
except ValueError as e:
self.stdout.write(f'--> ValueError while extracting ingredient info: {e}')
self.counter['skipped'] += 1
else:
self.process_ingredient(ingredient_data)
if tmp_folder:
self.stdout.write(f'Removing temporary folder {download_folder}')
tmp_folder.cleanup()
self.stdout.write(self.style.SUCCESS('Finished!'))
self.stdout.write(self.style.SUCCESS(str(self.counter)))
| 4,692 | Python | .py | 100 | 37.02 | 94 | 0.63151 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,606 | download-ingredient-images.py | wger-project_wger/wger/nutrition/management/commands/download-ingredient-images.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
from django.core.exceptions import (
ImproperlyConfigured,
ValidationError,
)
from django.core.management.base import (
BaseCommand,
CommandError,
)
from django.core.validators import URLValidator
# wger
from wger.nutrition.sync import download_ingredient_images
class Command(BaseCommand):
"""
Download ingredient images from a wger instance and updates the local database
Both the ingredients and the images are identified by their UUID, which can't
be modified via the GUI.
"""
help = (
'Download ingredient images from wger.de and update the local database\n'
'\n'
'ATTENTION: The script will download the images from the server and add them\n'
' to your local ingredients. The ingredients are identified by\n'
' their UUID field, if you manually edited or changed it\n'
' the script will not be able to match them.'
)
def add_arguments(self, parser):
parser.add_argument(
'--remote-url',
action='store',
dest='remote_url',
default=settings.WGER_SETTINGS['WGER_INSTANCE'],
help=f'Remote URL to fetch the ingredients from (default: WGER_SETTINGS'
f'["WGER_INSTANCE"] - {settings.WGER_SETTINGS["WGER_INSTANCE"]})',
)
def handle(self, **options):
if not settings.MEDIA_ROOT:
raise ImproperlyConfigured('Please set MEDIA_ROOT in your settings file')
remote_url = options['remote_url']
try:
val = URLValidator()
val(remote_url)
except ValidationError:
raise CommandError('Please enter a valid URL')
download_ingredient_images(self.stdout.write, remote_url, self.style.SUCCESS)
| 2,473 | Python | .py | 59 | 36.067797 | 87 | 0.697587 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,607 | __init__.py | wger-project_wger/wger/nutrition/management/commands/__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/>.
| 802 | Python | .py | 15 | 52.466667 | 79 | 0.766201 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,608 | import-off-products.py | wger-project_wger/wger/nutrition/management/commands/import-off-products.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
import os
# Third Party
import requests
from pymongo import MongoClient
# wger
from wger.core.models import Language
from wger.nutrition.management.products import (
ImportProductCommand,
Mode,
)
from wger.nutrition.off import extract_info_from_off
logger = logging.getLogger(__name__)
class Command(ImportProductCommand):
"""
Import an Open Food facts Dump
"""
help = 'Import an Open Food Facts dump. Please consult extras/docker/open-food-facts'
deltas_base_url = 'https://static.openfoodfacts.org/data/delta/'
full_off_dump_url = 'https://static.openfoodfacts.org/data/openfoodfacts-products.jsonl.gz'
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
'--jsonl',
action='store_true',
default=False,
dest='use_jsonl',
help=(
'Use the JSONL dump of the Open Food Facts database.'
'(this option does not require mongo)'
),
)
parser.add_argument(
'--delta-updates',
action='store_true',
default=False,
dest='delta_updates',
help='Downloads and imports the most recent delta file',
)
def import_mongo(self, languages: dict[str:int]):
client = MongoClient('mongodb://off:off-wger@127.0.0.1', port=27017)
db = client.admin
for product in db.products.find({'lang': {'$in': list(languages.keys())}}):
try:
ingredient_data = extract_info_from_off(product, languages[product['lang']])
except (KeyError, ValueError) as e:
# self.stdout.write(f'--> KeyError while extracting info from OFF: {e}')
self.counter['skipped'] += 1
else:
self.process_ingredient(ingredient_data)
def import_daily_delta(self, languages: dict[str:int], destination: str):
download_folder, tmp_folder = self.get_download_folder(destination)
# Fetch the index page with requests and read the result
index_url = self.deltas_base_url + 'index.txt'
req = requests.get(index_url)
index_content = req.text
newest_entry = index_content.split('\n')[0]
file_path = os.path.join(download_folder, newest_entry)
# Fetch the newest entry and extract the contents
delta_url = self.deltas_base_url + newest_entry
self.download_file(delta_url, file_path)
self.stdout.write('Start processing...')
for entry in self.iterate_gz_file_contents(file_path, list(languages.keys())):
try:
ingredient_data = extract_info_from_off(entry, languages[entry['lang']])
except (KeyError, ValueError) as e:
self.stdout.write(
f'--> {ingredient_data.remote_id=} Error while extracting info from OFF: {e}'
)
self.counter['skipped'] += 1
else:
self.process_ingredient(ingredient_data)
if tmp_folder:
self.stdout.write(f'Removing temporary folder {download_folder}')
tmp_folder.cleanup()
def import_full_dump(self, languages: dict[str:int], destination: str):
download_folder, tmp_folder = self.get_download_folder(destination)
file_path = os.path.join(download_folder, os.path.basename(self.full_off_dump_url))
self.download_file(self.full_off_dump_url, file_path)
self.stdout.write('Start processing...')
for entry in self.iterate_gz_file_contents(file_path, list(languages.keys())):
try:
ingredient_data = extract_info_from_off(entry, languages[entry['lang']])
except (KeyError, ValueError) as e:
self.stdout.write(f'--> Error while extracting info from OFF: {e}')
self.counter['skipped'] += 1
else:
self.process_ingredient(ingredient_data)
if tmp_folder:
self.stdout.write(f'Removing temporary folder {download_folder}')
tmp_folder.cleanup()
def handle(self, **options):
try:
# Third Party
from pymongo import MongoClient
except ImportError:
self.stdout.write('Please install pymongo, `pip install pymongo`')
return
if options['mode'] == 'insert':
self.mode = Mode.INSERT
self.stdout.write('Importing entries from Open Food Facts')
self.stdout.write(f' - {self.mode}')
if options['delta_updates']:
self.stdout.write(f' - importing only delta updates')
elif options['use_jsonl']:
self.stdout.write(f' - importing the full dump')
else:
self.stdout.write(f' - importing from mongo')
self.stdout.write('')
languages = {lang.short_name: lang.pk for lang in Language.objects.all()}
if options['delta_updates']:
self.import_daily_delta(languages, options['folder'])
elif options['use_jsonl']:
self.import_full_dump(languages, options['folder'])
else:
self.import_mongo(languages)
self.stdout.write(self.style.SUCCESS('Finished!'))
self.stdout.write(self.style.SUCCESS(str(self.counter)))
| 6,013 | Python | .py | 132 | 36.25 | 97 | 0.635913 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,609 | sync-ingredients.py | wger-project_wger/wger/nutrition/management/commands/sync-ingredients.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
from django.core.exceptions import ValidationError
from django.core.management.base import (
BaseCommand,
CommandError,
)
from django.core.validators import URLValidator
# wger
from wger.nutrition.sync import sync_ingredients
class Command(BaseCommand):
"""
Synchronizes ingredient data from a wger instance to the local database
"""
remote_url = settings.WGER_SETTINGS['WGER_INSTANCE']
help = """Synchronizes ingredient data from a wger instance to the local database"""
def add_arguments(self, parser):
parser.add_argument(
'--remote-url',
action='store',
dest='remote_url',
default=settings.WGER_SETTINGS['WGER_INSTANCE'],
help=f'Remote URL to fetch the ingredients from (default: WGER_SETTINGS'
f'["WGER_INSTANCE"] - {settings.WGER_SETTINGS["WGER_INSTANCE"]})',
)
def handle(self, **options):
remote_url = options['remote_url']
try:
val = URLValidator()
val(remote_url)
self.remote_url = remote_url
except ValidationError:
raise CommandError('Please enter a valid URL')
sync_ingredients(self.stdout.write, self.remote_url, self.style.SUCCESS)
| 1,942 | Python | .py | 47 | 35.765957 | 88 | 0.711936 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,610 | urls.py | wger-project_wger/wger/software/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
# Django
from django.urls import path
from django.views.generic import (
RedirectView,
TemplateView,
)
# wger
from wger import get_version
from wger.software import views
urlpatterns = [
path(
'terms-of-service',
TemplateView.as_view(template_name='tos.html'),
name='tos',
),
path(
'features',
views.features,
name='features',
),
path(
'code',
RedirectView.as_view(permanent=True, url='https://github.com/wger-project/wger'),
name='code',
),
path(
'about-us',
TemplateView.as_view(
template_name='about_us.html', extra_context={'version': get_version()}
),
name='about-us',
),
path(
'api',
TemplateView.as_view(template_name='api.html'),
name='api',
),
]
| 1,511 | Python | .py | 52 | 24.346154 | 89 | 0.671252 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,611 | __init__.py | wger-project_wger/wger/software/__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,612 | views.py | wger-project_wger/wger/software/views.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.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.shortcuts import render
# Third Party
import requests
# wger
from wger.core.forms import (
RegistrationForm,
RegistrationFormNoCaptcha,
)
from wger.exercises.models import ExerciseBase
from wger.nutrition.models import Ingredient
logger = logging.getLogger(__name__)
CACHE_KEY = 'landing-page-context'
def features(request):
"""
Render the landing page
"""
context = cache.get(CACHE_KEY)
if not context:
result_github_api = requests.get('https://api.github.com/repos/wger-project/wger').json()
context = {
'nr_users': User.objects.count(),
'nr_exercises': ExerciseBase.objects.count(),
'nr_ingredients': Ingredient.objects.count(),
'nr_stars': result_github_api.get('stargazers_count', '2000'),
}
cache.set(CACHE_KEY, context, 60 * 60 * 24 * 7) # one week
FormClass = (
RegistrationForm if settings.WGER_SETTINGS['USE_RECAPTCHA'] else RegistrationFormNoCaptcha
)
form = FormClass()
form.fields['username'].widget.attrs.pop('autofocus', None)
context['form'] = form
context['allow_registration'] = settings.WGER_SETTINGS['ALLOW_REGISTRATION']
context['allow_guest_users'] = settings.WGER_SETTINGS['ALLOW_GUEST_USERS']
return render(request, 'features.html', context)
| 2,135 | Python | .py | 54 | 35.555556 | 98 | 0.734526 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,613 | signals.py | wger-project_wger/wger/gym/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_delete,
post_save,
)
from django.dispatch import receiver
# wger
from wger.gym.models import (
Gym,
GymConfig,
UserDocument,
)
@receiver(post_save, sender=Gym)
def gym_config(sender, instance, created, **kwargs):
"""
Creates a configuration entry for newly added gyms
"""
if not created or kwargs['raw']:
return
config = GymConfig()
config.gym = instance
config.save()
@receiver(post_delete, sender=UserDocument)
def delete_user_document_on_delete(sender, instance, **kwargs):
"""
Deletes the document from the disk as well
"""
instance.document.delete(save=False)
| 1,362 | Python | .py | 42 | 29.5 | 78 | 0.742944 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,614 | urls.py | wger-project_wger/wger/gym/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
# Django
from django.conf.urls import include
from django.urls import path
# wger
from wger.gym.views import (
admin_config,
admin_notes,
config,
contract,
contract_option,
contract_type,
document,
export,
gym,
user_config,
)
# 'sub patterns' for gyms
patterns_gym = [
path(
'list',
gym.GymListView.as_view(),
name='list',
),
path(
'new-user-data/view',
gym.gym_new_user_info,
name='new-user-data',
),
path(
'new-user-data/export',
gym.gym_new_user_info_export,
name='new-user-data-export',
),
path(
'<int:pk>/members',
gym.GymUserListView.as_view(),
name='user-list',
),
path(
'<int:gym_pk>/add-member',
gym.GymAddUserView.as_view(),
name='add-user',
),
path(
'add',
gym.GymAddView.as_view(),
name='add',
),
path(
'<int:pk>/edit',
gym.GymUpdateView.as_view(),
name='edit',
),
path(
'<int:pk>/delete',
gym.GymDeleteView.as_view(),
name='delete',
),
path(
'user/<int:user_pk>/permission-edit',
gym.gym_permissions_user_edit,
name='edit-user-permission',
),
path(
'user/<int:user_pk>/reset-user-password',
gym.reset_user_password,
name='reset-user-password',
),
]
# 'sub patterns' for gym config
patterns_gymconfig = [
path(
'<int:pk>/edit',
config.GymConfigUpdateView.as_view(),
name='edit',
),
]
# 'sub patterns' for gym admin config
patterns_adminconfig = [
path(
'<int:pk>/edit',
admin_config.ConfigUpdateView.as_view(),
name='edit',
),
]
# 'sub patterns' for gym user config
patterns_userconfig = [
path(
'<int:pk>/edit',
user_config.ConfigUpdateView.as_view(),
name='edit',
),
]
# 'sub patterns' for admin notes
patterns_admin_notes = [
path(
'list/user/<int:user_pk>',
admin_notes.ListView.as_view(),
name='list',
),
path(
'add/user/<int:user_pk>',
admin_notes.AddView.as_view(),
name='add',
),
path(
'<int:pk>/edit',
admin_notes.UpdateView.as_view(),
name='edit',
),
path(
'<int:pk>/delete',
admin_notes.DeleteView.as_view(),
name='delete',
),
]
# 'sub patterns' for user documents
patterns_documents = [
path(
'list/user/<int:user_pk>',
document.ListView.as_view(),
name='list',
),
path(
'add/user/<int:user_pk>',
document.AddView.as_view(),
name='add',
),
path(
'<int:pk>/edit',
document.UpdateView.as_view(),
name='edit',
),
path(
'<int:pk>/delete',
document.DeleteView.as_view(),
name='delete',
),
]
# sub patterns for contracts
patterns_contracts = [
path(
'add/<int:user_pk>',
contract.AddView.as_view(),
name='add',
),
path(
'view/<int:pk>',
contract.DetailView.as_view(),
name='view',
),
path(
'edit/<int:pk>',
contract.UpdateView.as_view(),
name='edit',
),
path(
'list/<int:user_pk>',
contract.ListView.as_view(),
name='list',
),
]
# sub patterns for contract types
patterns_contract_types = [
path(
'add/<int:gym_pk>',
contract_type.AddView.as_view(),
name='add',
),
path(
'edit/<int:pk>',
contract_type.UpdateView.as_view(),
name='edit',
),
path(
'delete/<int:pk>',
contract_type.DeleteView.as_view(),
name='delete',
),
path(
'list/<int:gym_pk>',
contract_type.ListView.as_view(),
name='list',
),
]
# sub patterns for contract options
patterns_contract_options = [
path(
'add/<int:gym_pk>',
contract_option.AddView.as_view(),
name='add',
),
path(
'edit/<int:pk>',
contract_option.UpdateView.as_view(),
name='edit',
),
path(
'delete/<int:pk>',
contract_option.DeleteView.as_view(),
name='delete',
),
path(
'list/<int:gym_pk>',
contract_option.ListView.as_view(),
name='list',
),
]
# sub patterns for exports
patterns_export = [
path(
'users/<int:gym_pk>)',
export.users,
name='users',
),
]
#
# All patterns for this app
#
urlpatterns = [
path('', include((patterns_gym, 'gym'), namespace='gym')),
path('config/', include((patterns_gymconfig, 'config'), namespace='config')),
path(
'admin-config/', include((patterns_adminconfig, 'admin_config'), namespace='admin_config')
),
path('user-config/', include((patterns_userconfig, 'user_config'), namespace='user_config')),
path('notes/', include((patterns_admin_notes, 'admin_note'), namespace='admin_note')),
path('document/', include((patterns_documents, 'document'), namespace='document')),
path('contract/', include((patterns_contracts, 'contract'), namespace='contract')),
path(
'contract-type/',
include((patterns_contract_types, 'contract_type'), namespace='contract_type'),
),
path(
'contract-option/',
include((patterns_contract_options, 'contract-option'), namespace='contract-option'),
),
path('export/', include((patterns_export, 'export'), namespace='export')),
]
| 6,237 | Python | .py | 253 | 18.770751 | 98 | 0.58251 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,615 | apps.py | wger-project_wger/wger/gym/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 GymConfig(AppConfig):
name = 'wger.gym'
verbose_name = 'Gym'
def ready(self):
import wger.gym.signals
| 839 | Python | .py | 21 | 37.761905 | 78 | 0.765068 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,616 | __init__.py | wger-project_wger/wger/gym/__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.gym.apps.GymConfig'
| 848 | Python | .py | 19 | 43.421053 | 78 | 0.775758 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,617 | helpers.py | wger-project_wger/wger/gym/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
def get_user_last_activity(user):
"""
Find out when the user was last active. "Active" means in this context logging
a weight, or saving a workout session.
:param user: user object
:return: a date or None if nothing was found
"""
# wger
from wger.manager.models import (
WorkoutLog,
WorkoutSession,
)
last_activity = None
# Check workout logs
last_log = WorkoutLog.objects.filter(user=user).order_by('date').last()
if last_log:
last_activity = last_log.date
# Check workout sessions
last_session = WorkoutSession.objects.filter(user=user).order_by('date').last()
if last_session:
last_session = last_session.date
# Return the last one
if last_session:
if not last_activity:
last_activity = last_session
if last_activity < last_session:
last_activity = last_session
return last_activity
def is_any_gym_admin(user):
"""
Small utility that checks that the user object has any administrator
permissions
"""
return (
user.has_perm('gym.manage_gym')
or user.has_perm('gym.manage_gyms')
or user.has_perm('gym.gym_trainer')
)
def get_permission_list(user):
"""
Calculate available user permissions
This is needed because a user shouldn't be able to create or give another
account with more permissions than himself.
:param user: the user creating the account
:return: a list of permissions
"""
form_group_permission = ['user', 'trainer']
if user.has_perm('gym.manage_gym'):
form_group_permission.append('admin')
if user.has_perm('gym.manage_gyms'):
form_group_permission.append('admin')
form_group_permission.append('manager')
return form_group_permission
| 2,495 | Python | .py | 67 | 32 | 83 | 0.699336 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,618 | forms.py | wger-project_wger/wger/gym/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.contrib.auth.models import User
from django.utils.translation import gettext as _
# Third Party
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
# wger
from wger.core.forms import UserPersonalInformationForm
from wger.utils.widgets import BootstrapSelectMultiple
class GymUserPermissionForm(forms.ModelForm):
"""
Form used to set the permission group of a gym member
"""
USER = 'user'
GYM_ADMIN = 'admin'
TRAINER = 'trainer'
MANAGER = 'manager'
# Empty default roles, they are always set at run time
ROLES = ()
class Meta:
model = User
fields = ('role',)
role = forms.MultipleChoiceField(choices=ROLES, initial=USER)
def __init__(self, available_roles=None, *args, **kwargs):
"""
Custom logic to reduce the available permissions
"""
super(GymUserPermissionForm, self).__init__(*args, **kwargs)
if available_roles is None:
available_roles = []
field_choices = [(self.USER, _('User'))]
if 'trainer' in available_roles:
field_choices.append((self.TRAINER, _('Trainer')))
if 'admin' in available_roles:
field_choices.append((self.GYM_ADMIN, _('Gym administrator')))
if 'manager' in available_roles:
field_choices.append((self.MANAGER, _('General manager')))
self.fields['role'] = forms.MultipleChoiceField(
choices=field_choices,
initial=User,
widget=BootstrapSelectMultiple(),
)
self.helper = FormHelper()
self.helper.form_class = 'wger-form'
self.helper.add_input(Submit('submit', _('Save'), css_class='btn-success btn-block'))
class GymUserAddForm(GymUserPermissionForm, UserPersonalInformationForm):
"""
Form used when adding a user to a gym
"""
birthdate = forms.DateField(required=False)
class Meta:
model = User
widgets = {'role': BootstrapSelectMultiple()}
fields = (
'first_name',
'last_name',
'username',
'email',
'role',
)
username = forms.RegexField(
label=_('Username'),
max_length=30,
regex=r'^[\w.@+-]+$',
help_text=_('Required. 30 characters or fewer. Letters, digits and ' '@/./+/-/_ only.'),
error_messages={
'invalid': _('This value may contain only letters, numbers and ' '@/.//-/_ characters.')
},
)
def clean_username(self):
"""
Since User.username is unique, this check is redundant,
but it sets a nicer error message than the ORM. See #13147.
"""
username = self.cleaned_data['username']
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_('A user with that username already exists.'))
| 3,669 | Python | .py | 95 | 31.821053 | 100 | 0.652321 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,619 | managers.py | wger-project_wger/wger/gym/managers.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.contrib.auth.models import (
Permission,
User,
)
from django.db import models
from django.db.models import Q
class GymManager(models.Manager):
"""
Custom query manager for Gyms
"""
def get_members(self, gym_pk):
"""
Returns all members for this gym (i.e non-admin ones)
"""
perm_gym = Permission.objects.get(codename='manage_gym')
perm_gyms = Permission.objects.get(codename='manage_gyms')
perm_trainer = Permission.objects.get(codename='gym_trainer')
users = User.objects.filter(userprofile__gym_id=gym_pk)
return users.exclude(
Q(groups__permissions=perm_gym)
| Q(groups__permissions=perm_gyms)
| Q(groups__permissions=perm_trainer)
).distinct()
def get_admins(self, gym_pk):
"""
Returns all admins for this gym (i.e trainers, managers, etc.)
"""
perm_gym = Permission.objects.get(codename='manage_gym')
perm_gyms = Permission.objects.get(codename='manage_gyms')
perm_trainer = Permission.objects.get(codename='gym_trainer')
users = User.objects.filter(userprofile__gym_id=gym_pk)
return users.filter(
Q(groups__permissions=perm_gym)
| Q(groups__permissions=perm_gyms)
| Q(groups__permissions=perm_trainer)
).distinct()
| 2,058 | Python | .py | 51 | 34.411765 | 78 | 0.684342 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,620 | user_config.py | wger-project_wger/wger/gym/models/user_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/>.
# Django
from django.contrib.auth.models import User
from django.db import models as m
from django.utils.translation import gettext_lazy as _
# wger
from wger.gym.models import Gym
class AbstractGymUserConfigModel(m.Model):
"""
Abstract class for member and admin gym configuration models
"""
class Meta:
abstract = True
gym = m.ForeignKey(
Gym,
editable=False,
on_delete=m.CASCADE,
)
"""
Gym this configuration belongs to
"""
user = m.OneToOneField(
User,
editable=False,
on_delete=m.CASCADE,
)
"""
User this configuration belongs to
"""
class GymAdminConfig(AbstractGymUserConfigModel, m.Model):
"""
Administrator/trainer configuration options for a specific gym
"""
class Meta:
unique_together = ('gym', 'user')
"""
Only one entry per user and gym
"""
overview_inactive = m.BooleanField(
verbose_name=_('Overview of inactive members'),
help_text=_('Receive email overviews of inactive members'),
default=True,
)
"""
Reminder of inactive members
"""
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
class GymUserConfig(AbstractGymUserConfigModel, m.Model):
"""
Gym member configuration options for a specific gym
"""
class Meta:
unique_together = ('gym', 'user')
"""
Only one entry per user and gym
"""
include_inactive = m.BooleanField(
verbose_name=_('Include in inactive overview'),
help_text=_('Include this user in the email list with ' 'inactive members'),
default=True,
)
"""
Include user in inactive overview
"""
def get_owner_object(self):
"""
While the model has a user foreign key, this is editable by all
trainers in the gym.
"""
return None
| 2,796 | Python | .py | 88 | 26.306818 | 84 | 0.668153 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,621 | user_document.py | wger-project_wger/wger/gym/models/user_document.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 uuid
# Django
from django.contrib.auth.models import User
from django.db import models as m
from django.utils.translation import gettext_lazy as _
def gym_document_upload_dir(instance, filename):
"""
Returns the upload target for documents
"""
return f'gym/documents/{instance.member.userprofile.gym.id}/{instance.member.id}/{uuid.uuid4()}'
class UserDocument(m.Model):
"""
Model for a document
"""
class Meta:
"""
Order by time
"""
ordering = [
'-timestamp_created',
]
user = m.ForeignKey(User, editable=False, related_name='userdocument_user', on_delete=m.CASCADE)
"""
User this note belongs to
"""
member = m.ForeignKey(
User,
editable=False,
related_name='userdocument_member',
on_delete=m.CASCADE,
)
"""
Gym member this note refers to
"""
timestamp_created = m.DateTimeField(auto_now_add=True)
"""
Time when this document was created
"""
timestamp_edited = m.DateTimeField(auto_now=True)
"""
Last time when this document was edited
"""
document = m.FileField(verbose_name=_('Document'), upload_to=gym_document_upload_dir)
"""
Uploaded document
"""
original_name = m.CharField(max_length=128, editable=False)
"""
Original document name when uploaded
"""
name = m.CharField(
max_length=60,
verbose_name=_('Name'),
help_text=_('Will use file name if nothing provided'),
blank=True,
)
"""
Name or description
"""
note = m.TextField(
verbose_name=_('Note'),
blank=True,
null=True,
)
"""
Note with additional information
"""
def __str__(self):
"""
Return a more human-readable representation
"""
if self.name != self.original_name:
return f'{self.name} ({self.original_name})'
else:
return self.name
def get_owner_object(self):
"""
While the model has a user foreign key, this is editable by all
trainers in the gym.
"""
return None
| 3,002 | Python | .py | 97 | 25.391753 | 100 | 0.651888 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,622 | gym_config.py | wger-project_wger/wger/gym/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/>.
# Django
from django.db import models as m
from django.utils.translation import (
gettext,
gettext_lazy as _,
)
# wger
from wger.gym.models import Gym
class GymConfig(m.Model):
"""
Configuration options for a gym
"""
gym = m.OneToOneField(
Gym,
related_name='config',
editable=False,
on_delete=m.CASCADE,
)
"""
Gym this configuration belongs to
"""
weeks_inactive = m.PositiveIntegerField(
verbose_name=_('Reminder of inactive members'),
help_text=_(
'Number of weeks since the last time a '
'user logged his presence to be considered inactive'
),
default=4,
)
"""
Reminder of inactive members
"""
show_name = m.BooleanField(
verbose_name=_('Show name in header'),
help_text=_('Show the name of the gym in the site header'),
default=False,
)
"""
Show name of the current user's gym in the header, instead of 'wger'
"""
def __str__(self):
"""
Return a more human-readable representation
"""
return gettext(f'Configuration for {self.gym.name}')
def get_owner_object(self):
"""
Config has no user owner
"""
return None
| 2,091 | Python | .py | 65 | 26.969231 | 79 | 0.663361 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,623 | gym.py | wger-project_wger/wger/gym/models/gym.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 as m
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
# wger
from wger.gym.managers import GymManager
class Gym(m.Model):
"""
Model for a gym
"""
class Meta:
permissions = (
('gym_trainer', _('Trainer: can see the users for a gym')),
('manage_gym', _('Admin: can manage users for a gym')),
('manage_gyms', _('Admin: can administrate the different gyms')),
)
ordering = [
'name',
]
objects = GymManager()
"""
Custom Gym Query Manager
"""
name = m.CharField(max_length=60, verbose_name=_('Name'))
"""Gym name"""
phone = m.CharField(
verbose_name=_('Phone'),
max_length=20,
blank=True,
null=True,
)
"""Phone number"""
email = m.EmailField(
verbose_name=_('Email'),
blank=True,
null=True,
)
"""Email"""
owner = m.CharField(
verbose_name=_('Owner'),
max_length=100,
blank=True,
null=True,
)
"""Gym owner"""
zip_code = m.CharField(
_('ZIP code'),
max_length=10,
blank=True,
null=True,
)
"""ZIP code"""
city = m.CharField(
_('City'),
max_length=30,
blank=True,
null=True,
)
"""City"""
street = m.CharField(
_('Street'),
max_length=30,
blank=True,
null=True,
)
"""Street"""
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def get_absolute_url(self):
"""
Return the URL for this object
"""
return reverse('gym:gym:user-list', kwargs={'pk': self.pk})
def get_owner_object(self):
"""
Gym has no owner information
"""
return None
| 2,736 | Python | .py | 96 | 22.291667 | 79 | 0.598323 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,624 | __init__.py | wger-project_wger/wger/gym/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 .admin_user_note import AdminUserNote
from .contract import (
Contract,
ContractOption,
ContractType,
)
from .gym import Gym
from .gym_config import GymConfig
from .user_config import (
GymAdminConfig,
GymUserConfig,
)
from .user_document import UserDocument
| 1,095 | Python | .py | 29 | 36.034483 | 79 | 0.770892 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,625 | admin_user_note.py | wger-project_wger/wger/gym/models/admin_user_note.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.db import models as m
from django.utils.translation import gettext_lazy as _
class AdminUserNote(m.Model):
"""
Administrator notes about a member
"""
class Meta:
"""
Order by time
"""
ordering = [
'-timestamp_created',
]
user = m.ForeignKey(
User,
editable=False,
related_name='adminusernote_user',
on_delete=m.CASCADE,
)
"""
User this note belongs to
"""
member = m.ForeignKey(
User,
editable=False,
related_name='adminusernote_member',
on_delete=m.CASCADE,
)
"""
Gym member this note refers to
"""
timestamp_created = m.DateTimeField(auto_now_add=True)
"""
Time when this note was created
"""
timestamp_edited = m.DateTimeField(auto_now=True)
"""
Last time when this note was edited
"""
note = m.TextField(verbose_name=_('Note'))
"""
Actual note
"""
def get_owner_object(self):
"""
While the model has a user foreign key, this is editable by all
trainers in the gym.
"""
return None
| 2,027 | Python | .py | 66 | 25.545455 | 79 | 0.663077 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,626 | contract.py | wger-project_wger/wger/gym/models/contract.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 as m
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
# Local
from .gym import Gym
class ContractType(m.Model):
"""
Model for a contract's type
A contract type is a user-editable way of enhancing the contract to
specify types, such as e.g. 'with personal trainer', 'regular', etc.
"""
class Meta:
"""
Order by name
"""
ordering = [
'name',
]
gym = m.ForeignKey(Gym, editable=False, on_delete=m.CASCADE)
"""
The gym this contract type belongs to
"""
name = m.CharField(verbose_name=_('Name'), max_length=25)
"""
The contract type's short name
"""
description = m.TextField(
verbose_name=_('Description'),
blank=True,
null=True,
)
"""
Free text field for additional information
"""
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def get_owner_object(self):
"""
Contract type has no owner information
"""
return None
class ContractOption(m.Model):
"""
Model for a contract Option
A contract option is a user-editable way of enhancing the contract to
specify options, such as e.g. 'cash', 'bank withdrawal', etc. The
difference with a contract type is that a contract can only be of one
type but can have different options.
"""
class Meta:
"""
Order by name
"""
ordering = [
'name',
]
gym = m.ForeignKey(Gym, editable=False, on_delete=m.CASCADE)
"""
The gym this contract option belongs to
"""
name = m.CharField(verbose_name=_('Name'), max_length=25)
"""
The contract options short name
"""
description = m.TextField(
verbose_name=_('Description'),
blank=True,
null=True,
)
"""
Free text field for additional information
"""
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def get_owner_object(self):
"""
Contract type has no owner information
"""
return None
class Contract(m.Model):
"""
Model for a member's contract in a gym
"""
AMOUNT_TYPE_YEARLY = '1'
AMOUNT_TYPE_HALFYEARLY = '2'
AMOUNT_TYPE_MONTHLY = '3'
AMOUNT_TYPE_BIWEEKLY = '4'
AMOUNT_TYPE_WEEKLY = '5'
AMOUNT_TYPE_DAILY = '6'
AMOUNT_TYPE = (
(AMOUNT_TYPE_YEARLY, _('Yearly')),
(AMOUNT_TYPE_HALFYEARLY, _('Half yearly')),
(AMOUNT_TYPE_MONTHLY, _('Monthly')),
(AMOUNT_TYPE_BIWEEKLY, _('Biweekly')),
(AMOUNT_TYPE_WEEKLY, _('Weekly')),
(AMOUNT_TYPE_DAILY, _('Daily')),
)
class Meta:
"""
Order by time
"""
ordering = [
'-date_start',
]
user = m.ForeignKey(
User,
editable=False,
related_name='contract_user',
on_delete=m.CASCADE,
)
"""
User that originally created the contract
"""
member = m.ForeignKey(
User,
editable=False,
related_name='contract_member',
on_delete=m.CASCADE,
)
"""
Gym member this contract refers to
"""
timestamp_created = m.DateTimeField(auto_now_add=True)
"""
Time when the contract was created
"""
timestamp_edited = m.DateTimeField(auto_now=True)
"""
Last time when the contract was edited
"""
contract_type = m.ForeignKey(
ContractType,
blank=True,
null=True,
verbose_name=_('Contract type'),
on_delete=m.CASCADE,
)
"""
Optional type of contract
"""
options = m.ManyToManyField(
ContractOption,
verbose_name=_('Options'),
blank=True,
)
"""
Options for the contract
"""
amount = m.DecimalField(
verbose_name=_('Amount'),
decimal_places=2,
max_digits=12,
default=0,
)
"""
The amount to pay
"""
payment = m.CharField(
verbose_name=_('Payment type'),
max_length=2,
choices=AMOUNT_TYPE,
default=AMOUNT_TYPE_MONTHLY,
help_text=_('How often the amount will be charged to the member'),
)
"""
How often the amount will be charged to the member
"""
is_active = m.BooleanField(verbose_name=_('Contract is active'), default=True)
"""
Flag showing whether the contract is currently active
"""
date_start = m.DateField(
verbose_name=_('Start date'),
default=datetime.date.today,
blank=True,
null=True,
)
"""
The date when the contract starts
"""
date_end = m.DateField(
verbose_name=_('End date'),
blank=True,
null=True,
)
"""
The date when the contract ends
"""
email = m.EmailField(
verbose_name=_('Email'),
blank=True,
null=True,
)
"""The member's email"""
zip_code = m.CharField(
_('ZIP code'),
max_length=10,
blank=True,
null=True,
)
"""ZIP code"""
city = m.CharField(
_('City'),
max_length=30,
blank=True,
null=True,
)
"""City"""
street = m.CharField(
_('Street'),
max_length=30,
blank=True,
null=True,
)
"""Street"""
phone = m.CharField(
verbose_name=_('Phone'),
max_length=20,
blank=True,
null=True,
)
"""Phone number"""
profession = m.CharField(
verbose_name=_('Profession'),
max_length=50,
blank=True,
null=True,
)
"""
The member's profession
"""
note = m.TextField(
verbose_name=_('Note'),
blank=True,
null=True,
)
"""
Free text note with additional information
"""
def __str__(self):
"""
Return a more human-readable representation
"""
return f'#{self.id}'
def get_absolute_url(self):
"""
Return the URL for this object
"""
return reverse('gym:contract:view', kwargs={'pk': self.pk})
def get_owner_object(self):
"""
While the model has a user foreign key, this is editable by all
managers in the gym.
"""
return None
| 7,376 | Python | .py | 280 | 19.835714 | 82 | 0.589271 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,627 | 0008_auto_20190618_1617.py | wger-project_wger/wger/gym/migrations/0008_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 = [
('gym', '0007_auto_20170123_0920'),
]
operations = [
migrations.AlterField(
model_name='gymconfig',
name='show_name',
field=models.BooleanField(
default=False,
help_text='Show the name of the gym in the site header',
verbose_name='Show name in header',
),
),
]
| 572 | Python | .py | 18 | 23 | 72 | 0.567273 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,628 | 0002_auto_20151003_1944.py | wger-project_wger/wger/gym/migrations/0002_auto_20151003_1944.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.conf import settings
import datetime
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('gym', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='gym',
name='email',
field=models.EmailField(max_length=254, verbose_name='Email', blank=True, null=True),
),
migrations.AlterField(
model_name='gym',
name='zip_code',
field=models.CharField(max_length=10, verbose_name='ZIP code', blank=True, null=True),
),
migrations.AlterField(
model_name='gymconfig',
name='weeks_inactive',
field=models.PositiveIntegerField(
help_text='Number of weeks since the last time a user logged his presence to be considered inactive',
default=4,
verbose_name='Reminder inactive members',
),
),
]
| 1,083 | Python | .py | 30 | 26.7 | 117 | 0.600572 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,629 | 0004_auto_20151003_2357.py | wger-project_wger/wger/gym/migrations/0004_auto_20151003_2357.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('gym', '0003_auto_20151003_2008'),
]
operations = [
migrations.AlterField(
model_name='contract',
name='amount',
field=models.DecimalField(
default=0, verbose_name='Amount', max_digits=12, decimal_places=2
),
),
]
| 444 | Python | .py | 15 | 21.4 | 81 | 0.569412 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,630 | 0006_auto_20160214_1013.py | wger-project_wger/wger/gym/migrations/0006_auto_20160214_1013.py | # -*- coding: utf-8 -*-
from django.db import migrations, models
def update_permission_names(apps, schema_editor):
"""
Updates the wording of our three custom gym permissions
"""
Permission = apps.get_model('auth', 'Permission')
for name in [
'Trainer, can see the users for a gym',
'Admin, can manage users for a gym',
'Admin, can administrate the different gyms',
]:
permissions = Permission.objects.filter(name=name)
if permissions.exists():
permissions[0].name = name.replace(',', ':')
permissions[0].save()
class Migration(migrations.Migration):
dependencies = [
('gym', '0005_auto_20151023_1522'),
]
operations = [
migrations.RunPython(update_permission_names),
]
| 797 | Python | .py | 23 | 28.130435 | 59 | 0.636245 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,631 | 0003_auto_20151003_2008.py | wger-project_wger/wger/gym/migrations/0003_auto_20151003_2008.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
import datetime
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('gym', '0002_auto_20151003_1944'),
]
operations = [
migrations.CreateModel(
name='Contract',
fields=[
(
'id',
models.AutoField(
auto_created=True, verbose_name='ID', serialize=False, primary_key=True
),
),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('timestamp_edited', models.DateTimeField(auto_now=True)),
('amount', models.PositiveIntegerField(verbose_name='Amount', default=0)),
(
'payment',
models.CharField(
verbose_name='Payment type',
default='3',
help_text='How often the amount will be charged to the member',
choices=[
('1', 'Yearly'),
('2', 'Half yearly'),
('3', 'Monthly'),
('4', 'Biweekly'),
('5', 'Weekly'),
('6', 'Daily'),
],
max_length=2,
),
),
('is_active', models.BooleanField(verbose_name='Contract is active', default=True)),
(
'date_start',
models.DateField(
verbose_name='Start date',
blank=True,
default=datetime.date.today,
null=True,
),
),
('date_end', models.DateField(verbose_name='End date', blank=True, null=True)),
(
'email',
models.EmailField(verbose_name='Email', blank=True, null=True, max_length=254),
),
(
'zip_code',
models.CharField(verbose_name='ZIP code', blank=True, null=True, max_length=10),
),
(
'city',
models.CharField(verbose_name='City', blank=True, null=True, max_length=30),
),
(
'street',
models.CharField(verbose_name='Street', blank=True, null=True, max_length=30),
),
(
'phone',
models.CharField(verbose_name='Phone', blank=True, null=True, max_length=20),
),
(
'profession',
models.CharField(
verbose_name='Profession', blank=True, null=True, max_length=50
),
),
('note', models.TextField(verbose_name='Note', blank=True, null=True)),
],
options={
'ordering': ['-date_start'],
},
),
migrations.CreateModel(
name='ContractType',
fields=[
(
'id',
models.AutoField(
auto_created=True, verbose_name='ID', serialize=False, primary_key=True
),
),
('name', models.CharField(verbose_name='Name', max_length=25)),
(
'description',
models.TextField(verbose_name='Description', blank=True, null=True),
),
('gym', models.ForeignKey(to='gym.Gym', editable=False, on_delete=models.CASCADE)),
],
),
migrations.AddField(
model_name='contract',
name='contract_type',
field=models.ForeignKey(
verbose_name='Contract type',
blank=True,
null=True,
to='gym.ContractType',
on_delete=models.CASCADE,
),
),
migrations.AddField(
model_name='contract',
name='member',
field=models.ForeignKey(
editable=False,
to=settings.AUTH_USER_MODEL,
related_name='contract_member',
on_delete=models.CASCADE,
),
),
migrations.AddField(
model_name='contract',
name='user',
field=models.ForeignKey(
editable=False,
to=settings.AUTH_USER_MODEL,
related_name='contract_user',
on_delete=models.CASCADE,
),
),
]
| 4,953 | Python | .py | 131 | 20.931298 | 100 | 0.42611 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,632 | 0001_initial.py | wger-project_wger/wger/gym/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.conf import settings
import wger.gym.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='AdminUserNote',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('timestamp_edited', models.DateTimeField(auto_now=True)),
('note', models.TextField(verbose_name='Note')),
(
'member',
models.ForeignKey(
related_name='adminusernote_member',
editable=False,
to=settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
),
),
(
'user',
models.ForeignKey(
related_name='adminusernote_user',
editable=False,
to=settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
),
),
],
options={
'ordering': ['-timestamp_created'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Gym',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('name', models.CharField(max_length=60, verbose_name='Name')),
(
'phone',
models.CharField(max_length=20, null=True, verbose_name='Phone', blank=True),
),
(
'email',
models.EmailField(max_length=75, null=True, verbose_name='Email', blank=True),
),
(
'owner',
models.CharField(max_length=100, null=True, verbose_name='Owner', blank=True),
),
(
'zip_code',
models.IntegerField(
max_length=5, null=True, verbose_name='ZIP code', blank=True
),
),
(
'city',
models.CharField(max_length=30, null=True, verbose_name='City', blank=True),
),
(
'street',
models.CharField(max_length=30, null=True, verbose_name='Street', blank=True),
),
],
options={
'ordering': ['name'],
'permissions': (
('gym_trainer', 'Trainer, can see the users for a gym'),
('manage_gym', 'Admin, can manage users for a gym'),
('manage_gyms', 'Admin, can administrate the different gyms'),
),
},
bases=(models.Model,),
),
migrations.CreateModel(
name='GymAdminConfig',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'overview_inactive',
models.BooleanField(
default=True,
help_text='Receive email overviews of inactive members',
verbose_name='Overview inactive members',
),
),
('gym', models.ForeignKey(editable=False, to='gym.Gym', on_delete=models.CASCADE)),
(
'user',
models.OneToOneField(
editable=False, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE
),
),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name='GymConfig',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'weeks_inactive',
models.PositiveIntegerField(
default=4,
help_text='Number of weeks since the last time a user logged his presence to be considered inactive',
max_length=2,
verbose_name='Reminder inactive members',
),
),
(
'gym',
models.OneToOneField(
related_name='config',
editable=False,
to='gym.Gym',
on_delete=models.CASCADE,
),
),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name='GymUserConfig',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'include_inactive',
models.BooleanField(
default=True,
help_text='Include this user in the email list with inactive members',
verbose_name='Include in inactive overview',
),
),
('gym', models.ForeignKey(editable=False, to='gym.Gym', on_delete=models.CASCADE)),
(
'user',
models.OneToOneField(
editable=False, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE
),
),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name='UserDocument',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('timestamp_edited', models.DateTimeField(auto_now=True)),
(
'document',
models.FileField(
upload_to=wger.gym.models.user_document.gym_document_upload_dir,
verbose_name='Document',
),
),
('original_name', models.CharField(max_length=128, editable=False)),
(
'name',
models.CharField(
help_text='Will use file name if nothing provided',
max_length=60,
verbose_name='Name',
blank=True,
),
),
('note', models.TextField(null=True, verbose_name='Note', blank=True)),
(
'member',
models.ForeignKey(
related_name='userdocument_member',
editable=False,
to=settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
),
),
(
'user',
models.ForeignKey(
related_name='userdocument_user',
editable=False,
to=settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
),
),
],
options={
'ordering': ['-timestamp_created'],
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='gymuserconfig',
unique_together=set([('gym', 'user')]),
),
migrations.AlterUniqueTogether(
name='gymadminconfig',
unique_together=set([('gym', 'user')]),
),
]
| 8,976 | Python | .py | 241 | 19.282158 | 125 | 0.403848 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,633 | 0007_auto_20170123_0920.py | wger-project_wger/wger/gym/migrations/0007_auto_20170123_0920.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-01-23 08:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gym', '0006_auto_20160214_1013'),
]
operations = [
migrations.AlterModelOptions(
name='gym',
options={
'ordering': ['name'],
'permissions': (
('gym_trainer', 'Trainer: can see the users for a gym'),
('manage_gym', 'Admin: can manage users for a gym'),
('manage_gyms', 'Admin: can administrate the different gyms'),
),
},
),
migrations.AddField(
model_name='gymconfig',
name='show_name',
field=models.BooleanField(
default=False, verbose_name='Show name of the gym in the header'
),
),
migrations.AlterField(
model_name='contract',
name='options',
field=models.ManyToManyField(
blank=True, to='gym.ContractOption', verbose_name='Options'
),
),
migrations.AlterField(
model_name='gymadminconfig',
name='overview_inactive',
field=models.BooleanField(
default=True,
help_text='Receive email overviews of inactive members',
verbose_name='Overview of inactive members',
),
),
migrations.AlterField(
model_name='gymconfig',
name='weeks_inactive',
field=models.PositiveIntegerField(
default=4,
help_text='Number of weeks since the last time a user logged his presence to be considered inactive',
verbose_name='Reminder of inactive members',
),
),
]
| 1,885 | Python | .py | 52 | 24.25 | 117 | 0.530891 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,634 | 0005_auto_20151023_1522.py | wger-project_wger/wger/gym/migrations/0005_auto_20151023_1522.py | # -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gym', '0004_auto_20151003_2357'),
]
operations = [
migrations.CreateModel(
name='ContractOption',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('name', models.CharField(max_length=25, verbose_name='Name')),
(
'description',
models.TextField(null=True, verbose_name='Description', blank=True),
),
('gym', models.ForeignKey(editable=False, to='gym.Gym', on_delete=models.CASCADE)),
],
options={
'ordering': ['name'],
},
),
migrations.AlterModelOptions(
name='contracttype',
options={'ordering': ['name']},
),
migrations.AddField(
model_name='contract',
name='options',
field=models.ManyToManyField(to='gym.ContractOption', verbose_name='Options'),
),
]
| 1,274 | Python | .py | 37 | 21.756757 | 99 | 0.487429 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,635 | user_config.py | wger-project_wger/wger/gym/views/user_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.contrib.auth.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django.http import HttpResponseForbidden
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.views.generic import UpdateView
# wger
from wger.gym.models import GymUserConfig
from wger.utils.generic_views import WgerFormMixin
logger = logging.getLogger(__name__)
class ConfigUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
"""
View to update an existing user gym configuration
"""
model = GymUserConfig
fields = ['include_inactive']
permission_required = 'gym.change_gymuserconfig'
title = gettext_lazy('Configuration')
def dispatch(self, request, *args, **kwargs):
"""
Only managers for this gym can edit the user settings
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
config = self.get_object()
gym_id = request.user.userprofile.gym_id
if gym_id != config.gym.pk:
return HttpResponseForbidden()
return super(ConfigUpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
"""
Return to the gym user overview
"""
return reverse('gym:gym:user-list', kwargs={'pk': self.object.gym.pk})
| 2,087 | Python | .py | 53 | 35.037736 | 95 | 0.737754 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,636 | config.py | wger-project_wger/wger/gym/views/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.contrib.auth.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django.http.response import HttpResponseForbidden
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.generic import UpdateView
# wger
from wger.gym.models import GymConfig
from wger.utils.generic_views import WgerFormMixin
logger = logging.getLogger(__name__)
class GymConfigUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
"""
View to update an existing gym configuration
"""
model = GymConfig
fields = ['weeks_inactive', 'show_name']
permission_required = 'gym.change_gymconfig'
def dispatch(self, request, *args, **kwargs):
"""
Only managers for this gym can add new members
"""
if request.user.has_perm('gym.change_gymconfig'):
gym_id = request.user.userprofile.gym_id
if gym_id != int(self.kwargs['pk']):
return HttpResponseForbidden()
return super(GymConfigUpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
"""
Return to the gym user overview
"""
return reverse('gym:gym:user-list', kwargs={'pk': self.object.gym.pk})
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(GymConfigUpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit {0}').format(self.object)
return context
| 2,279 | Python | .py | 57 | 35.192982 | 98 | 0.717647 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,637 | gym.py | wger-project_wger/wger/gym/views/gym.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,
PermissionRequiredMixin,
)
from django.contrib.auth.models import (
Group,
User,
)
from django.http.response import (
HttpResponse,
HttpResponseForbidden,
HttpResponseRedirect,
)
from django.shortcuts import (
get_object_or_404,
render,
)
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 (
CreateView,
DeleteView,
ListView,
UpdateView,
)
# Third Party
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
# wger
from wger.config.models import GymConfig as GlobalGymConfig
from wger.gym.forms import (
GymUserAddForm,
GymUserPermissionForm,
)
from wger.gym.helpers import (
get_permission_list,
is_any_gym_admin,
)
from wger.gym.models import (
Gym,
GymAdminConfig,
GymUserConfig,
)
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
WgerMultiplePermissionRequiredMixin,
)
from wger.utils.helpers import password_generator
logger = logging.getLogger(__name__)
class GymListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
"""
Overview of all available gyms
"""
model = Gym
permission_required = 'gym.manage_gyms'
template_name = 'gym/list.html'
def get_context_data(self, **kwargs):
"""
Pass other info to the template
"""
context = super(GymListView, self).get_context_data(**kwargs)
context['global_gym_config'] = GlobalGymConfig.objects.all().first()
return context
class GymUserListView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, ListView):
"""
Overview of all users for a specific gym
"""
model = User
permission_required = ('gym.manage_gym', 'gym.gym_trainer', 'gym.manage_gyms')
template_name = 'gym/member_list.html'
def dispatch(self, request, *args, **kwargs):
"""
Only managers and trainers for this gym can access the members
"""
if request.user.has_perm('gym.manage_gyms') or (
(request.user.has_perm('gym.manage_gym') or request.user.has_perm('gym.gym_trainer'))
and request.user.userprofile.gym_id == int(self.kwargs['pk'])
):
return super(GymUserListView, self).dispatch(request, *args, **kwargs)
return HttpResponseForbidden()
def get_queryset(self):
"""
Return a list with the users, not really a queryset.
"""
out = {'admins': [], 'members': []}
for u in Gym.objects.get_members(self.kwargs['pk']).select_related('usercache'):
out['members'].append({'obj': u, 'last_log': u.usercache.last_activity})
# admins list
for u in Gym.objects.get_admins(self.kwargs['pk']):
out['admins'].append(
{
'obj': u,
'perms': {
'manage_gym': u.has_perm('gym.manage_gym'),
'manage_gyms': u.has_perm('gym.manage_gyms'),
'gym_trainer': u.has_perm('gym.gym_trainer'),
'any_admin': is_any_gym_admin(u),
},
}
)
return out
def get_context_data(self, **kwargs):
"""
Pass other info to the template
"""
context = super(GymUserListView, self).get_context_data(**kwargs)
context['gym'] = Gym.objects.get(pk=self.kwargs['pk'])
context['admin_count'] = len(context['object_list']['admins'])
context['user_count'] = len(context['object_list']['members'])
context['user_table'] = {
'keys': [_('ID'), _('Username'), _('Name'), _('Last activity')],
'users': context['object_list']['members'],
}
return context
class GymAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
"""
View to add a new gym
"""
model = Gym
fields = ['name', 'phone', 'email', 'owner', 'zip_code', 'city', 'street']
title = gettext_lazy('Add new gym')
permission_required = 'gym.add_gym'
@login_required
def gym_new_user_info(request):
"""
Shows info about a newly created user
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
if not request.session.get('gym.user'):
return HttpResponseRedirect(reverse('gym:gym:list'))
if not request.user.has_perm('gym.manage_gyms') and not request.user.has_perm('gym.manage_gym'):
return HttpResponseForbidden()
context = {
'new_user': get_object_or_404(User, pk=request.session['gym.user']['user_pk']),
'password': request.session['gym.user']['password'],
}
return render(request, 'gym/new_user.html', context)
@login_required
def gym_new_user_info_export(request):
"""
Exports the info of newly created user
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
if not request.session.get('gym.user'):
return HttpResponseRedirect(reverse('gym:gym:list'))
if not request.user.has_perm('gym.manage_gyms') and not request.user.has_perm('gym.manage_gym'):
return HttpResponseForbidden()
new_user = get_object_or_404(User, pk=request.session['gym.user']['user_pk'])
new_username = new_user.username
password = request.session['gym.user']['password']
# Crease CSV 'file'
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow([_('Username'), _('First name'), _('Last name'), _('Gym'), _('Password')])
writer.writerow(
[
new_username,
new_user.first_name,
new_user.last_name,
new_user.userprofile.gym.name,
password,
]
)
# Send the data to the browser
today = datetime.date.today()
filename = 'User-data-{t.year}-{t.month:02d}-{t.day:02d}-{user}.csv'.format(
t=today, user=new_username
)
response['Content-Disposition'] = f'attachment; filename={filename}'
response['Content-Length'] = len(response.content)
return response
def reset_user_password(request, user_pk):
"""
Resets the password of the selected user to random password
"""
user = get_object_or_404(User, pk=user_pk)
if not request.user.is_authenticated:
return HttpResponseForbidden()
if not request.user.has_perm('gym.manage_gyms') and not request.user.has_perm('gym.manage_gym'):
return HttpResponseForbidden()
if (
request.user.has_perm('gym.manage_gym')
and request.user.userprofile.gym != user.userprofile.gym
):
return HttpResponseForbidden()
password = password_generator()
user.set_password(password)
user.save()
context = {'mod_user': user, 'password': password}
return render(request, 'gym/reset_user_password.html', context)
def gym_permissions_user_edit(request, user_pk):
"""
Edits the permissions of a gym member
"""
member = get_object_or_404(User, pk=user_pk)
user = request.user
if not user.is_authenticated:
return HttpResponseForbidden()
if not user.has_perm('gym.manage_gyms') and not user.has_perm('gym.manage_gym'):
return HttpResponseForbidden()
if user.has_perm('gym.manage_gym') and user.userprofile.gym != member.userprofile.gym:
return HttpResponseForbidden()
# Calculate available user permissions
form_group_permission = get_permission_list(user)
if request.method == 'POST':
form = GymUserPermissionForm(available_roles=form_group_permission, data=request.POST)
if form.is_valid():
# Remove the user from all gym permission groups
member.groups.remove(Group.objects.get(name='gym_member'))
member.groups.remove(Group.objects.get(name='gym_trainer'))
member.groups.remove(Group.objects.get(name='gym_manager'))
member.groups.remove(Group.objects.get(name='general_gym_manager'))
# Set appropriate permission groups
if 'user' in form.cleaned_data['role']:
member.groups.add(Group.objects.get(name='gym_member'))
if 'trainer' in form.cleaned_data['role']:
member.groups.add(Group.objects.get(name='gym_trainer'))
if 'admin' in form.cleaned_data['role']:
member.groups.add(Group.objects.get(name='gym_manager'))
if 'manager' in form.cleaned_data['role']:
member.groups.add(Group.objects.get(name='general_gym_manager'))
return HttpResponseRedirect(
reverse('gym:gym:user-list', kwargs={'pk': member.userprofile.gym.pk})
)
else:
initial_data = {}
if member.groups.filter(name='gym_member').exists():
initial_data['user'] = True
if member.groups.filter(name='gym_trainer').exists():
initial_data['trainer'] = True
if member.groups.filter(name='gym_manager').exists():
initial_data['admin'] = True
if member.groups.filter(name='general_gym_manager').exists():
initial_data['manager'] = True
form = GymUserPermissionForm(
initial={'role': initial_data}, available_roles=form_group_permission
)
# Set form action to absolute path
form.helper.form_action = request.path
context = {'title': member.get_full_name(), 'form': form, 'submit_text': 'Save'}
return render(request, 'form.html', context)
class GymAddUserView(
WgerFormMixin,
LoginRequiredMixin,
WgerMultiplePermissionRequiredMixin,
CreateView,
):
"""
View to add a user to a new gym
"""
model = User
title = gettext_lazy('Add user to gym')
success_url = reverse_lazy('gym:gym:new-user-data')
permission_required = ('gym.manage_gym', 'gym.manage_gyms')
form_class = GymUserAddForm
def get_initial(self):
"""
Pre-select the 'user' role
"""
return {'role': ['user']}
def dispatch(self, request, *args, **kwargs):
"""
Only managers for this gym can add new members
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
if not request.user.has_perm('gym.manage_gyms') and not request.user.has_perm(
'gym.manage_gym'
):
return HttpResponseForbidden()
# Gym managers can edit their own gym only, general gym managers
# can edit all gyms
if (
request.user.has_perm('gym.manage_gym')
and not request.user.has_perm('gym.manage_gyms')
and request.user.userprofile.gym_id != int(self.kwargs['gym_pk'])
):
return HttpResponseForbidden()
return super(GymAddUserView, self).dispatch(request, *args, **kwargs)
def get_form(self):
"""
Set available user permissions
"""
form = self.form_class(
available_roles=get_permission_list(self.request.user), **self.get_form_kwargs()
)
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_valid(self, form):
"""
Create the user, set the user permissions and gym
"""
gym = Gym.objects.get(pk=self.kwargs['gym_pk'])
password = password_generator()
user = User.objects.create_user(
form.cleaned_data['username'], form.cleaned_data['email'], password
)
user.first_name = form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name']
form.instance = user
# Update profile
user.userprofile.gym = gym
user.userprofile.birthdate = form.cleaned_data['birthdate']
user.userprofile.save()
# Set appropriate permission groups
if 'user' in form.cleaned_data['role']:
user.groups.add(Group.objects.get(name='gym_member'))
if 'trainer' in form.cleaned_data['role']:
user.groups.add(Group.objects.get(name='gym_trainer'))
if 'admin' in form.cleaned_data['role']:
user.groups.add(Group.objects.get(name='gym_manager'))
if 'manager' in form.cleaned_data['role']:
user.groups.add(Group.objects.get(name='general_gym_manager'))
self.request.session['gym.user'] = {'user_pk': user.pk, 'password': password}
# Create config
if is_any_gym_admin(user):
config = GymAdminConfig()
else:
config = GymUserConfig()
config.user = user
config.gym = gym
config.save()
return super(GymAddUserView, self).form_valid(form)
class GymUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
"""
View to update an existing gym
"""
model = Gym
fields = ['name', 'phone', 'email', 'owner', 'zip_code', 'city', 'street']
title = gettext_lazy('Edit gym')
permission_required = 'gym.change_gym'
def dispatch(self, request, *args, **kwargs):
"""
Only managers for this gym and general managers can edit the gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
if request.user.has_perm('gym.manage_gym') and not request.user.has_perm('gym.manage_gyms'):
if request.user.userprofile.gym_id != int(self.kwargs['pk']):
return HttpResponseForbidden()
return super(GymUpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(GymUpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit {0}').format(self.object)
return context
class GymDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
"""
View to delete an existing gym
"""
model = Gym
success_url = reverse_lazy('gym:gym:list')
permission_required = 'gym.delete_gym'
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(GymDeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete {0}?').format(self.object)
return context
| 15,654 | Python | .py | 397 | 32.030227 | 100 | 0.644345 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,638 | export.py | wger-project_wger/wger/gym/views/export.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.http.response import (
HttpResponse,
HttpResponseForbidden,
)
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _
# wger
from wger.gym.models import Gym
logger = logging.getLogger(__name__)
@login_required
def users(request, gym_pk):
"""
Exports all members in selected gym
"""
gym = get_object_or_404(Gym, pk=gym_pk)
if not request.user.has_perm('gym.manage_gyms') and not request.user.has_perm('gym.manage_gym'):
return HttpResponseForbidden()
if request.user.has_perm('gym.manage_gym') and request.user.userprofile.gym != gym:
return HttpResponseForbidden()
# Create CSV 'file'
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response, delimiter='\t', quoting=csv.QUOTE_ALL)
writer.writerow(
[
_('Nr.'),
_('Gym'),
_('Username'),
_('Email'),
_('First name'),
_('Last name'),
_('Gender'),
_('Age'),
_('ZIP code'),
_('City'),
_('Street'),
_('Phone'),
]
)
for user in Gym.objects.get_members(gym_pk):
address = user.userprofile.address
writer.writerow(
[
user.id,
gym.name,
user.username,
user.email,
user.first_name,
user.last_name,
user.userprofile.get_gender_display(),
user.userprofile.age,
address['zip_code'],
address['city'],
address['street'],
address['phone'],
]
)
# Send the data to the browser
today = datetime.date.today()
filename = 'User-data-gym-{gym}-{t.year}-{t.month:02d}-{t.day:02d}.csv'.format(
t=today, gym=gym.id
)
response['Content-Disposition'] = f'attachment; filename={filename}'
response['Content-Length'] = len(response.content)
return response
| 2,862 | Python | .py | 84 | 26.869048 | 100 | 0.623508 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,639 | contract_type.py | wger-project_wger/wger/gym/views/contract_type.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.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django.http.response import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import (
CreateView,
DeleteView,
ListView,
UpdateView,
)
# wger
from wger.gym.models import (
ContractType,
Gym,
)
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
)
logger = logging.getLogger(__name__)
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
"""
View to add a new contract type
"""
model = ContractType
fields = ('name', 'description')
title = gettext_lazy('Add contract type')
permission_required = 'gym.add_contracttype'
member = None
def get_success_url(self):
"""
Redirect back to overview page
"""
return reverse('gym:contract_type:list', kwargs={'gym_pk': self.object.gym_id})
def dispatch(self, request, *args, **kwargs):
"""
Can only add contract types in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
if request.user.userprofile.gym_id != int(self.kwargs['gym_pk']):
return HttpResponseForbidden()
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Set the foreign key to the gym object
"""
form.instance.gym_id = self.kwargs['gym_pk']
return super(AddView, self).form_valid(form)
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
"""
View to update an existing contract option
"""
model = ContractType
fields = ('name', 'description')
permission_required = 'gym.change_contracttype'
def dispatch(self, request, *args, **kwargs):
"""
Can only add contract types in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
contract_type = self.get_object()
if request.user.userprofile.gym_id != contract_type.gym_id:
return HttpResponseForbidden()
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
"""
Redirect back to overview page
"""
return reverse('gym:contract_type:list', kwargs={'gym_pk': self.object.gym_id})
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit {0}').format(self.object)
return context
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
"""
View to delete an existing contract type
"""
model = ContractType
permission_required = 'gym.delete_contracttype'
def dispatch(self, request, *args, **kwargs):
"""
Can only add contract types in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
contract_type = self.get_object()
if request.user.userprofile.gym_id != contract_type.gym_id:
return HttpResponseForbidden()
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
"""
Redirect back to overview page
"""
return reverse('gym:contract_type:list', kwargs={'gym_pk': self.object.gym_id})
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete {0}').format(self.object)
return context
class ListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
"""
Overview of all available contract options
"""
model = ContractType
permission_required = 'gym.add_contracttype'
template_name = 'contract_type/list.html'
gym = None
def get_queryset(self):
"""
Only contract types for current gym
"""
return ContractType.objects.filter(gym=self.gym)
def dispatch(self, request, *args, **kwargs):
"""
Can only list contract types in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.gym = get_object_or_404(Gym, id=self.kwargs['gym_pk'])
if request.user.userprofile.gym_id != self.gym.id:
return HttpResponseForbidden()
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(ListView, self).get_context_data(**kwargs)
context['gym'] = self.gym
return context
| 5,826 | Python | .py | 160 | 30.025 | 91 | 0.668977 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,640 | document.py | wger-project_wger/wger/gym/views/document.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.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django.contrib.auth.models import User
from django.http.response import HttpResponseForbidden
from django.urls import reverse
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import (
CreateView,
DeleteView,
ListView,
UpdateView,
)
# wger
from wger.gym.models import UserDocument
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
)
logger = logging.getLogger(__name__)
class ListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
"""
Overview of all available admin notes
"""
model = UserDocument
permission_required = 'gym.add_userdocument'
template_name = 'document/list.html'
member = None
def get_queryset(self):
"""
Only documents for current user
"""
return UserDocument.objects.filter(member_id=self.kwargs['user_pk'])
def dispatch(self, request, *args, **kwargs):
"""
Can only add notes to users in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
user = User.objects.get(pk=self.kwargs['user_pk'])
self.member = user
if user.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(ListView, self).get_context_data(**kwargs)
context['member'] = self.member
return context
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
"""
View to add a new document
"""
model = UserDocument
fields = ['document', 'name', 'note']
title = gettext_lazy('Add note')
permission_required = 'gym.add_userdocument'
member = None
def get_success_url(self):
"""
Redirect back to user page
"""
return reverse('gym:document:list', kwargs={'user_pk': self.member.pk})
def dispatch(self, request, *args, **kwargs):
"""
Can only add documents to users in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
user = User.objects.get(pk=self.kwargs['user_pk'])
self.member = user
if user.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Set user instances
"""
form.instance.original_name = form.cleaned_data['document'].name
if not form.cleaned_data['name']:
form.instance.name = form.cleaned_data['document'].name
form.instance.member = self.member
form.instance.user = self.request.user
return super(AddView, self).form_valid(form)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(AddView, self).get_context_data(**kwargs)
context['enctype'] = 'multipart/form-data'
return context
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
"""
View to update an existing document
"""
model = UserDocument
fields = ['document', 'name', 'note']
permission_required = 'gym.change_userdocument'
def get_success_url(self):
"""
Redirect back to user page
"""
return reverse('gym:document:list', kwargs={'user_pk': self.object.member.pk})
def dispatch(self, request, *args, **kwargs):
"""
Only trainers for this gym can edit user notes
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
note = self.get_object()
if note.member.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit {0}').format(self.object)
return context
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
"""
View to delete an existing document
"""
model = UserDocument
permission_required = 'gym.delete_userdocument'
def get_success_url(self):
"""
Redirect back to user page
"""
return reverse('gym:document:list', kwargs={'user_pk': self.object.member.pk})
def dispatch(self, request, *args, **kwargs):
"""
Only trainers for this gym can delete documents
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
note = self.get_object()
if note.member.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete {0}?').format(self.object)
return context
| 6,373 | Python | .py | 171 | 30.631579 | 91 | 0.665585 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,641 | contract_option.py | wger-project_wger/wger/gym/views/contract_option.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.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django.http.response import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import (
CreateView,
DeleteView,
ListView,
UpdateView,
)
# wger
from wger.gym.models import (
ContractOption,
Gym,
)
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
)
logger = logging.getLogger(__name__)
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
"""
View to add a new contract option
"""
model = ContractOption
fields = ('name', 'description')
title = gettext_lazy('Add option')
permission_required = 'gym.add_contractoption'
member = None
def get_success_url(self):
"""
Redirect back to overview page
"""
return reverse('gym:contract-option:list', kwargs={'gym_pk': self.object.gym_id})
def dispatch(self, request, *args, **kwargs):
"""
Can only add contract types in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
if request.user.userprofile.gym_id != int(self.kwargs['gym_pk']):
return HttpResponseForbidden()
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Set the foreign key to the gym object
"""
form.instance.gym_id = self.kwargs['gym_pk']
return super(AddView, self).form_valid(form)
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
"""
View to update an existing contract option
"""
model = ContractOption
fields = ('name', 'description')
permission_required = 'gym.change_contractoption'
def dispatch(self, request, *args, **kwargs):
"""
Can only add contract types in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
contract_type = self.get_object()
if request.user.userprofile.gym_id != contract_type.gym_id:
return HttpResponseForbidden()
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
"""
Redirect back to overview page
"""
return reverse('gym:contract-option:list', kwargs={'gym_pk': self.object.gym_id})
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit {0}').format(self.object)
return context
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
"""
View to delete an existing contract option
"""
model = ContractOption
permission_required = 'gym.delete_contractoption'
def dispatch(self, request, *args, **kwargs):
"""
Can only add contract option in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
contract_type = self.get_object()
if request.user.userprofile.gym_id != contract_type.gym_id:
return HttpResponseForbidden()
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
"""
Redirect back to overview page
"""
return reverse('gym:contract-option:list', kwargs={'gym_pk': self.object.gym_id})
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete {0}').format(self.object)
return context
class ListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
"""
Overview of all available contract options
"""
model = ContractOption
permission_required = 'gym.add_contractoption'
template_name = 'contract_option/list.html'
gym = None
def get_queryset(self):
"""
Only documents for current user
"""
return ContractOption.objects.filter(gym=self.gym)
def dispatch(self, request, *args, **kwargs):
"""
Can only list contract types in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.gym = get_object_or_404(Gym, id=self.kwargs['gym_pk'])
if request.user.userprofile.gym_id != self.gym.id:
return HttpResponseForbidden()
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(ListView, self).get_context_data(**kwargs)
context['gym'] = self.gym
return context
| 5,848 | Python | .py | 160 | 30.1625 | 91 | 0.670619 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,642 | admin_notes.py | wger-project_wger/wger/gym/views/admin_notes.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.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django.contrib.auth.models import User
from django.http.response import HttpResponseForbidden
from django.urls import reverse
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import (
CreateView,
DeleteView,
ListView,
UpdateView,
)
# wger
from wger.gym.models import AdminUserNote
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
)
logger = logging.getLogger(__name__)
class ListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
"""
Overview of all available admin notes
"""
model = AdminUserNote
permission_required = 'gym.add_adminusernote'
template_name = 'admin_notes/list.html'
member = None
def get_queryset(self):
"""
Only notes for current user
"""
return AdminUserNote.objects.filter(member_id=self.kwargs['user_pk'])
def dispatch(self, request, *args, **kwargs):
"""
Can only add notes to users in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
user = User.objects.get(pk=self.kwargs['user_pk'])
self.member = user
if user.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(ListView, self).get_context_data(**kwargs)
context['member'] = self.member
return context
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
"""
View to add a new admin note
"""
model = AdminUserNote
fields = ['note']
title = gettext_lazy('Add note')
permission_required = 'gym.add_adminusernote'
member = None
def get_success_url(self):
"""
Redirect back to user page
"""
return reverse('gym:admin_note:list', kwargs={'user_pk': self.member.pk})
def dispatch(self, request, *args, **kwargs):
"""
Can only add notes to users in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
user = User.objects.get(pk=self.kwargs['user_pk'])
self.member = user
gym_id = user.userprofile.gym_id
if gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Set user instances
"""
form.instance.member = self.member
form.instance.user = self.request.user
return super(AddView, self).form_valid(form)
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
"""
View to update an existing admin note
"""
model = AdminUserNote
fields = ['note']
permission_required = 'gym.change_adminusernote'
def get_success_url(self):
"""
Redirect back to user page
"""
return reverse('gym:admin_note:list', kwargs={'user_pk': self.object.member.pk})
def dispatch(self, request, *args, **kwargs):
"""
Only trainers for this gym can edit user notes
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
note = self.get_object()
if note.member.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit {0}').format(self.object)
return context
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
"""
View to delete an existing admin note
"""
model = AdminUserNote
permission_required = 'gym.delete_adminusernote'
def get_success_url(self):
"""
Redirect back to user page
"""
return reverse('gym:admin_note:list', kwargs={'user_pk': self.object.member.pk})
def dispatch(self, request, *args, **kwargs):
"""
Only trainers for this gym can delete user notes
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
note = self.get_object()
if note.member.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _('Delete {0}?').format(self.object)
return context
| 5,935 | Python | .py | 162 | 30.135802 | 91 | 0.668003 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,643 | contract.py | wger-project_wger/wger/gym/views/contract.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.mixins import (
LoginRequiredMixin,
PermissionRequiredMixin,
)
from django.contrib.auth.models import User
from django.http.response import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import (
CreateView,
DetailView,
ListView,
UpdateView,
)
# wger
from wger.gym.models import Contract
from wger.utils.generic_views import WgerFormMixin
logger = logging.getLogger(__name__)
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
"""
View to add a new contract
"""
model = Contract
fields = [
'contract_type',
'options',
'amount',
'payment',
'is_active',
'date_start',
'date_end',
'email',
'zip_code',
'city',
'street',
'phone',
'profession',
'note',
]
title = gettext_lazy('Add contract')
permission_required = 'gym.add_contract'
member = None
def get_initial(self):
"""
Get the initial data for new contracts
Since the user's data probably didn't change between one contract and the
next, try to fill in as much data as possible from previous ones or the
user's profile
"""
out = {}
if Contract.objects.filter(member=self.member).exists():
last_contract = Contract.objects.filter(member=self.member).first()
for key in (
'amount',
'payment',
'email',
'zip_code',
'city',
'street',
'phone',
'profession',
):
out[key] = getattr(last_contract, key)
elif self.member.email:
out['email'] = self.member.email
return out
def dispatch(self, request, *args, **kwargs):
"""
Can only add documents to users in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
user = get_object_or_404(User, pk=self.kwargs['user_pk'])
self.member = user
if user.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Set user instances
"""
form.instance.member = self.member
form.instance.user = self.request.user
return super(AddView, self).form_valid(form)
class DetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView):
"""
Detail view of a member's contract
"""
model = Contract
template_name = 'contract/view.html'
permission_required = 'gym.add_contract'
def dispatch(self, request, *args, **kwargs):
"""
Can only see contracts for own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
contract = self.get_object()
if contract.member.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(DetailView, self).dispatch(request, *args, **kwargs)
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
"""
View to update an existing contract
"""
model = Contract
fields = [
'contract_type',
'options',
'amount',
'payment',
'is_active',
'date_start',
'date_end',
'email',
'zip_code',
'city',
'street',
'phone',
'profession',
'note',
]
permission_required = 'gym.change_contract'
def dispatch(self, request, *args, **kwargs):
"""
Only trainers for this gym can edit user notes
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
contract = self.get_object()
if contract.member.userprofile.gym_id != request.user.userprofile.gym_id:
return HttpResponseForbidden()
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _('Edit {0}').format(self.object)
return context
class ListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
"""
Overview of all available admin notes
"""
model = Contract
permission_required = 'gym.add_contract'
template_name = 'contract/list.html'
member = None
def get_queryset(self):
"""
Only documents for current user
"""
return Contract.objects.filter(member=self.member)
def dispatch(self, request, *args, **kwargs):
"""
Can only list contract types in own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.member = get_object_or_404(User, id=self.kwargs['user_pk'])
if request.user.userprofile.gym_id != self.member.userprofile.gym_id:
return HttpResponseForbidden()
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(ListView, self).get_context_data(**kwargs)
context['member'] = self.member
return context
| 6,442 | Python | .py | 190 | 26.489474 | 89 | 0.633424 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,644 | admin_config.py | wger-project_wger/wger/gym/views/admin_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
from django.utils.translation import (
gettext as _,
gettext_lazy,
)
from django.views.generic import UpdateView
# wger
from wger.gym.models import GymAdminConfig
from wger.utils.generic_views import WgerFormMixin
logger = logging.getLogger(__name__)
class ConfigUpdateView(WgerFormMixin, UpdateView):
"""
View to update an existing admin gym configuration
"""
model = GymAdminConfig
fields = ['overview_inactive']
permission_required = 'gym.change_gymadminconfig'
title = gettext_lazy('Configuration')
def get_success_url(self):
"""
Return to the gym user overview
"""
return reverse('gym:gym:user-list', kwargs={'pk': self.object.gym.pk})
def get_context_data(self, **kwargs):
"""
Send some additional data to the template
"""
context = super(ConfigUpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:admin_config:edit', kwargs={'pk': self.object.id})
context['title'] = _('Configuration')
return context
| 1,819 | Python | .py | 48 | 33.916667 | 96 | 0.725568 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,645 | test_user.py | wger-project_wger/wger/gym/tests/test_user.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.contrib.auth.models import (
Permission,
User,
)
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
# wger
from wger.core.models import UserProfile
from wger.core.tests.base_testcase import WgerTestCase
from wger.gym.models import (
Gym,
GymAdminConfig,
)
class GymAddUserTestCase(WgerTestCase):
"""
Tests admin adding users to gyms
"""
def add_user(self, fail=False):
"""
Helper function to add users
"""
count_before = User.objects.all().count()
GymAdminConfig.objects.all().delete()
response = self.client.get(reverse('gym:gym:add-user', kwargs={'gym_pk': 1}))
self.assertEqual(GymAdminConfig.objects.all().count(), 0)
if fail:
self.assertEqual(response.status_code, 403)
else:
self.assertEqual(response.status_code, 200)
response = self.client.post(
reverse('gym:gym:add-user', kwargs={'gym_pk': 1}),
{
'first_name': 'Cletus',
'last_name': 'Spuckle',
'username': 'cletus',
'email': 'cletus@spuckle-megacorp.com',
'role': 'admin',
},
)
count_after = User.objects.all().count()
if fail:
self.assertEqual(response.status_code, 403)
self.assertEqual(count_before, count_after)
self.assertFalse(self.client.session.get('gym.user'))
else:
self.assertEqual(count_before + 1, count_after)
self.assertEqual(response.status_code, 302)
self.assertTrue(self.client.session['gym.user']['user_pk'], 3)
self.assertTrue(self.client.session['gym.user']['password'])
self.assertEqual(len(self.client.session['gym.user']['password']), 15)
new_user = User.objects.get(pk=self.client.session['gym.user']['user_pk'])
self.assertEqual(GymAdminConfig.objects.all().count(), 1)
self.assertEqual(new_user.userprofile.gym_id, 1)
def test_add_user_authorized(self):
"""
Tests adding a user as authorized user
"""
self.user_login('admin')
self.add_user()
def test_add_user_authorized2(self):
"""
Tests adding a user as authorized user
"""
self.user_login('general_manager1')
self.add_user()
def test_add_user_unauthorized(self):
"""
Tests adding a user an unauthorized user
"""
self.user_login('test')
self.add_user(fail=True)
def test_add_user_unauthorized2(self):
"""
Tests adding a user an unauthorized user
"""
self.user_login('trainer1')
self.add_user(fail=True)
def test_add_user_unauthorized3(self):
"""
Tests adding a user an unauthorized user
"""
self.user_login('manager3')
self.add_user(fail=True)
def test_add_user_logged_out(self):
"""
Tests adding a user a logged out user
"""
self.add_user(fail=True)
def new_user_data_export(self, fail=False):
"""
Helper function to test exporting the data of a newly created user
"""
response = self.client.get(reverse('gym:gym:new-user-data-export'))
if fail:
self.assertIn(response.status_code, (302, 403))
else:
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'text/csv')
today = datetime.date.today()
filename = 'User-data-{t.year}-{t.month:02d}-{t.day:02d}-cletus.csv'.format(t=today)
self.assertEqual(response['Content-Disposition'], f'attachment; filename={filename}')
self.assertGreaterEqual(len(response.content), 90)
self.assertLessEqual(len(response.content), 120)
def test_new_user_data_export(self):
"""
Test exporting the data of a newly created user
"""
self.user_login('admin')
self.add_user()
self.new_user_data_export(fail=False)
self.user_logout()
self.new_user_data_export(fail=True)
self.user_logout()
self.user_login('test')
self.new_user_data_export(fail=True)
class TrainerLoginTestCase(WgerTestCase):
"""
Tests the trainer login view (switching to user ID)
"""
def test_anonymous(self):
"""
Test the trainer login as an anonymous user
"""
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 1}))
self.assertEqual(response.status_code, 302)
self.assertFalse(self.client.session.get('trainer.identity'))
def test_user(self):
"""
Test the trainer login as a logged in user without rights
"""
self.user_login('test')
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 1}))
self.assertEqual(response.status_code, 403)
self.assertFalse(self.client.session.get('trainer.identity'))
def test_trainer(self):
"""
Test the trainer login as a logged in user with enough rights
"""
self.user_login('admin')
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 2}))
self.assertEqual(response.status_code, 302)
self.assertTrue(self.client.session.get('trainer.identity'))
def test_wrong_gym(self):
"""
Test changing the identity to a user in a different gym
"""
profile = UserProfile.objects.get(user_id=2)
profile.gym_id = 2
profile.save()
self.user_login('admin')
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 2}))
self.assertEqual(response.status_code, 404)
self.assertFalse(self.client.session.get('trainer.identity'))
def test_gym_trainer(self):
"""
Test changing the identity to a user with trainer rights
"""
user = User.objects.get(pk=2)
content_type = ContentType.objects.get_for_model(Gym)
permission = Permission.objects.get(content_type=content_type, codename='gym_trainer')
user.user_permissions.add(permission)
self.user_login('admin')
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 2}))
self.assertEqual(response.status_code, 403)
self.assertFalse(self.client.session.get('trainer.identity'))
def test_gym_manager(self):
"""
Test changing the identity to a user with gym management rights
"""
user = User.objects.get(pk=2)
content_type = ContentType.objects.get_for_model(Gym)
permission = Permission.objects.get(content_type=content_type, codename='manage_gym')
user.user_permissions.add(permission)
self.user_login('admin')
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 2}))
self.assertEqual(response.status_code, 403)
self.assertFalse(self.client.session.get('trainer.identity'))
def test_gyms_manager(self):
"""
Test changing the identity to a user with gyms management rights
"""
user = User.objects.get(pk=2)
content_type = ContentType.objects.get_for_model(Gym)
permission = Permission.objects.get(content_type=content_type, codename='manage_gyms')
user.user_permissions.add(permission)
self.user_login('admin')
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 2}))
self.assertEqual(response.status_code, 403)
self.assertFalse(self.client.session.get('trainer.identity'))
class TrainerLogoutTestCase(WgerTestCase):
"""
Tests the trainer logout view (switching back to trainer ID)
"""
def test_logout(self):
"""
Test the trainer login as an anonymous user
"""
self.user_login('admin')
self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 2}))
self.assertTrue(self.client.session.get('trainer.identity'))
self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 1}))
self.assertFalse(self.client.session.get('trainer.identity'))
| 9,081 | Python | .py | 218 | 33.458716 | 97 | 0.642242 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,646 | test_contract_options.py | wger-project_wger/wger/gym/tests/test_contract_options.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 (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
delete_testcase_add_methods,
)
from wger.gym.models import ContractOption
class AddContractOptionTestCase(WgerAddTestCase):
"""
Tests creating a new contract option
"""
object_class = ContractOption
url = reverse('gym:contract-option:add', kwargs={'gym_pk': 1})
data = {'name': 'Some name'}
user_success = (
'manager1',
'manager2',
)
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
class EditContractOptionTestCase(WgerEditTestCase):
"""
Tests editing a contract option
"""
pk = 1
object_class = ContractOption
url = 'gym:contract-option:edit'
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
data = {'name': 'Standard contract 16-Gj'}
class DeleteContractOptionTestCase(WgerDeleteTestCase):
"""
Tests deleting a contract option
"""
pk = 1
object_class = ContractOption
url = 'gym:contract-option:delete'
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
delete_testcase_add_methods(DeleteContractOptionTestCase)
class AccessContractOptionOverviewTestCase(WgerAccessTestCase):
"""
Test accessing the contract option page
"""
url = reverse('gym:contract-option:list', kwargs={'gym_pk': 1})
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
| 2,912 | Python | .py | 107 | 21.392523 | 78 | 0.634995 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,647 | test_user_last_activity.py | wger-project_wger/wger/gym/tests/test_user_last_activity.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.contrib.auth.models import User
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.gym.helpers import get_user_last_activity
from wger.manager.models import (
WorkoutLog,
WorkoutSession,
)
class UserLastActivityTestCase(WgerTestCase):
"""
Test the helper function for last user activity
"""
def test_user_last_activity(self):
"""
Test the helper function for last user activity
"""
self.user_login('admin')
user = User.objects.get(username='admin')
log = WorkoutLog.objects.get(pk=1)
session = WorkoutSession.objects.get(pk=1)
self.assertEqual(user.usercache.last_activity, datetime.date(2014, 1, 30))
self.assertEqual(get_user_last_activity(user), datetime.date(2014, 1, 30))
# Log more recent than session
log.date = datetime.date(2014, 10, 2)
log.save()
session.date = datetime.date(2014, 10, 1)
session.save()
user = User.objects.get(username='admin')
self.assertEqual(get_user_last_activity(user), datetime.date(2014, 10, 2))
self.assertEqual(user.usercache.last_activity, datetime.date(2014, 10, 2))
# Session more recent than log
log.date = datetime.date(2014, 9, 1)
log.save()
session.date = datetime.date(2014, 10, 5)
session.save()
user = User.objects.get(username='admin')
self.assertEqual(get_user_last_activity(user), datetime.date(2014, 10, 5))
self.assertEqual(user.usercache.last_activity, datetime.date(2014, 10, 5))
# No logs, but session
WorkoutLog.objects.filter(user=user).delete()
user = User.objects.get(username='admin')
self.assertEqual(get_user_last_activity(user), datetime.date(2014, 10, 5))
self.assertEqual(user.usercache.last_activity, datetime.date(2014, 10, 5))
| 2,585 | Python | .py | 59 | 38.169492 | 82 | 0.705882 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,648 | test_contract_types.py | wger-project_wger/wger/gym/tests/test_contract_types.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 (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
delete_testcase_add_methods,
)
from wger.gym.models import ContractType
class AddContractTypeTestCase(WgerAddTestCase):
"""
Tests creating a new contract
"""
object_class = ContractType
url = reverse('gym:contract_type:add', kwargs={'gym_pk': 1})
data = {'name': 'Some name'}
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
class EditContractTypeTestCase(WgerEditTestCase):
"""
Tests editing a contract type
"""
pk = 1
object_class = ContractType
url = 'gym:contract_type:edit'
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
data = {'name': 'Standard contract 16-Gj'}
class DeleteContractTypeTestCase(WgerDeleteTestCase):
"""
Tests deleting a contract type
"""
pk = 1
object_class = ContractType
url = 'gym:contract_type:delete'
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
delete_testcase_add_methods(DeleteContractTypeTestCase)
class AccessContractTypeOverviewTestCase(WgerAccessTestCase):
"""
Test accessing the contract list page
"""
url = reverse('gym:contract_type:list', kwargs={'gym_pk': 1})
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
| 2,850 | Python | .py | 104 | 21.634615 | 78 | 0.634799 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,649 | test_user_config.py | wger-project_wger/wger/gym/tests/test_user_config.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
# wger
from wger.core.tests.base_testcase import WgerEditTestCase
from wger.gym.models import GymUserConfig
class EditConfigTestCase(WgerEditTestCase):
"""
Tests editing a user config
"""
pk = 1
object_class = GymUserConfig
url = 'gym:user_config:edit'
user_success = 'trainer1'
user_fail = 'member1'
user_success = (
'trainer1',
'trainer2',
'trainer3',
'admin',
)
user_fail = (
'general_manager1',
'general_manager2',
'member1',
'member2',
'trainer4',
'manager3',
)
data = {'include_inactive': False}
| 1,277 | Python | .py | 40 | 27.5 | 78 | 0.700487 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,650 | test_inactive_members.py | wger-project_wger/wger/gym/tests/test_inactive_members.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 import mail
from django.core.management import call_command
# wger
from wger.core.tests.base_testcase import WgerTestCase
class EmailInactiveUserTestCase(WgerTestCase):
"""
Test email reminders for inactive users
"""
def test_reminder(self, fail=False):
"""
Test email reminders for inactive users
"""
call_command('inactive-members')
self.assertEqual(len(mail.outbox), 6)
recipment_list = [message.to[0] for message in mail.outbox]
trainer_list = [
'trainer4@example.com',
'trainer5@example.com',
'trainer1@example.com',
'trainer2@example.com',
'trainer3@example.com',
]
recipment_list.sort()
trainer_list.sort()
self.assertEqual(recipment_list.sort(), trainer_list.sort())
| 1,512 | Python | .py | 39 | 33.358974 | 78 | 0.70785 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,651 | test_gym.py | wger-project_wger/wger/gym/tests/test_gym.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_lazy
# wger
from wger.core.models import UserProfile
from wger.core.tests.base_testcase import (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
WgerTestCase,
delete_testcase_add_methods,
)
from wger.gym.models import Gym
class GymRepresentationTestCase(WgerTestCase):
"""
Test the representation of a model
"""
def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual(str(Gym.objects.get(pk=1)), 'Test 123')
class GymOverviewTest(WgerAccessTestCase):
"""
Tests accessing the gym overview page
"""
url = 'gym:gym:list'
anonymous_fail = True
user_success = (
'admin',
'general_manager1',
'general_manager2',
)
user_fail = (
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
class GymUserOverviewTest(WgerAccessTestCase):
"""
Tests accessing the gym user overview page
"""
url = reverse_lazy('gym:gym:user-list', kwargs={'pk': 1})
anonymous_fail = True
user_success = (
'admin',
'trainer2',
'trainer3',
'manager1',
'general_manager1',
'general_manager2',
)
user_fail = (
'member1',
'member2',
'trainer4',
'manager3',
)
class AddGymTestCase(WgerAddTestCase):
"""
Tests adding a new gym
"""
object_class = Gym
url = 'gym:gym:add'
data = {'name': 'The name here'}
user_success = ('admin', 'general_manager1')
user_fail = (
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager1',
'manager3',
)
class DeleteGymTestCase(WgerDeleteTestCase):
"""
Tests deleting a gym
"""
pk = 2
object_class = Gym
url = 'gym:gym:delete'
user_success = (
'admin',
'general_manager1',
'general_manager2',
)
user_fail = (
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager1',
'manager3',
)
delete_testcase_add_methods(DeleteGymTestCase)
class EditGymTestCase(WgerEditTestCase):
"""
Tests editing a gym
"""
object_class = Gym
url = 'gym:gym:edit'
pk = 1
data = {'name': 'A different name'}
user_success = (
'admin',
'manager1',
'general_manager1',
'general_manager2',
)
user_fail = (
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
class GymTestCase(WgerTestCase):
"""
Tests other gym methods
"""
def test_delete_gym(self):
"""
Tests that deleting a gym also removes it from all user profiles
"""
gym = Gym.objects.get(pk=1)
self.assertEqual(UserProfile.objects.filter(gym=gym).count(), 17)
gym.delete()
self.assertEqual(UserProfile.objects.filter(gym_id=1).count(), 0)
| 3,880 | Python | .py | 148 | 20.283784 | 78 | 0.621155 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,652 | test_admin_user_notes.py | wger-project_wger/wger/gym/tests/test_admin_user_notes.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_lazy
# wger
from wger.core.tests.base_testcase import (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
delete_testcase_add_methods,
)
from wger.gym.models import AdminUserNote
class AdminNoteOverviewTest(WgerAccessTestCase):
"""
Tests accessing the admin notes overview page
"""
url = reverse_lazy('gym:admin_note:list', kwargs={'user_pk': 14})
anonymous_fail = True
user_success = (
'trainer1',
'trainer2',
'trainer3',
)
user_fail = (
'member1',
'manager1',
'manager2',
'trainer4',
'general_manager1',
'general_manager2',
)
class AddAdminNoteTestCase(WgerAddTestCase):
"""
Tests adding a new admin note
"""
object_class = AdminUserNote
url = reverse_lazy('gym:admin_note:add', kwargs={'user_pk': 14})
data = {'note': 'The note text goes here'}
user_success = (
'trainer1',
'trainer2',
'trainer3',
)
user_fail = (
'member1',
'manager1',
'manager2',
'trainer4',
'general_manager1',
'general_manager2',
)
class EditAdminNoteTestCase(WgerEditTestCase):
"""
Tests editing an admin note
"""
object_class = AdminUserNote
url = 'gym:admin_note:edit'
pk = 1
user_success = (
'trainer1',
'trainer2',
'trainer3',
)
user_fail = (
'member1',
'manager1',
'manager2',
'trainer4',
'general_manager1',
'general_manager2',
)
data = {'note': 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr'}
class DeleteAdminNoteTestCase(WgerDeleteTestCase):
"""
Tests deleting an admin note
"""
pk = 2
object_class = AdminUserNote
url = 'gym:admin_note:delete'
user_success = (
'trainer1',
'trainer2',
'trainer3',
)
user_fail = (
'member1',
'manager1',
'manager2',
'trainer4',
'general_manager1',
'general_manager2',
)
delete_testcase_add_methods(DeleteAdminNoteTestCase)
| 2,839 | Python | .py | 105 | 21.428571 | 78 | 0.643488 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,653 | test_generator.py | wger-project_wger/wger/gym/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.gym.models import Gym
class GymGeneratorTestCase(WgerTestCase):
def test_generator(self):
# Arrange
Gym.objects.all().delete()
# Act
call_command('dummy-generator-gyms', '--nr-entries', 10)
# Assert
self.assertEqual(Gym.objects.count(), 10)
| 1,067 | Python | .py | 26 | 37.807692 | 78 | 0.758454 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,654 | test_admin_config.py | wger-project_wger/wger/gym/tests/test_admin_config.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
# wger
from wger.core.tests.base_testcase import WgerEditTestCase
from wger.gym.models import GymAdminConfig
class EditConfigTestCase(WgerEditTestCase):
"""
Tests editing an admin config
"""
object_class = GymAdminConfig
url = 'gym:admin_config:edit'
pk = 1
user_success = 'admin'
user_fail = (
'member1',
'manager1',
'manager2',
'trainer4',
'general_manager1',
'general_manager2',
)
data = {'overview_inactive': False}
| 1,150 | Python | .py | 33 | 31.060606 | 78 | 0.72956 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,655 | test_config.py | wger-project_wger/wger/gym/tests/test_config.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/>.
# wger
from wger.core.tests.base_testcase import WgerEditTestCase
from wger.gym.models import GymConfig
class EditGymConfigTestCase(WgerEditTestCase):
"""
Test editing a gym configuration
"""
pk = 1
object_class = GymConfig
url = 'gym:config:edit'
data = {'weeks_inactive': 10, 'show_name': True}
user_success = (
'admin',
'manager1',
'manager2',
)
user_fail = (
'member1',
'general_manager1',
'trainer1',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
| 1,298 | Python | .py | 39 | 29 | 78 | 0.699602 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,656 | test_export.py | wger-project_wger/wger/gym/tests/test_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 datetime
# Django
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.gym.models import Gym
class GymMembersCsvExportTestCase(WgerTestCase):
"""
Test case for the CSV export of gym members
"""
def export_csv(self, fail=True):
"""
Helper function to test the CSV export
"""
response = self.client.get(reverse('gym:export:users', kwargs={'gym_pk': 1}))
gym = Gym.objects.get(pk=1)
if fail:
self.assertIn(response.status_code, (403, 302))
else:
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'text/csv')
today = datetime.date.today()
filename = 'User-data-gym-{gym}-{t.year}-{t.month:02d}-{t.day:02d}.csv'.format(
t=today, gym=gym.id
)
self.assertEqual(response['Content-Disposition'], f'attachment; filename={filename}')
self.assertGreaterEqual(len(response.content), 1000)
self.assertLessEqual(len(response.content), 1300)
def test_export_csv_authorized(self):
"""
Test the CSV export by authorized users
"""
for username in ('manager1', 'manager2', 'general_manager1'):
self.user_login(username)
self.export_csv(fail=False)
def test_export_csv_unauthorized(self):
"""
Test the CSV export by unauthorized users
"""
for username in (
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
):
self.user_login(username)
self.export_csv(fail=True)
def test_export_csv_logged_out(self):
"""
Test the CSV export by a logged out user
"""
self.user_logout()
self.export_csv(fail=True)
| 2,642 | Python | .py | 71 | 29.492958 | 97 | 0.637608 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,657 | test_contracts.py | wger-project_wger/wger/gym/tests/test_contracts.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 (
WgerAccessTestCase,
WgerAddTestCase,
WgerEditTestCase,
)
from wger.gym.models import Contract
class AddContractTestCase(WgerAddTestCase):
"""
Tests creating a new contract
"""
object_class = Contract
url = reverse('gym:contract:add', kwargs={'user_pk': 14})
data = {'amount': 30, 'payment': '2'}
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
class AccessContractTestCase(WgerAccessTestCase):
"""
Test accessing the detail page of a contract
"""
url = reverse('gym:contract:view', kwargs={'pk': 1})
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
class AccessContractOverviewTestCase(WgerAccessTestCase):
"""
Test accessing the contract list page
"""
url = reverse('gym:contract:list', kwargs={'user_pk': 4})
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
class EditContractTestCase(WgerEditTestCase):
"""
Tests editing a contract
"""
pk = 1
object_class = Contract
url = 'gym:contract:edit'
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
data = {
'note': 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr',
'amount': 35,
'payment': '5',
}
| 2,783 | Python | .py | 103 | 21.106796 | 78 | 0.615904 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,658 | test_user_documents.py | wger-project_wger/wger/gym/tests/test_user_documents.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 (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
delete_testcase_add_methods,
)
from wger.gym.models import UserDocument
class UserDocumentOverviewTest(WgerAccessTestCase):
"""
Tests accessing the user document overview page
"""
url = reverse('gym:document:list', kwargs={'user_pk': 14})
anonymous_fail = True
user_success = (
'trainer1',
'trainer2',
'trainer3',
)
user_fail = (
'admin',
'member1',
'member2',
'trainer4',
'manager3',
'general_manager1',
)
class AddDocumentTestCase(WgerAddTestCase):
"""
Tests uploading a new user document
"""
object_class = UserDocument
url = reverse('gym:document:add', kwargs={'user_pk': 14})
fileupload = ['document', 'wger/gym/tests/Wurzelpetersilie.pdf']
data = {'name': 'Petersilie'}
data_ignore = ['document']
user_success = (
'trainer1',
'trainer2',
'trainer3',
)
user_fail = (
'member1',
'member2',
'trainer4',
'manager3',
'general_manager1',
)
class EditDocumentTestCase(WgerEditTestCase):
"""
Tests editing a user document
"""
pk = 2
object_class = UserDocument
url = 'gym:document:edit'
data = {'name': 'Petersilie'}
user_success = (
'trainer1',
'trainer2',
'trainer3',
)
user_fail = (
'member1',
'member2',
'trainer4',
'manager3',
'general_manager1',
)
class DeleteDocumentTestCase(WgerDeleteTestCase):
"""
Tests deleting a user document
"""
pk = 1
object_class = UserDocument
url = 'gym:document:delete'
user_success = (
'admin',
'trainer1',
'trainer2',
'trainer3',
)
user_fail = (
'member1',
'member2',
'trainer4',
'manager3',
'general_manager1',
)
delete_testcase_add_methods(DeleteDocumentTestCase)
| 2,784 | Python | .py | 105 | 20.980952 | 78 | 0.641006 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,659 | gym-user-config.py | wger-project_wger/wger/gym/management/commands/gym-user-config.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
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand
# wger
from wger.gym.helpers import is_any_gym_admin
from wger.gym.models import (
GymAdminConfig,
GymUserConfig,
)
class Command(BaseCommand):
"""
Check that all gym trainers and users have configurations
"""
help = 'Check that all gym trainers and users have configurations'
def handle(self, **options):
"""
Process all users
"""
for user in User.objects.all():
if is_any_gym_admin(user):
try:
user.gymadminconfig
except ObjectDoesNotExist:
config = GymAdminConfig()
config.user = user
config.gym = user.userprofile.gym
config.save()
else:
if user.userprofile.gym_id:
try:
user.gymuserconfig
except ObjectDoesNotExist:
config = GymUserConfig()
config.user = user
config.gym = user.userprofile.gym
config.save()
| 1,911 | Python | .py | 50 | 29.22 | 78 | 0.637885 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,660 | dummy-generator-gyms.py | wger-project_wger/wger/gym/management/commands/dummy-generator-gyms.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.management.base import BaseCommand
# Third Party
from faker import Faker
from faker.providers import DynamicProvider
# wger
from wger.gym.models import Gym
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Dummy generator for gyms
"""
help = 'Dummy generator for gyms'
names_first = [
'1st',
'Body',
'Energy',
'Granite',
'Hardcore',
'Intense',
'Iron',
'Muscle',
'Peak',
'Power',
'Pumping',
'Results',
'Top',
]
names_second = [
'Academy',
'Barbells',
'Body',
'Centre',
'Dumbbells',
'Factory',
'Fitness',
'Force',
'Gym',
'Iron',
'Pit',
'Team',
'Workout',
]
def add_arguments(self, parser):
parser.add_argument(
'--nr-entries',
action='store',
default=10,
dest='number_gyms',
type=int,
help='The number of gyms to generate (default: 10)',
)
def handle(self, **options):
gym_names_1 = DynamicProvider(
provider_name='gym_names',
elements=self.names_first,
)
gym_names_2 = DynamicProvider(
provider_name='gym_names2',
elements=self.names_second,
)
faker = Faker()
faker.add_provider(gym_names_1)
faker.add_provider(gym_names_2)
self.stdout.write(f"** Generating {options['number_gyms']} gyms")
gym_list = []
for i in range(options['number_gyms']):
found = False
# We don't want names like "Iron Iron"
while not found:
part1 = faker.gym_names()
part2 = faker.gym_names2()
if part1 != part2:
found = True
name = f'{part1} {part2}'
gym = Gym()
gym.name = name
gym_list.append(gym)
self.stdout.write(f' - {gym.name}')
# Bulk-create the entries
Gym.objects.bulk_create(gym_list)
| 2,854 | Python | .py | 96 | 21.802083 | 78 | 0.580197 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,661 | inactive-members.py | wger-project_wger/wger/gym/management/commands/inactive-members.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.core import mail
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.utils import translation
from django.utils.translation import gettext as _
# wger
from wger.gym.helpers import is_any_gym_admin
from wger.gym.models import Gym
class Command(BaseCommand):
"""
Sends overviews of inactive users to gym trainers
"""
help = 'Send out emails to trainers with users that have not shown recent activity'
def handle(self, **options):
"""
Process gyms and send emails
"""
today = datetime.date.today()
for gym in Gym.objects.all():
if int(options['verbosity']) >= 2:
self.stdout.write(f"* Processing gym '{gym}' ")
user_list = []
trainer_list = []
user_list_no_activity = []
weeks = gym.config.weeks_inactive
if not weeks:
if int(options['verbosity']) >= 2:
self.stdout.write(' Reminders deactivatd, skipping')
continue
for profile in gym.userprofile_set.all():
user = profile.user
# check if the account was deactivated (user can't login)
if not user.is_active:
continue
# add to trainer list that will be notified
if user.has_perm('gym.gym_trainer'):
trainer_list.append(user)
# Check appropriate permissions
if is_any_gym_admin(user):
continue
# Check user preferences
if not user.gymuserconfig.include_inactive:
continue
last_activity = user.usercache.last_activity
if not last_activity:
user_list_no_activity.append({'user': user, 'last_activity': last_activity})
elif today - last_activity > datetime.timedelta(weeks=weeks):
user_list.append({'user': user, 'last_activity': last_activity})
if user_list or user_list_no_activity:
for trainer in trainer_list:
# Profile might not have email
if not trainer.email:
continue
# Check trainer preferences
if not trainer.gymadminconfig.overview_inactive:
continue
translation.activate(trainer.userprofile.notification_language.short_name)
subject = _('Reminder of inactive members')
context = {
'weeks': weeks,
'user_list': user_list,
'user_list_no_activity': user_list_no_activity,
}
message = render_to_string('gym/email_inactive_members.html', context)
mail.send_mail(
subject,
message,
settings.WGER_SETTINGS['EMAIL_FROM'],
[trainer.email],
fail_silently=True,
)
| 3,933 | Python | .py | 88 | 31.965909 | 96 | 0.583268 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,662 | signals.py | wger-project_wger/wger/exercises/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
# Standard Library
import pathlib
# Django
from django.db.models.signals import (
post_delete,
pre_delete,
pre_save,
)
from django.dispatch import receiver
# Third Party
from easy_thumbnails.files import get_thumbnailer
from easy_thumbnails.signal_handlers import generate_aliases
from easy_thumbnails.signals import saved_file
# wger
from wger.exercises.models import (
DeletionLog,
Exercise,
ExerciseImage,
ExerciseVideo,
)
@receiver(post_delete, sender=ExerciseImage)
def delete_exercise_image_on_delete(sender, instance, **kwargs):
"""
Delete the image, along with its thumbnails, from the disk
"""
thumbnailer = get_thumbnailer(instance.image)
thumbnailer.delete_thumbnails()
instance.image.delete(save=False)
@receiver(pre_save, sender=ExerciseImage)
def delete_exercise_image_on_update(sender, instance, **kwargs):
"""
Delete the corresponding image from the filesystem when the ExerciseImage
object was edited
"""
if not instance.pk:
return False
try:
old_file = ExerciseImage.objects.get(pk=instance.pk).image
except ExerciseImage.DoesNotExist:
return False
new_file = instance.image
if not old_file == new_file:
thumbnailer = get_thumbnailer(instance.image)
thumbnailer.delete_thumbnails()
instance.image.delete(save=False)
# Generate thumbnails when uploading a new image
saved_file.connect(generate_aliases)
@receiver(post_delete, sender=ExerciseVideo)
def auto_delete_video_on_delete(sender, instance: ExerciseVideo, **kwargs):
"""
Deletes file from filesystem when corresponding ExerciseVideo object is deleted
"""
if instance.video:
path = pathlib.Path(instance.video.path)
if path.exists():
path.unlink()
@receiver(pre_save, sender=ExerciseVideo)
def delete_exercise_video_on_update(sender, instance: ExerciseVideo, **kwargs):
"""
Deletes file from filesystem when corresponding ExerciseVideo object was edited
"""
if not instance.pk:
return False
try:
old_file = ExerciseVideo.objects.get(pk=instance.pk).video
except ExerciseVideo.DoesNotExist:
return False
new_file = instance.video
if old_file != new_file:
path = pathlib.Path(old_file.path)
if path.is_file():
path.unlink()
# Deletion log for exercise bases is handled in the model
# @receiver(pre_delete, sender=ExerciseBase)
# def add_deletion_log_base(sender, instance: ExerciseBase, **kwargs):
# pass
@receiver(pre_delete, sender=Exercise)
def add_deletion_log_translation(sender, instance: Exercise, **kwargs):
log = DeletionLog(
model_type=DeletionLog.MODEL_TRANSLATION,
uuid=instance.uuid,
comment=instance.name,
)
log.save()
@receiver(pre_delete, sender=ExerciseImage)
def add_deletion_log_image(sender, instance: ExerciseImage, **kwargs):
log = DeletionLog(
model_type=DeletionLog.MODEL_IMAGE,
uuid=instance.uuid,
)
log.save()
@receiver(pre_delete, sender=ExerciseVideo)
def add_deletion_log_video(sender, instance: ExerciseVideo, **kwargs):
log = DeletionLog(
model_type=DeletionLog.MODEL_VIDEO,
uuid=instance.uuid,
)
log.save()
| 3,961 | Python | .py | 112 | 30.9375 | 83 | 0.733316 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,663 | sync.py | wger-project_wger/wger/exercises/sync.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 os
# Django
from django.conf import settings
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
# Third Party
import requests
# wger
from wger.core.api.endpoints import (
LANGUAGE_ENDPOINT,
LICENSE_ENDPOINT,
)
from wger.core.models import (
Language,
License,
)
from wger.exercises.api.endpoints import (
CATEGORY_ENDPOINT,
DELETION_LOG_ENDPOINT,
EQUIPMENT_ENDPOINT,
EXERCISE_ENDPOINT,
IMAGE_ENDPOINT,
MUSCLE_ENDPOINT,
VIDEO_ENDPOINT,
)
from wger.exercises.models import (
Alias,
DeletionLog,
Equipment,
Exercise,
ExerciseBase,
ExerciseCategory,
ExerciseComment,
ExerciseImage,
ExerciseVideo,
Muscle,
)
from wger.manager.models import (
Setting,
WorkoutLog,
)
from wger.utils.requests import (
get_all_paginated,
get_paginated,
wger_headers,
)
from wger.utils.url import make_uri
def sync_exercises(
print_fn,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
"""Synchronize the exercises from the remote server"""
print_fn('*** Synchronizing exercises...')
url = make_uri(EXERCISE_ENDPOINT, server_url=remote_url, query={'limit': 100})
for data in get_paginated(url, headers=wger_headers()):
uuid = data['uuid']
created = data['created']
license_id = data['license']['id']
category_id = data['category']['id']
license_author = data['license_author']
equipment = [Equipment.objects.get(pk=i['id']) for i in data['equipment']]
muscles = [Muscle.objects.get(pk=i['id']) for i in data['muscles']]
muscles_sec = [Muscle.objects.get(pk=i['id']) for i in data['muscles_secondary']]
base, base_created = ExerciseBase.objects.update_or_create(
uuid=uuid,
defaults={'category_id': category_id, 'created': created},
)
print_fn(f"{'created' if base_created else 'updated'} exercise {uuid}")
base.muscles.set(muscles)
base.muscles_secondary.set(muscles_sec)
base.equipment.set(equipment)
base.save()
for translation_data in data['exercises']:
trans_uuid = translation_data['uuid']
name = translation_data['name']
description = translation_data['description']
language_id = translation_data['language']
translation, translation_created = Exercise.objects.update_or_create(
uuid=trans_uuid,
defaults={
'exercise_base': base,
'name': name,
'description': description,
'license_id': license_id,
'license_author': license_author,
'language_id': language_id,
},
)
out = (
f"- {'created' if translation_created else 'updated'} translation "
f"{translation.language.short_name} {trans_uuid} - {name}"
)
print_fn(out)
# TODO: currently (2024-01-06) we always delete all the comments and the aliases
# when synchronizing the data, even though we could identify them via the
# UUID. However, the UUID created when running the database migrations will
# be unique as well, so we will never update. We need to wait a while till
# most local instances have run the sync script so that the UUID is the same
# locally as well.
#
# -> remove the `.delete()` after the 2024-06-01
ExerciseComment.objects.filter(exercise=translation).delete()
for note in translation_data['notes']:
ExerciseComment.objects.update_or_create(
uuid=note['uuid'],
defaults={
'uuid': note['uuid'],
'exercise': translation,
'comment': note['comment'],
},
)
Alias.objects.filter(exercise=translation).delete()
for alias in translation_data['aliases']:
Alias.objects.update_or_create(
uuid=alias['uuid'],
defaults={
'uuid': alias['uuid'],
'exercise': translation,
'alias': alias['alias'],
},
)
print_fn('')
print_fn(style_fn('done!\n'))
def sync_languages(
print_fn,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
"""Synchronize the languages from the remote server"""
print_fn('*** Synchronizing languages...')
headers = wger_headers()
url = make_uri(LANGUAGE_ENDPOINT, server_url=remote_url)
for data in get_all_paginated(url, headers=headers):
short_name = data['short_name']
full_name = data['full_name']
full_name_en = data['full_name_en']
language, created = Language.objects.update_or_create(
short_name=short_name,
defaults={'full_name': full_name, 'full_name_en': full_name_en},
)
if created:
print_fn(f'Saved new language {full_name}')
print_fn(style_fn('done!\n'))
def sync_licenses(
print_fn,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
"""Synchronize the licenses from the remote server"""
print_fn('*** Synchronizing licenses...')
url = make_uri(LICENSE_ENDPOINT, server_url=remote_url)
for data in get_all_paginated(url, headers=wger_headers()):
short_name = data['short_name']
full_name = data['full_name']
license_url = data['url']
language, created = License.objects.update_or_create(
short_name=short_name,
defaults={'full_name': full_name, 'url': license_url},
)
if created:
print_fn(f'Saved new license {full_name}')
print_fn(style_fn('done!\n'))
def sync_categories(
print_fn,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
"""Synchronize the categories from the remote server"""
print_fn('*** Synchronizing categories...')
url = make_uri(CATEGORY_ENDPOINT, server_url=remote_url)
for data in get_all_paginated(url, headers=wger_headers()):
category_id = data['id']
category_name = data['name']
category, created = ExerciseCategory.objects.update_or_create(
pk=category_id,
defaults={'name': category_name},
)
if created:
print_fn(f'Saved new category {category_name}')
print_fn(style_fn('done!\n'))
def sync_muscles(
print_fn,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
"""Synchronize the muscles from the remote server"""
print_fn('*** Synchronizing muscles...')
url = make_uri(MUSCLE_ENDPOINT, server_url=remote_url)
for data in get_all_paginated(url, headers=wger_headers()):
muscle_id = data['id']
muscle_name = data['name']
muscle_is_front = data['is_front']
muscle_name_en = data['name_en']
muscle_url_main = data['image_url_main']
muscle_url_secondary = data['image_url_secondary']
muscle, created = Muscle.objects.update_or_create(
pk=muscle_id,
defaults={
'name': muscle_name,
'name_en': muscle_name_en,
'is_front': muscle_is_front,
},
)
if created:
print_fn(f'Saved new muscle {muscle_name}. Save the corresponding images manually:')
print_fn(f' - {remote_url}{muscle_url_main}')
print_fn(f' - {remote_url}{muscle_url_secondary}')
print_fn(style_fn('done!\n'))
def sync_equipment(
print_fn,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
"""Synchronize the equipment from the remote server"""
print_fn('*** Synchronizing equipment...')
url = make_uri(EQUIPMENT_ENDPOINT, server_url=remote_url)
for data in get_all_paginated(url, headers=wger_headers()):
equipment_id = data['id']
equipment_name = data['name']
equipment, created = Equipment.objects.update_or_create(
pk=equipment_id,
defaults={'name': equipment_name},
)
if created:
print_fn(f'Saved new equipment {equipment_name}')
print_fn(style_fn('done!\n'))
def handle_deleted_entries(
print_fn=None,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
if not print_fn:
def print_fn(_):
return None
"""Delete exercises that were removed on the server"""
print_fn('*** Deleting exercise data that was removed on the server...')
url = make_uri(DELETION_LOG_ENDPOINT, server_url=remote_url, query={'limit': 100})
for data in get_paginated(url, headers=wger_headers()):
uuid = data['uuid']
replaced_by_uuid = data['replaced_by']
model_type = data['model_type']
if model_type == DeletionLog.MODEL_BASE:
obj_replaced = None
nr_settings = None
nr_logs = None
try:
obj_replaced = ExerciseBase.objects.get(uuid=replaced_by_uuid)
except ExerciseBase.DoesNotExist:
pass
try:
obj = ExerciseBase.objects.get(uuid=uuid)
# Replace exercise in workouts and logs
if obj_replaced:
nr_settings = Setting.objects.filter(exercise_base=obj).update(
exercise_base=obj_replaced
)
nr_logs = WorkoutLog.objects.filter(exercise_base=obj).update(
exercise_base=obj_replaced
)
obj.delete()
print_fn(f'Deleted exercise base {uuid}')
if nr_settings:
print_fn(f'- replaced {nr_settings} time(s) in workouts by {replaced_by_uuid}')
if nr_logs:
print_fn(f'- replaced {nr_logs} time(s) in workout logs by {replaced_by_uuid}')
except ExerciseBase.DoesNotExist:
pass
elif model_type == DeletionLog.MODEL_TRANSLATION:
try:
obj = Exercise.objects.get(uuid=uuid)
obj.delete()
print_fn(f"Deleted translation {uuid} ({data['comment']})")
except Exercise.DoesNotExist:
pass
elif model_type == DeletionLog.MODEL_IMAGE:
try:
obj = ExerciseImage.objects.get(uuid=uuid)
obj.delete()
print_fn(f'Deleted image {uuid}')
except ExerciseImage.DoesNotExist:
pass
elif model_type == DeletionLog.MODEL_VIDEO:
try:
obj = ExerciseVideo.objects.get(uuid=uuid)
obj.delete()
print_fn(f'Deleted video {uuid}')
except ExerciseVideo.DoesNotExist:
pass
def download_exercise_images(
print_fn,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
headers = wger_headers()
url = make_uri(IMAGE_ENDPOINT, server_url=remote_url)
print_fn('*** Processing images ***')
# 2023-04-21: Delete all images that have no associated image files
#
# This is a temporary fix necessary because we had a bug in this sync
# script that downloaded the image files and created image entries in the
# database, but didn't connect them. This deletes the image entries so
# that they can be re-downloaded (the dangling files are still there, though).
deleted, rows = ExerciseImage.objects.filter(image='').delete()
if deleted:
print_fn(f'Deleted {deleted} images without associated image files')
for image_data in get_paginated(url, headers=headers):
image_uuid = image_data['uuid']
print_fn(f'Processing image {image_uuid}')
try:
exercise = ExerciseBase.objects.get(uuid=image_data['exercise_base_uuid'])
except ExerciseBase.DoesNotExist:
print_fn(' Remote exercise base not found in local DB, skipping...')
continue
try:
ExerciseImage.objects.get(uuid=image_uuid)
print_fn(' Image already present locally, skipping...')
continue
except ExerciseImage.DoesNotExist:
print_fn(' Image not found in local DB, creating now...')
retrieved_image = requests.get(image_data['image'], headers=headers)
image = ExerciseImage.from_json(exercise, retrieved_image, image_data)
print_fn(style_fn(' successfully saved'))
def download_exercise_videos(
print_fn,
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
headers = wger_headers()
url = make_uri(VIDEO_ENDPOINT, server_url=remote_url)
print_fn('*** Processing videos ***')
for video_data in get_paginated(url, headers=headers):
video_uuid = video_data['uuid']
print_fn(f'Processing video {video_uuid}')
try:
exercise = ExerciseBase.objects.get(uuid=video_data['exercise_base_uuid'])
except ExerciseBase.DoesNotExist:
print_fn(' Remote exercise base not found in local DB, skipping...')
continue
try:
ExerciseVideo.objects.get(uuid=video_uuid)
print_fn(' Video already present locally, skipping...')
continue
except ExerciseVideo.DoesNotExist:
print_fn(' Video not found in local DB, creating now...')
video = ExerciseVideo()
video.exercise_base = exercise
video.uuid = video_uuid
video.is_main = video_data['is_main']
video.license_id = video_data['license']
video.license_author = video_data['license_author']
video.size = video_data['size']
video.width = video_data['width']
video.height = video_data['height']
video.codec = video_data['codec']
video.codec_long = video_data['codec_long']
video.duration = video_data['duration']
# Save the downloaded video
# http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
retrieved_video = requests.get(video_data['video'], headers=headers)
# Temporary files on Windows don't support the delete attribute
if os.name == 'nt':
img_temp = NamedTemporaryFile()
else:
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(retrieved_video.content)
img_temp.flush()
video.video.save(
os.path.basename(os.path.basename(video_data['video'])),
File(img_temp),
)
video.save()
print_fn(style_fn(' saved successfully'))
| 15,880 | Python | .py | 387 | 31.516796 | 99 | 0.60689 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,664 | urls.py | wger-project_wger/wger/exercises/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,
re_path,
)
# wger
from wger.core.views.react import ReactView
from wger.exercises.views import (
categories,
equipment,
exercises,
history,
muscles,
)
# sub patterns for history
patterns_history = [
path('admin-control', history.control, name='overview'),
path(
'admin-control/revert/<int:history_pk>/<int:content_type_id>',
history.history_revert,
name='revert',
),
]
# sub patterns for muscles
patterns_muscle = [
path(
'admin-overview/',
muscles.MuscleAdminListView.as_view(),
name='admin-list',
),
path(
'add/',
muscles.MuscleAddView.as_view(),
name='add',
),
path(
'<int:pk>/edit/',
muscles.MuscleUpdateView.as_view(),
name='edit',
),
path(
'<int:pk>/delete/',
muscles.MuscleDeleteView.as_view(),
name='delete',
),
]
# sub patterns for categories
patterns_category = [
path(
'list',
categories.ExerciseCategoryListView.as_view(),
name='list',
),
path(
'<int:pk>/edit/',
categories.ExerciseCategoryUpdateView.as_view(),
name='edit',
),
path(
'add/',
categories.ExerciseCategoryAddView.as_view(),
name='add',
),
path(
'<int:pk>/delete/',
categories.ExerciseCategoryDeleteView.as_view(),
name='delete',
),
]
# sub patterns for equipment
patterns_equipment = [
path(
'list',
equipment.EquipmentListView.as_view(),
name='list',
),
path(
'add',
equipment.EquipmentAddView.as_view(),
name='add',
),
path(
'<int:pk>/edit',
equipment.EquipmentEditView.as_view(),
name='edit',
),
path(
'<int:pk>/delete',
equipment.EquipmentDeleteView.as_view(),
name='delete',
),
]
# sub patterns for exercises
patterns_exercise = [
path(
'overview/',
ReactView.as_view(div_id='react-exercise-overview'),
name='overview',
),
path(
'<int:id>/view/',
exercises.view,
name='view',
),
re_path(
r'^(?P<id>\d+)/view/(?P<slug>[-\w]*)/?$',
exercises.view,
name='view',
),
path(
'<int:pk>/view-base',
ReactView.as_view(div_id='react-exercise-overview'),
name='view-base',
),
path(
'<int:pk>/view-base/<slug:slug>',
ReactView.as_view(div_id='react-exercise-detail'),
name='view-base',
),
path(
'contribute',
ReactView.as_view(div_id='react-exercise-contribute'),
name='contribute',
),
]
urlpatterns = [
path('muscle/', include((patterns_muscle, 'muscle'), namespace='muscle')),
path('category/', include((patterns_category, 'category'), namespace='category')),
path('equipment/', include((patterns_equipment, 'equipment'), namespace='equipment')),
path('history/', include((patterns_history, 'history'), namespace='history')),
path('', include((patterns_exercise, 'exercise'), namespace='exercise')),
]
| 3,958 | Python | .py | 148 | 21.216216 | 90 | 0.618947 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,665 | tasks.py | wger-project_wger/wger/exercises/tasks.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
import random
# Django
from django.conf import settings
# Third Party
from celery.schedules import crontab
# wger
from wger.celery_configuration import app
from wger.exercises.sync import (
download_exercise_images,
download_exercise_videos,
handle_deleted_entries,
sync_categories,
sync_equipment,
sync_exercises,
sync_languages,
sync_licenses,
sync_muscles,
)
logger = logging.getLogger(__name__)
@app.task
def sync_exercises_task():
"""
Fetches the current exercises from the default wger instance
"""
sync_languages(logger.info)
sync_licenses(logger.info)
sync_categories(logger.info)
sync_muscles(logger.info)
sync_equipment(logger.info)
sync_exercises(logger.info)
handle_deleted_entries(logger.info)
@app.task
def sync_images_task():
"""
Fetches the exercise images from the default wger instance
"""
download_exercise_images(logger.info)
@app.task
def sync_videos_task():
"""
Fetches the exercise videos from the default wger instance
"""
download_exercise_videos(logger.info)
@app.on_after_finalize.connect
def setup_periodic_tasks(sender, **kwargs):
if settings.WGER_SETTINGS['SYNC_EXERCISES_CELERY']:
sender.add_periodic_task(
crontab(
hour=str(random.randint(0, 23)),
minute=str(random.randint(0, 59)),
day_of_week=str(random.randint(0, 6)),
),
sync_exercises_task.s(),
name='Sync exercises',
)
if settings.WGER_SETTINGS['SYNC_EXERCISE_IMAGES_CELERY']:
sender.add_periodic_task(
crontab(
hour=str(random.randint(0, 23)),
minute=str(random.randint(0, 59)),
day_of_week=str(random.randint(0, 6)),
),
sync_images_task.s(),
name='Sync exercise images',
)
if settings.WGER_SETTINGS['SYNC_EXERCISE_VIDEOS_CELERY']:
sender.add_periodic_task(
crontab(
hour=str(random.randint(0, 23)),
minute=str(random.randint(0, 59)),
day_of_week=str(random.randint(0, 6)),
),
sync_videos_task.s(),
name='Sync exercise videos',
)
| 2,964 | Python | .py | 90 | 26.688889 | 78 | 0.668999 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,666 | apps.py | wger-project_wger/wger/exercises/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 ExerciseConfig(AppConfig):
name = 'wger.exercises'
verbose_name = 'Exercise'
def ready(self):
import wger.exercises.signals
from actstream import registry
registry.register(self.get_model('Alias'))
registry.register(self.get_model('Exercise'))
registry.register(self.get_model('ExerciseBase'))
registry.register(self.get_model('ExerciseComment'))
registry.register(self.get_model('ExerciseImage'))
registry.register(self.get_model('ExerciseVideo'))
| 1,244 | Python | .py | 28 | 40.464286 | 78 | 0.748553 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,667 | sitemap.py | wger-project_wger/wger/exercises/sitemap.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.contrib.sitemaps import Sitemap
# wger
from wger.exercises.models import Exercise
class ExercisesSitemap(Sitemap):
changefreq = 'monthly'
priority = 0.5
def items(self):
return Exercise.objects.all()
def lastmod(self, obj):
return obj.last_update
| 970 | Python | .py | 25 | 36.24 | 78 | 0.766525 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,668 | __init__.py | wger-project_wger/wger/exercises/__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.exercises.apps.ExerciseConfig'
| 859 | Python | .py | 19 | 44 | 78 | 0.778708 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,669 | forms.py | wger-project_wger/wger/exercises/forms.py | # -*- coding: utf-8 -*-
# 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 import forms
# wger
from wger.exercises.models import (
ExerciseComment,
ExerciseImage,
ExerciseVideo,
)
class ExerciseImageForm(forms.ModelForm):
class Meta:
model = ExerciseImage
fields = (
'image',
'is_main',
'license',
'license_author',
'style',
)
class ExerciseVideoForm(forms.ModelForm):
class Meta:
model = ExerciseVideo
fields = (
'video',
'is_main',
'license_author',
)
class CommentForm(forms.ModelForm):
class Meta:
model = ExerciseComment
exclude = ('exercise',)
| 1,337 | Python | .py | 44 | 25 | 77 | 0.676012 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,670 | managers.py | wger-project_wger/wger/exercises/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.db import models
from django.db.models import Count
class ExerciseBaseManagerTranslations(models.Manager):
"""Returns all exercise bases that have at least one translation"""
def get_queryset(self):
return super().get_queryset().annotate(count=Count('exercises')).filter(count__gt=0)
class ExerciseBaseManagerNoTranslations(models.Manager):
"""Returns all exercise bases that have no translations"""
def get_queryset(self):
return super().get_queryset().annotate(count=Count('exercises')).filter(count=0)
class ExerciseBaseManagerAll(models.Manager):
"""Returns all exercise bases"""
pass
| 1,462 | Python | .py | 29 | 47.689655 | 92 | 0.763176 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,671 | variation.py | wger-project_wger/wger/exercises/models/variation.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
class Variation(models.Model):
"""
Variation ids for exercises
"""
def __str__(self):
"""
Return a more human-readable representation
"""
return f'Variation {self.id}'
def get_owner_object(self):
"""
Variation has no owner information
"""
return False
| 1,181 | Python | .py | 31 | 34.225806 | 79 | 0.710917 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,672 | category.py | wger-project_wger/wger/exercises/models/category.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 _
class ExerciseCategory(models.Model):
"""
Model for an exercise category
"""
name = models.CharField(
max_length=100,
verbose_name=_('Name'),
)
# Metaclass to set some other properties
class Meta:
verbose_name_plural = _('Exercise Categories')
ordering = [
'name',
]
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def get_owner_object(self):
"""
Category has no owner information
"""
return False
| 1,492 | Python | .py | 42 | 30.738095 | 79 | 0.688843 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,673 | equipment.py | wger-project_wger/wger/exercises/models/equipment.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 _
class Equipment(models.Model):
"""
Equipment used or needed by an exercise
"""
name = models.CharField(
max_length=50,
verbose_name=_('Name'),
)
class Meta:
"""
Set default ordering
"""
ordering = [
'name',
]
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def get_owner_object(self):
"""
Equipment has no owner information
"""
return False
| 1,448 | Python | .py | 43 | 28.674419 | 79 | 0.675734 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,674 | muscle.py | wger-project_wger/wger/exercises/models/muscle.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.templatetags.static import static
from django.utils.translation import gettext_lazy as _
logger = logging.getLogger(__name__)
class Muscle(models.Model):
"""
Muscle an exercise works out
"""
name = models.CharField(
max_length=50,
verbose_name=_('Name'),
help_text=_('In latin, e.g. "Pectoralis major"'),
)
# Whether to use the front or the back image for background
is_front = models.BooleanField(default=1)
# The name of the muscle in layman's terms
name_en = models.CharField(
max_length=50,
default='',
verbose_name=_('Alternative name'),
help_text=_('A more basic name for the muscle'),
)
# Metaclass to set some other properties
class Meta:
ordering = [
'name',
]
# Image to use when displaying this as a main muscle in an exercise
@property
def image_url_main(self):
return static(f'images/muscles/main/muscle-{self.id}.svg')
# Image to use when displaying this as a secondary muscle in an exercise
@property
def image_url_secondary(self):
return static(f'images/muscles/secondary/muscle-{self.id}.svg')
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def get_owner_object(self):
"""
Muscle has no owner information
"""
return False
| 2,324 | Python | .py | 63 | 31.793651 | 79 | 0.688028 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,675 | exercise_alias.py | wger-project_wger/wger/exercises/models/exercise_alias.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 uuid
# Django
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils.translation import gettext_lazy as _
# Third Party
from simple_history.models import HistoricalRecords
# wger
from wger.utils.cache import (
reset_exercise_api_cache,
reset_workout_canonical_form,
)
# Local
from .exercise import Exercise
class Alias(models.Model):
"""
Model for an exercise (name)alias
"""
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True,
verbose_name='UUID',
)
"""Globally unique ID, to identify the alias across installations"""
exercise = models.ForeignKey(
Exercise,
verbose_name=_('Exercise'),
on_delete=models.CASCADE,
)
alias = models.CharField(
max_length=200,
verbose_name=_('Alias for an exercise'),
)
history = HistoricalRecords()
"""Edit history"""
class Meta:
indexes = (GinIndex(fields=['alias']),)
def __str__(self):
"""
Return a more human-readable representation
"""
return self.alias
def save(self, *args, **kwargs):
"""
Reset cached workouts
"""
# Api cache
reset_exercise_api_cache(self.exercise.exercise_base.uuid)
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Reset cached workouts
"""
for setting in self.exercise.exercise_base.setting_set.all():
reset_workout_canonical_form(setting.set.exerciseday.training.pk)
# Api cache
reset_exercise_api_cache(self.exercise.exercise_base.uuid)
super().delete(*args, **kwargs)
def get_owner_object(self):
"""
Comment has no owner information
"""
return False
| 2,683 | Python | .py | 80 | 28.1 | 79 | 0.677632 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,676 | comment.py | wger-project_wger/wger/exercises/models/comment.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 uuid
# Django
from django.db import models
from django.utils.translation import gettext_lazy as _
# Third Party
from simple_history.models import HistoricalRecords
# wger
from wger.utils.cache import (
reset_exercise_api_cache,
reset_workout_canonical_form,
)
# Local
from .exercise import Exercise
class ExerciseComment(models.Model):
"""
Model for an exercise comment
"""
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True,
verbose_name='UUID',
)
"""Globally unique ID, to identify the comment across installations"""
exercise = models.ForeignKey(
Exercise,
verbose_name=_('Exercise'),
on_delete=models.CASCADE,
)
comment = models.CharField(
max_length=200,
verbose_name=_('Comment'),
help_text=_('A comment about how to correctly do this exercise.'),
)
history = HistoricalRecords()
"""Edit history"""
def __str__(self):
"""
Return a more human-readable representation
"""
return self.comment
def save(self, *args, **kwargs):
"""
Reset cached workouts
"""
for setting in self.exercise.exercise_base.setting_set.all():
reset_workout_canonical_form(setting.set.exerciseday.training_id)
# Api cache
reset_exercise_api_cache(self.exercise.exercise_base.uuid)
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Reset cached workouts
"""
for setting in self.exercise.exercise_base.setting_set.all():
reset_workout_canonical_form(setting.set.exerciseday.training.pk)
# Api cache
reset_exercise_api_cache(self.exercise.exercise_base.uuid)
super().delete(*args, **kwargs)
def get_owner_object(self):
"""
Comment has no owner information
"""
return False
| 2,787 | Python | .py | 80 | 29.2 | 79 | 0.679688 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,677 | __init__.py | wger-project_wger/wger/exercises/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 .base import ExerciseBase
from .category import ExerciseCategory
from .comment import ExerciseComment
from .deletion_log import DeletionLog
from .equipment import Equipment
from .exercise import Exercise
from .exercise_alias import Alias
from .image import ExerciseImage
from .muscle import Muscle
from .variation import Variation
from .video import ExerciseVideo
| 1,180 | Python | .py | 27 | 42.666667 | 79 | 0.798611 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,678 | base.py | wger-project_wger/wger/exercises/models/base.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
import uuid
from typing import (
List,
Optional,
)
# Django
from django.core.checks import Warning
from django.db import models
from django.db.models import Q
from django.urls import reverse
from django.utils.translation import (
get_language,
gettext_lazy as _,
)
# Third Party
from simple_history.models import HistoricalRecords
# wger
from wger.core.models import Language
from wger.exercises.managers import (
ExerciseBaseManagerAll,
ExerciseBaseManagerNoTranslations,
ExerciseBaseManagerTranslations,
)
from wger.utils.cache import reset_exercise_api_cache
from wger.utils.constants import ENGLISH_SHORT_NAME
from wger.utils.models import (
AbstractHistoryMixin,
AbstractLicenseModel,
collect_models_author_history,
)
# Local
from .category import ExerciseCategory
from .equipment import Equipment
from .muscle import Muscle
from .variation import Variation
class ExerciseBase(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
"""
Model for an exercise base
"""
objects = ExerciseBaseManagerAll()
no_translations = ExerciseBaseManagerNoTranslations()
translations = ExerciseBaseManagerTranslations()
"""
Custom Query Manager
"""
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True,
verbose_name='UUID',
)
"""Globally unique ID, to identify the base across installations"""
category = models.ForeignKey(
ExerciseCategory,
verbose_name=_('Category'),
on_delete=models.CASCADE,
)
muscles = models.ManyToManyField(
Muscle,
blank=True,
verbose_name=_('Primary muscles'),
)
"""Main muscles trained by the exercise"""
muscles_secondary = models.ManyToManyField(
Muscle,
verbose_name=_('Secondary muscles'),
related_name='secondary_muscles_base',
blank=True,
)
"""Secondary muscles trained by the exercise"""
equipment = models.ManyToManyField(
Equipment,
verbose_name=_('Equipment'),
blank=True,
)
"""Equipment needed by this exercise"""
variations = models.ForeignKey(
Variation,
verbose_name=_('Variations'),
on_delete=models.SET_NULL,
null=True,
blank=True,
)
"""Variations of this exercise"""
created = models.DateTimeField(
_('Date'),
auto_now_add=True,
)
"""The submission datetime"""
last_update = models.DateTimeField(
_('Date'),
auto_now=True,
)
"""Datetime of last modification"""
history = HistoricalRecords()
"""Edit history"""
def __str__(self):
"""
Return a more human-readable representation
"""
return f'base {self.uuid} ({self.get_translation()})'
def get_absolute_url(self):
"""
Returns the canonical URL to view an exercise
"""
return reverse('exercise:exercise:view-base', kwargs={'pk': self.id})
@classmethod
def check(cls, **kwargs):
errors = super().check(**kwargs)
no_translations = cls.no_translations.all().count()
if no_translations:
errors.append(
Warning(
'exercises without translations',
hint=f'There are {no_translations} exercises without translations, this will '
'cause problems! You can output or delete them with "python manage.py '
'exercises-health-check --help"',
id='wger.W002',
)
)
return errors
#
# Own methods
#
@property
def total_authors_history(self):
"""
All authors history related to the BaseExercise.
"""
collect_for_models = [
*self.exercises.all(),
*self.exercisevideo_set.all(),
*self.exerciseimage_set.all(),
]
return self.author_history.union(collect_models_author_history(collect_for_models))
@property
def last_update_global(self):
"""
The latest update datetime of all exercises, videos and images.
"""
return max(
self.last_update,
*[image.last_update for image in self.exerciseimage_set.all()],
*[video.last_update for video in self.exercisevideo_set.all()],
*[translation.last_update for translation in self.exercises.all()],
datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc),
)
@property
def main_image(self):
"""
Return the main image for the exercise or None if nothing is found
"""
return self.exerciseimage_set.all().filter(is_main=True).first()
@property
def languages(self) -> List[Language]:
"""
Returns the languages from the exercises that use this base
"""
return [exercise.language for exercise in self.exercises.all()]
@property
def base_variations(self):
"""
Returns the variations of this exercise base, excluding itself
"""
if not self.variations:
return []
return self.variations.exercisebase_set.filter(~Q(id=self.id))
def get_translation(self, language: Optional[str] = None):
"""
Returns the exercise for the given language. If the language is not
available, return the English translation.
Note that as a fallback, if no English translation is found, the
first available one is returned. While this is kind of wrong, it won't
happen in our dataset, but it is possible that some local installations
have deleted the English translation or similar
"""
# wger
from wger.exercises.models import Exercise
language = language or get_language()
try:
translation = self.exercises.get(language__short_name=language)
except Exercise.DoesNotExist:
try:
translation = self.exercises.get(language__short_name=ENGLISH_SHORT_NAME)
except Exercise.DoesNotExist:
translation = self.exercises.first()
except Exercise.MultipleObjectsReturned:
translation = self.exercises.filter(language__short_name=language).first()
return translation
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
reset_exercise_api_cache(self.uuid)
def delete(self, using=None, keep_parents=False, replace_by: str = None):
"""
Save entry to log
"""
# wger
from wger.exercises.models import DeletionLog
if replace_by:
try:
ExerciseBase.objects.get(uuid=replace_by)
except ExerciseBase.DoesNotExist:
replace_by = None
log = DeletionLog(
model_type=DeletionLog.MODEL_BASE,
uuid=self.uuid,
comment=f'Exercise base of {self.get_translation(ENGLISH_SHORT_NAME)}',
replaced_by=replace_by,
)
log.save()
reset_exercise_api_cache(self.uuid)
return super().delete(using, keep_parents)
| 8,064 | Python | .py | 229 | 27.820961 | 98 | 0.650802 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,679 | deletion_log.py | wger-project_wger/wger/exercises/models/deletion_log.py | # This file is part of wger Workout Manager <https://github.com/wger-project>.
#
# 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 uuid
# Django
from django.db import models
class DeletionLog(models.Model):
"""
Model to log deleted exercises
This is needed to keep the local instances in sync with upstream wger. Sometimes
it is necessary to delete entries, either because they are duplicated, the submission
wasn't of the needed quality, or other reasons and these would land in the
different DBs, without any way of cleaning them up.
"""
MODEL_BASE = 'base'
MODEL_TRANSLATION = 'translation'
MODEL_IMAGE = 'image'
MODEL_VIDEO = 'video'
MODELS = [
(MODEL_BASE, 'base'),
(MODEL_TRANSLATION, 'translation'),
(MODEL_IMAGE, 'image'),
(MODEL_VIDEO, 'video'),
]
model_type = models.CharField(
max_length=11,
choices=MODELS,
)
uuid = models.UUIDField(
default=uuid.uuid4,
unique=True,
editable=False,
verbose_name='UUID',
)
replaced_by = models.UUIDField(
default=None,
unique=False,
editable=False,
null=True,
verbose_name='Replaced by',
help_text='UUID of the object replaced by the deleted one. At the moment only available '
'for exercise bases',
)
timestamp = models.DateTimeField(auto_now=True)
comment = models.CharField(max_length=200, default='')
| 2,140 | Python | .py | 57 | 32.473684 | 97 | 0.697248 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,680 | video.py | wger-project_wger/wger/exercises/models/video.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 pathlib
import uuid
# Django
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext_lazy as _
# Third Party
from simple_history.models import HistoricalRecords
# wger
from wger.utils.cache import reset_exercise_api_cache
try:
# Third Party
import ffmpeg
except ImportError:
ffmpeg = None
# wger
from wger.exercises.models import ExerciseBase
from wger.utils.models import (
AbstractHistoryMixin,
AbstractLicenseModel,
)
MAX_FILE_SIZE_MB = 100
def validate_video(value):
if value.size > 1024 * 1024 * MAX_FILE_SIZE_MB:
raise ValidationError(_('Maximum file size is %(size)sMB.') % {'size': MAX_FILE_SIZE_MB})
# Editing existing video
if not hasattr(value.file, 'temporary_file_path'):
return
if value.file.content_type not in ['video/mp4', 'video/webm', 'video/ogg']:
raise ValidationError(_('File type is not supported'))
# ffmpeg is not installed, skip
if not ffmpeg:
return
# ffmpeg needs to access this
if not hasattr(value.file, 'temporary_file_path'):
raise ValidationError(_('File type is not supported'))
try:
ffmpeg.probe(value.file.temporary_file_path())
except ffmpeg.Error as e:
raise ValidationError(_('File is not a valid video'))
def exercise_video_upload_dir(instance, filename):
"""
Returns the upload target for exercise videos
"""
ext = pathlib.Path(filename).suffix
return f'exercise-video/{instance.exercise_base.id}/{instance.uuid}{ext}'
class ExerciseVideo(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
"""
Model for an exercise image
"""
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True,
verbose_name='UUID',
)
"""Globally unique ID, to identify the image across installations"""
exercise_base = models.ForeignKey(
ExerciseBase,
verbose_name=_('Exercise'),
on_delete=models.CASCADE,
)
"""The exercise the video belongs to"""
is_main = models.BooleanField(
verbose_name=_('Main video'),
default=False,
)
"""A flag indicating whether the video is the exercise's main one"""
video = models.FileField(
verbose_name=_('Video'),
upload_to=exercise_video_upload_dir,
validators=[validate_video],
)
"""Uploaded video"""
size = models.IntegerField(
verbose_name=_('Size'),
default=0,
editable=False,
)
"""The video filesize, in bytes"""
duration = models.DecimalField(
verbose_name=_('Duration'),
default=0,
editable=False,
max_digits=12,
decimal_places=2,
)
"""The video duration, in seconds"""
width = models.IntegerField(
verbose_name=_('Width'),
default=0,
editable=False,
)
"""The video width, in pixels"""
height = models.IntegerField(
verbose_name=_('Height'),
default=0,
editable=False,
)
"""The video height, in pixels"""
codec = models.CharField(
verbose_name=_('Codec'),
max_length=30,
default='',
editable=False,
)
"""The video codec"""
codec_long = models.CharField(
verbose_name=_('Codec, long name'),
max_length=100,
default='',
editable=False,
)
"""The video codec, in full"""
created = models.DateTimeField(
_('Date'),
auto_now_add=True,
)
"""The creation time"""
last_update = models.DateTimeField(
_('Date'),
auto_now=True,
)
"""Datetime of last modification"""
history = HistoricalRecords()
"""Edit history"""
def get_absolute_url(self):
"""
Returns the video URL
"""
return self.video.url
class Meta:
"""
Set default ordering
"""
ordering = ['-is_main', 'id']
def get_owner_object(self):
"""
Video has no owner information
"""
return False
def save(self, *args, **kwargs):
"""
Save metadata about the video if ffmpeg is installed
"""
if ffmpeg and not self.pk and hasattr(self.video.file, 'temporary_file_path'):
probe_result = ffmpeg.probe(self.video.file.temporary_file_path())
self.size = probe_result['format']['size']
self.duration = probe_result['format']['duration']
# Streams are stored in a list, and we don't know which one is the video stream
for stream in probe_result['streams']:
if stream['codec_type'] != 'video':
continue
# Read out video information
self.width = stream['width']
self.height = stream['height']
self.codec = stream['codec_name']
self.codec_long = stream['codec_long_name']
# Api cache
reset_exercise_api_cache(self.exercise_base.uuid)
super().save(*args, **kwargs)
| 5,957 | Python | .py | 177 | 27.062147 | 97 | 0.640293 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,681 | image.py | wger-project_wger/wger/exercises/models/image.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 pathlib
import uuid
# Django
from django.db import models
from django.utils.translation import gettext_lazy as _
# Third Party
from simple_history.models import HistoricalRecords
# wger
from wger.exercises.models import ExerciseBase
from wger.utils.cache import reset_exercise_api_cache
from wger.utils.helpers import BaseImage
from wger.utils.models import (
AbstractHistoryMixin,
AbstractLicenseModel,
)
def exercise_image_upload_dir(instance, filename):
"""
Returns the upload target for exercise images
"""
ext = pathlib.Path(filename).suffix
return f'exercise-images/{instance.exercise_base.id}/{instance.uuid}{ext}'
class ExerciseImage(AbstractLicenseModel, AbstractHistoryMixin, models.Model, BaseImage):
"""
Model for an exercise image
"""
LINE_ART = '1'
THREE_D = '2'
LOW_POLY = '3'
PHOTO = '4'
OTHER = '5'
STYLE = (
(LINE_ART, _('Line')),
(THREE_D, _('3D')),
(LOW_POLY, _('Low-poly')),
(PHOTO, _('Photo')),
(OTHER, _('Other')),
)
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True,
verbose_name='UUID',
)
"""Globally unique ID, to identify the image across installations"""
exercise_base = models.ForeignKey(
ExerciseBase,
verbose_name=_('Exercise'),
on_delete=models.CASCADE,
)
"""The exercise the image belongs to"""
image = models.ImageField(
verbose_name=_('Image'),
help_text=_('Only PNG and JPEG formats are supported'),
upload_to=exercise_image_upload_dir,
)
"""Uploaded image"""
is_main = models.BooleanField(
verbose_name=_('Main picture'),
default=False,
help_text=_(
'Tick the box if you want to set this image as the '
'main one for the exercise (will be shown e.g. in '
'the search). The first image is automatically '
'marked by the system.'
),
)
"""A flag indicating whether the image is the exercise's main image"""
style = models.CharField(
help_text=_('The art style of your image'),
max_length=1,
choices=STYLE,
default=PHOTO,
)
"""The art style of the image"""
created = models.DateTimeField(
_('Date'),
auto_now_add=True,
)
"""The creation time"""
last_update = models.DateTimeField(
_('Date'),
auto_now=True,
)
"""Datetime of last modification"""
history = HistoricalRecords()
"""Edit history"""
def get_absolute_url(self):
"""
Return the image URL
"""
return self.image.url
class Meta:
"""
Set default ordering
"""
ordering = ['-is_main', 'id']
base_manager_name = 'objects'
def save(self, *args, **kwargs):
"""
Only one image can be marked as main picture at a time
"""
if self.is_main:
ExerciseImage.objects.filter(exercise_base=self.exercise_base).update(is_main=False)
self.is_main = True
else:
if (
ExerciseImage.objects.all().filter(exercise_base=self.exercise_base).count() == 0
or not ExerciseImage.objects.all()
.filter(exercise_base=self.exercise_base, is_main=True)
.count()
):
self.is_main = True
# Api cache
reset_exercise_api_cache(self.exercise_base.uuid)
# And go on
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Reset all cached infos
"""
super().delete(*args, **kwargs)
# Make sure there is always a main image
if (
not ExerciseImage.objects.all()
.filter(exercise_base=self.exercise_base, is_main=True)
.count()
and ExerciseImage.objects.all()
.filter(exercise_base=self.exercise_base)
.filter(is_main=False)
.count()
):
image = ExerciseImage.objects.all().filter(
exercise_base=self.exercise_base, is_main=False
)[0]
image.is_main = True
image.save()
def get_owner_object(self):
"""
Image has no owner information
"""
return False
@classmethod
def from_json(
cls,
connect_to: ExerciseBase,
retrieved_image,
json_data: dict,
generate_uuid: bool = False,
):
image: cls = super().from_json(
connect_to,
retrieved_image,
json_data,
generate_uuid,
)
image.exercise_base = connect_to
image.is_main = json_data['is_main']
image.license_id = json_data['license']
image.license_title = json_data['license_title']
image.license_object_url = json_data['license_object_url']
image.license_author = json_data['license_author']
image.license_author_url = json_data['license_author_url']
image.license_derivative_source_url = json_data['license_derivative_source_url']
image.save_image(retrieved_image, json_data)
image.save()
return image
| 6,137 | Python | .py | 182 | 26.203297 | 97 | 0.614852 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,682 | exercise.py | wger-project_wger/wger/exercises/models/exercise.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 uuid
# Django
from django.contrib.postgres.indexes import GinIndex
from django.core.validators import MinLengthValidator
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
# Third Party
import bleach
from simple_history.models import HistoricalRecords
# wger
from wger.core.models import Language
from wger.exercises.models import ExerciseBase
from wger.utils.cache import (
reset_exercise_api_cache,
reset_workout_canonical_form,
)
from wger.utils.models import (
AbstractHistoryMixin,
AbstractLicenseModel,
)
class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
"""
Model for an exercise
"""
description = models.TextField(
max_length=2000,
verbose_name=_('Description'),
validators=[MinLengthValidator(40)],
)
"""Description on how to perform the exercise"""
name = models.CharField(
max_length=200,
verbose_name=_('Name'),
)
"""The exercise's name"""
created = models.DateTimeField(
_('Date'),
auto_now_add=True,
)
"""The submission date"""
last_update = models.DateTimeField(
_('Date'),
auto_now=True,
)
"""Datetime of the last modification"""
language = models.ForeignKey(
Language,
verbose_name=_('Language'),
on_delete=models.CASCADE,
)
"""The exercise's language"""
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True,
verbose_name='UUID',
)
"""Globally unique ID, to identify the exercise across installations"""
exercise_base = models.ForeignKey(
ExerciseBase,
verbose_name='ExerciseBase',
on_delete=models.CASCADE,
default=None,
null=False,
related_name='exercises',
)
""" Refers to the base exercise with non translated information """
history = HistoricalRecords()
"""Edit history"""
#
# Django methods
#
class Meta:
base_manager_name = 'objects'
ordering = [
'name',
]
indexes = (GinIndex(fields=['name']),)
def get_absolute_url(self):
"""
Returns the canonical URL to view an exercise
"""
slug_name = slugify(self.name)
kwargs = {'pk': self.exercise_base_id}
if slug_name:
kwargs['slug'] = slug_name
return reverse('exercise:exercise:view-base', kwargs=kwargs)
def save(self, *args, **kwargs):
"""
Reset all cached infos
"""
super().save(*args, **kwargs)
# Api cache
reset_exercise_api_cache(self.exercise_base.uuid)
# Cached workouts
for setting in self.exercise_base.setting_set.all():
reset_workout_canonical_form(setting.set.exerciseday.training_id)
def delete(self, *args, **kwargs):
"""
Reset all cached infos
"""
# Cached workouts
for setting in self.exercise_base.setting_set.all():
reset_workout_canonical_form(setting.set.exerciseday.training.pk)
# Api cache
reset_exercise_api_cache(self.exercise_base.uuid)
super().delete(*args, **kwargs)
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
#
# Properties to expose the info from the exercise base
#
@property
def category(self):
return self.exercise_base.category
@property
def muscles(self):
return self.exercise_base.muscles
@property
def muscles_secondary(self):
return self.exercise_base.muscles_secondary
@property
def equipment(self):
return self.exercise_base.equipment
@property
def images(self):
return self.exercise_base.exerciseimage_set
@property
def videos(self):
return self.exercise_base.exercisevideo_set
@property
def variations(self):
"""
Returns the variations for this exercise in the same language
"""
out = []
if self.exercise_base.variations:
for variation in self.exercise_base.variations.exercisebase_set.all():
for exercise in variation.exercises.filter(language=self.language).all():
out.append(exercise)
return out
#
# Own methods
#
@property
def main_image(self):
"""
Return the main image for the exercise or None if nothing is found
"""
return self.images.all().filter(is_main=True).first()
@property
def description_clean(self):
"""
Return the exercise description with all markup removed
"""
return bleach.clean(self.description, strip=True)
def get_owner_object(self):
"""
Exercise has no owner information
"""
return False
| 5,844 | Python | .py | 182 | 25.626374 | 89 | 0.656183 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,683 | 0016_exercisealias.py | wger-project_wger/wger/exercises/migrations/0016_exercisealias.py | # Generated by Django 3.2.10 on 2022-02-17 21:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('exercises', '0015_exercise_videos'),
]
operations = [
migrations.CreateModel(
name='Alias',
fields=[
(
'id',
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name='ID'
),
),
('alias', models.CharField(max_length=200, verbose_name='Alias for an exercise')),
(
'exercise',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercise',
verbose_name='Exercise',
),
),
],
),
]
| 987 | Python | .py | 29 | 20.068966 | 98 | 0.469602 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,684 | 0019_exercise_crowdsourcing_changes.py | wger-project_wger/wger/exercises/migrations/0019_exercise_crowdsourcing_changes.py | # Generated by Django 3.2.15 on 2022-08-15 18:06
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import simple_history.models
import uuid
class Migration(migrations.Migration):
dependencies = [
('exercises', '0018_delete_pending_exercises'),
]
operations = [
migrations.RemoveField(
model_name='exercise',
name='name_original',
),
migrations.RemoveField(
model_name='exercise',
name='status',
),
migrations.RemoveField(
model_name='exercisebase',
name='status',
),
migrations.AddField(
model_name='exercise',
name='update_date',
field=models.DateTimeField(auto_now=True, verbose_name='Date'),
),
migrations.AddField(
model_name='exercisebase',
name='creation_date',
field=models.DateField(
auto_now_add=True, default=django.utils.timezone.now, verbose_name='Date'
),
preserve_default=False,
),
migrations.AddField(
model_name='exercisebase',
name='update_date',
field=models.DateTimeField(auto_now=True, verbose_name='Date'),
),
migrations.AlterField(
model_name='exercisebase',
name='variations',
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to='exercises.variation',
verbose_name='Variations',
),
),
migrations.AlterField(
model_name='exercisecomment',
name='exercise',
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercise',
verbose_name='Exercise',
),
),
migrations.CreateModel(
name='HistoricalExerciseComment',
fields=[
(
'id',
models.IntegerField(
auto_created=True, blank=True, db_index=True, verbose_name='ID'
),
),
(
'comment',
models.CharField(
help_text='A comment about how to correctly do this exercise.',
max_length=200,
verbose_name='Comment',
),
),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
(
'history_type',
models.CharField(
choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1
),
),
(
'exercise',
models.ForeignKey(
blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.exercise',
verbose_name='Exercise',
),
),
(
'history_user',
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='+',
to=settings.AUTH_USER_MODEL,
),
),
],
options={
'verbose_name': 'historical exercise comment',
'verbose_name_plural': 'historical exercise comments',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalExerciseBase',
fields=[
(
'id',
models.IntegerField(
auto_created=True, blank=True, db_index=True, verbose_name='ID'
),
),
(
'license_author',
models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=50,
null=True,
verbose_name='Author',
),
),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')),
(
'creation_date',
models.DateField(blank=True, editable=False, verbose_name='Date'),
),
(
'update_date',
models.DateTimeField(blank=True, editable=False, verbose_name='Date'),
),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
(
'history_type',
models.CharField(
choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1
),
),
(
'category',
models.ForeignKey(
blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.exercisecategory',
verbose_name='Category',
),
),
(
'history_user',
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='+',
to=settings.AUTH_USER_MODEL,
),
),
(
'license',
models.ForeignKey(
blank=True,
db_constraint=False,
default=2,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='core.license',
verbose_name='License',
),
),
(
'variations',
models.ForeignKey(
blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.variation',
verbose_name='Variations',
),
),
],
options={
'verbose_name': 'historical exercise base',
'verbose_name_plural': 'historical exercise bases',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalExercise',
fields=[
(
'id',
models.IntegerField(
auto_created=True, blank=True, db_index=True, verbose_name='ID'
),
),
(
'license_author',
models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=50,
null=True,
verbose_name='Author',
),
),
(
'description',
models.TextField(
max_length=2000,
validators=[django.core.validators.MinLengthValidator(40)],
verbose_name='Description',
),
),
('name', models.CharField(max_length=200, verbose_name='Name')),
(
'creation_date',
models.DateField(blank=True, editable=False, null=True, verbose_name='Date'),
),
(
'update_date',
models.DateTimeField(blank=True, editable=False, verbose_name='Date'),
),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
(
'history_type',
models.CharField(
choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1
),
),
(
'exercise_base',
models.ForeignKey(
blank=True,
db_constraint=False,
default=None,
null=False,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.exercisebase',
verbose_name='ExerciseBase',
),
),
(
'history_user',
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='+',
to=settings.AUTH_USER_MODEL,
),
),
(
'language',
models.ForeignKey(
blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='core.language',
verbose_name='Language',
),
),
(
'license',
models.ForeignKey(
blank=True,
db_constraint=False,
default=2,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='core.license',
verbose_name='License',
),
),
],
options={
'verbose_name': 'historical exercise',
'verbose_name_plural': 'historical exercises',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalAlias',
fields=[
(
'id',
models.IntegerField(
auto_created=True, blank=True, db_index=True, verbose_name='ID'
),
),
('alias', models.CharField(max_length=200, verbose_name='Alias for an exercise')),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
(
'history_type',
models.CharField(
choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1
),
),
(
'exercise',
models.ForeignKey(
blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.exercise',
verbose_name='Exercise',
),
),
(
'history_user',
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='+',
to=settings.AUTH_USER_MODEL,
),
),
],
options={
'verbose_name': 'historical alias',
'verbose_name_plural': 'historical aliass',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.RemoveField(
model_name='exerciseimage',
name='status',
),
migrations.AlterField(
model_name='exercise',
name='exercise_base',
field=models.ForeignKey(
default=None,
on_delete=django.db.models.deletion.CASCADE,
related_name='exercises',
to='exercises.exercisebase',
verbose_name='ExerciseBase',
),
),
migrations.AlterField(
model_name='historicalexercise',
name='exercise_base',
field=models.ForeignKey(
blank=True,
db_constraint=False,
default=None,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.exercisebase',
verbose_name='ExerciseBase',
),
),
]
| 15,412 | Python | .py | 392 | 21.193878 | 146 | 0.42155 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,685 | 0009_auto_20201211_0139.py | wger-project_wger/wger/exercises/migrations/0009_auto_20201211_0139.py | # Generated by Django 3.1.4 on 2020-12-11 00:39
from django.db import migrations
def copy_columns(apps, schema_editor):
Exercise = apps.get_model('exercises', 'Exercise')
ExerciseBase = apps.get_model('exercises', 'ExerciseBase')
for exercise in Exercise.objects.all():
exercise_base = ExerciseBase.objects.create(
category=exercise.category,
)
exercise_base.equipment.set(exercise.equipment.all())
exercise_base.muscles.set(exercise.muscles.all())
exercise_base.muscles_secondary.set(exercise.muscles_secondary.all())
exercise_base.status = exercise.status
exercise_base.license = exercise.license
exercise_base.license_author = exercise.license_author
exercise_base.license_author = exercise.license_author
exercise_base.variations = exercise.variations
exercise_base.save()
exercise.exercise_base = exercise_base
exercise.save()
class Migration(migrations.Migration):
dependencies = [
('exercises', '0008_exercisebase'),
]
operations = [
migrations.RunPython(copy_columns),
]
| 1,147 | Python | .py | 27 | 35.259259 | 77 | 0.697842 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,686 | 0027_alter_deletionlog_replaced_by_and_more.py | wger-project_wger/wger/exercises/migrations/0027_alter_deletionlog_replaced_by_and_more.py | # Generated by Django 4.2.6 on 2023-11-23 19:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exercises', '0026_deletionlog_replaced_by'),
]
operations = [
migrations.AlterField(
model_name='deletionlog',
name='replaced_by',
field=models.UUIDField(
default=None,
editable=False,
help_text='UUID of the object replaced by the deleted one. At the moment only available for exercise bases',
null=True,
verbose_name='Replaced by',
),
),
migrations.AlterField(
model_name='exercise',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=600,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exercise',
name='license_author_url',
field=models.URLField(blank=True, verbose_name='Link to author profile, if available'),
),
migrations.AlterField(
model_name='exercise',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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.',
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AlterField(
model_name='exercise',
name='license_object_url',
field=models.URLField(blank=True, verbose_name='Link to original object, if available'),
),
migrations.AlterField(
model_name='exercise',
name='license_title',
field=models.CharField(
blank=True,
max_length=300,
verbose_name='The original title of this object, if available',
),
),
migrations.AlterField(
model_name='exercisebase',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=600,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exercisebase',
name='license_author_url',
field=models.URLField(blank=True, verbose_name='Link to author profile, if available'),
),
migrations.AlterField(
model_name='exercisebase',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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.',
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AlterField(
model_name='exercisebase',
name='license_object_url',
field=models.URLField(blank=True, verbose_name='Link to original object, if available'),
),
migrations.AlterField(
model_name='exercisebase',
name='license_title',
field=models.CharField(
blank=True,
max_length=300,
verbose_name='The original title of this object, if available',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=600,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='license_author_url',
field=models.URLField(blank=True, verbose_name='Link to author profile, if available'),
),
migrations.AlterField(
model_name='exerciseimage',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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.',
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='license_object_url',
field=models.URLField(blank=True, verbose_name='Link to original object, if available'),
),
migrations.AlterField(
model_name='exerciseimage',
name='license_title',
field=models.CharField(
blank=True,
max_length=300,
verbose_name='The original title of this object, if available',
),
),
migrations.AlterField(
model_name='exercisevideo',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=600,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exercisevideo',
name='license_author_url',
field=models.URLField(blank=True, verbose_name='Link to author profile, if available'),
),
migrations.AlterField(
model_name='exercisevideo',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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.',
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AlterField(
model_name='exercisevideo',
name='license_object_url',
field=models.URLField(blank=True, verbose_name='Link to original object, if available'),
),
migrations.AlterField(
model_name='exercisevideo',
name='license_title',
field=models.CharField(
blank=True,
max_length=300,
verbose_name='The original title of this object, if available',
),
),
migrations.AlterField(
model_name='historicalexercise',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=600,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercise',
name='license_author_url',
field=models.URLField(blank=True, verbose_name='Link to author profile, if available'),
),
migrations.AlterField(
model_name='historicalexercise',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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.',
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AlterField(
model_name='historicalexercise',
name='license_object_url',
field=models.URLField(blank=True, verbose_name='Link to original object, if available'),
),
migrations.AlterField(
model_name='historicalexercise',
name='license_title',
field=models.CharField(
blank=True,
max_length=300,
verbose_name='The original title of this object, if available',
),
),
migrations.AlterField(
model_name='historicalexercisebase',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=600,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercisebase',
name='license_author_url',
field=models.URLField(blank=True, verbose_name='Link to author profile, if available'),
),
migrations.AlterField(
model_name='historicalexercisebase',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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.',
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AlterField(
model_name='historicalexercisebase',
name='license_object_url',
field=models.URLField(blank=True, verbose_name='Link to original object, if available'),
),
migrations.AlterField(
model_name='historicalexercisebase',
name='license_title',
field=models.CharField(
blank=True,
max_length=300,
verbose_name='The original title of this object, if available',
),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=600,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='license_author_url',
field=models.URLField(blank=True, verbose_name='Link to author profile, if available'),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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.',
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='license_object_url',
field=models.URLField(blank=True, verbose_name='Link to original object, if available'),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='license_title',
field=models.CharField(
blank=True,
max_length=300,
verbose_name='The original title of this object, if available',
),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=600,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='license_author_url',
field=models.URLField(blank=True, verbose_name='Link to author profile, if available'),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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.',
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='license_object_url',
field=models.URLField(blank=True, verbose_name='Link to original object, if available'),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='license_title',
field=models.CharField(
blank=True,
max_length=300,
verbose_name='The original title of this object, if available',
),
),
]
| 13,880 | Python | .py | 331 | 29.006042 | 200 | 0.565079 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,687 | 0014_exerciseimage_style.py | wger-project_wger/wger/exercises/migrations/0014_exerciseimage_style.py | # Generated by Django 3.2.7 on 2021-09-17 15:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exercises', '0013_auto_20210503_1232'),
]
operations = [
migrations.AddField(
model_name='exerciseimage',
name='style',
field=models.CharField(
choices=[
('1', 'Line'),
('2', '3D'),
('3', 'Low-poly'),
('4', 'Photo'),
('5', 'Other'),
],
default='1',
help_text='The art style of your image',
max_length=1,
),
),
]
| 731 | Python | .py | 24 | 18.125 | 56 | 0.432432 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,688 | 0020_historicalexerciseimage_historicalexercisevideo.py | wger-project_wger/wger/exercises/migrations/0020_historicalexerciseimage_historicalexercisevideo.py | # Generated by Django 3.2.15 on 2022-09-22 19:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
import uuid
import wger.exercises.models.video
class Migration(migrations.Migration):
dependencies = [
('core', '0014_merge_20210818_1735'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('exercises', '0019_exercise_crowdsourcing_changes'),
]
operations = [
migrations.CreateModel(
name='HistoricalExerciseVideo',
fields=[
(
'id',
models.IntegerField(
auto_created=True, blank=True, db_index=True, verbose_name='ID'
),
),
(
'license_author',
models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=50,
null=True,
verbose_name='Author',
),
),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')),
('is_main', models.BooleanField(default=False, verbose_name='Main video')),
(
'video',
models.TextField(
max_length=100,
validators=[wger.exercises.models.video.validate_video],
verbose_name='Video',
),
),
('size', models.IntegerField(default=0, editable=False, verbose_name='Size')),
(
'duration',
models.DecimalField(
decimal_places=2,
default=0,
editable=False,
max_digits=12,
verbose_name='Duration',
),
),
('width', models.IntegerField(default=0, editable=False, verbose_name='Width')),
('height', models.IntegerField(default=0, editable=False, verbose_name='Height')),
(
'codec',
models.CharField(
default='', editable=False, max_length=30, verbose_name='Codec'
),
),
(
'codec_long',
models.CharField(
default='', editable=False, max_length=100, verbose_name='Codec, long name'
),
),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
(
'history_type',
models.CharField(
choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1
),
),
(
'exercise_base',
models.ForeignKey(
blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.exercisebase',
verbose_name='Exercise',
),
),
(
'history_user',
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='+',
to=settings.AUTH_USER_MODEL,
),
),
(
'license',
models.ForeignKey(
blank=True,
db_constraint=False,
default=2,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='core.license',
verbose_name='License',
),
),
],
options={
'verbose_name': 'historical exercise video',
'verbose_name_plural': 'historical exercise videos',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalExerciseImage',
fields=[
(
'id',
models.IntegerField(
auto_created=True, blank=True, db_index=True, verbose_name='ID'
),
),
(
'license_author',
models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=50,
null=True,
verbose_name='Author',
),
),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')),
(
'image',
models.TextField(
help_text='Only PNG and JPEG formats are supported',
max_length=100,
verbose_name='Image',
),
),
(
'is_main',
models.BooleanField(
default=False,
help_text='Tick the box if you want to set this image as the main one for the exercise (will be shown e.g. in the search). The first image is automatically marked by the system.',
verbose_name='Main picture',
),
),
(
'style',
models.CharField(
choices=[
('1', 'Line'),
('2', '3D'),
('3', 'Low-poly'),
('4', 'Photo'),
('5', 'Other'),
],
default='4',
help_text='The art style of your image',
max_length=1,
),
),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
(
'history_type',
models.CharField(
choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1
),
),
(
'exercise_base',
models.ForeignKey(
blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.exercisebase',
verbose_name='Exercise',
),
),
(
'history_user',
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name='+',
to=settings.AUTH_USER_MODEL,
),
),
(
'license',
models.ForeignKey(
blank=True,
db_constraint=False,
default=2,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='core.license',
verbose_name='License',
),
),
],
options={
'verbose_name': 'historical exercise image',
'verbose_name_plural': 'historical exercise images',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': ('history_date', 'history_id'),
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
]
| 9,261 | Python | .py | 224 | 21.683036 | 203 | 0.402081 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,689 | 0025_rename_update_date_exercise_last_update_and_more.py | wger-project_wger/wger/exercises/migrations/0025_rename_update_date_exercise_last_update_and_more.py | # Generated by Django 4.1.9 on 2023-07-27 08:49
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exercises', '0024_license_information'),
]
operations = [
migrations.RenameField(
model_name='exercise',
old_name='update_date',
new_name='last_update',
),
migrations.RenameField(
model_name='exercisebase',
old_name='update_date',
new_name='last_update',
),
migrations.RenameField(
model_name='historicalexercise',
old_name='update_date',
new_name='created',
),
migrations.RenameField(
model_name='historicalexercisebase',
old_name='update_date',
new_name='created',
),
migrations.RemoveField(
model_name='exercise',
name='creation_date',
),
migrations.RemoveField(
model_name='exercisebase',
name='creation_date',
),
migrations.RemoveField(
model_name='historicalexercise',
name='creation_date',
),
migrations.RemoveField(
model_name='historicalexercisebase',
name='creation_date',
),
migrations.AddField(
model_name='exercise',
name='created',
field=models.DateTimeField(
auto_now_add=True, default=django.utils.timezone.now, verbose_name='Date'
),
preserve_default=False,
),
migrations.AddField(
model_name='exercisebase',
name='created',
field=models.DateTimeField(
auto_now_add=True, default=django.utils.timezone.now, verbose_name='Date'
),
preserve_default=False,
),
migrations.AddField(
model_name='exerciseimage',
name='created',
field=models.DateTimeField(
auto_now_add=True,
default=django.utils.timezone.now,
verbose_name='Date',
),
preserve_default=False,
),
migrations.AddField(
model_name='exerciseimage',
name='last_update',
field=models.DateTimeField(
auto_now=True,
verbose_name='Date',
),
),
migrations.AddField(
model_name='exercisevideo',
name='created',
field=models.DateTimeField(
auto_now_add=True,
default=django.utils.timezone.now,
verbose_name='Date',
),
preserve_default=False,
),
migrations.AddField(
model_name='exercisevideo',
name='last_update',
field=models.DateTimeField(
auto_now=True,
verbose_name='Date',
),
),
migrations.AddField(
model_name='historicalexercise',
name='last_update',
field=models.DateTimeField(
blank=True,
default=django.utils.timezone.now,
editable=False,
verbose_name='Date',
),
preserve_default=False,
),
migrations.AddField(
model_name='historicalexercisebase',
name='last_update',
field=models.DateTimeField(
blank=True,
default=django.utils.timezone.now,
editable=False,
verbose_name='Date',
),
preserve_default=False,
),
migrations.AddField(
model_name='historicalexerciseimage',
name='created',
field=models.DateTimeField(
blank=True,
default=django.utils.timezone.now,
editable=False,
verbose_name='Date',
),
preserve_default=False,
),
migrations.AddField(
model_name='historicalexerciseimage',
name='last_update',
field=models.DateTimeField(
blank=True,
default=django.utils.timezone.now,
editable=False,
verbose_name='Date',
),
preserve_default=False,
),
migrations.AddField(
model_name='historicalexercisevideo',
name='created',
field=models.DateTimeField(
blank=True,
default=django.utils.timezone.now,
editable=False,
verbose_name='Date',
),
preserve_default=False,
),
migrations.AddField(
model_name='historicalexercisevideo',
name='last_update',
field=models.DateTimeField(
blank=True,
default=django.utils.timezone.now,
editable=False,
verbose_name='Date',
),
preserve_default=False,
),
]
| 5,198 | Python | .py | 163 | 19.478528 | 89 | 0.512622 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,690 | 0017_muscle_name_en.py | wger-project_wger/wger/exercises/migrations/0017_muscle_name_en.py | # Generated by Django 3.2.13 on 2022-05-10 10:07
# Edited by Tom on 2022-05-12 18:30 to include name_en values
from django.db import migrations, models
# Will also set the name_en value in the migration
muscle_names = [
(1, 'Biceps'),
(2, 'Shoulders'),
(4, 'Chest'),
(5, 'Triceps'),
(6, 'Abs'),
(7, 'Calves'),
(8, 'Glutes'),
(10, 'Quads'),
(11, 'Hamstrings'),
(12, 'Lats'),
(16, 'Lower back'),
]
def set_names(apps, schema_editor):
Muscle = apps.get_model('exercises', 'Muscle')
for mapping in muscle_names:
try:
m = Muscle.objects.get(pk=mapping[0])
m.name_en = mapping[1]
m.save()
except Muscle.DoesNotExist:
pass
class Migration(migrations.Migration):
dependencies = [
('exercises', '0016_exercisealias'),
]
operations = [
migrations.AddField(
model_name='muscle',
name='name_en',
field=models.CharField(
default='',
help_text='A more basic name for the muscle',
max_length=50,
verbose_name='Alternative name',
),
),
migrations.RunPython(set_names),
]
| 1,238 | Python | .py | 43 | 21.209302 | 61 | 0.555556 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,691 | 0004_auto_20170404_0114.py | wger-project_wger/wger/exercises/migrations/0004_auto_20170404_0114.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-04-04 01:14
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('exercises', '0003_auto_20160921_2000'),
]
operations = [
migrations.AlterField(
model_name='exercise',
name='equipment',
field=models.ManyToManyField(
blank=True, to='exercises.Equipment', verbose_name='Equipment'
),
),
migrations.AlterField(
model_name='exercise',
name='muscles',
field=models.ManyToManyField(
blank=True, to='exercises.Muscle', verbose_name='Primary muscles'
),
),
migrations.AlterField(
model_name='exercise',
name='muscles_secondary',
field=models.ManyToManyField(
blank=True,
related_name='secondary_muscles',
to='exercises.Muscle',
verbose_name='Secondary muscles',
),
),
migrations.AlterField(
model_name='exercise',
name='status',
field=models.CharField(
choices=[('1', 'Pending'), ('2', 'Accepted'), ('3', 'Declined')],
default='1',
editable=False,
max_length=2,
),
),
migrations.AlterField(
model_name='exercise',
name='uuid',
field=models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID'),
),
migrations.AlterField(
model_name='exerciseimage',
name='is_main',
field=models.BooleanField(
default=False,
help_text='Tick the box if you want to set this image as the main one for the exercise (will be shown e.g. in the search). The first image is automatically marked by the system.',
verbose_name='Main picture',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='status',
field=models.CharField(
choices=[('1', 'Pending'), ('2', 'Accepted'), ('3', 'Declined')],
default='1',
editable=False,
max_length=2,
),
),
]
| 2,389 | Python | .py | 68 | 23.308824 | 195 | 0.520932 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,692 | 0021_deletionlog.py | wger-project_wger/wger/exercises/migrations/0021_deletionlog.py | # Generated by Django 4.0.8 on 2023-01-23 17:41
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('exercises', '0020_historicalexerciseimage_historicalexercisevideo'),
]
operations = [
migrations.CreateModel(
name='DeletionLog',
fields=[
(
'id',
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name='ID'
),
),
(
'model_type',
models.CharField(
choices=[
('base', 'base'),
('translation', 'translation'),
('image', 'image'),
('video', 'video'),
],
max_length=11,
),
),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')),
('timestamp', models.DateTimeField(auto_now=True)),
('comment', models.CharField(default='', max_length=200)),
],
),
]
| 1,284 | Python | .py | 35 | 20.828571 | 100 | 0.435341 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,693 | 0024_license_information.py | wger-project_wger/wger/exercises/migrations/0024_license_information.py | # Generated by Django 4.2 on 2023-04-07 15:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exercises', '0023_make_uuid_unique'),
]
operations = [
migrations.AddField(
model_name='exercise',
name='license_author_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to author profile, if available',
),
),
migrations.AddField(
model_name='exercise',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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=100,
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AddField(
model_name='exercise',
name='license_object_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to original object, if available',
),
),
migrations.AddField(
model_name='exercise',
name='license_title',
field=models.CharField(
blank=True,
max_length=200,
verbose_name='The original title of this object, if available',
),
),
migrations.AddField(
model_name='exercisebase',
name='license_author_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to author profile, if available',
),
),
migrations.AddField(
model_name='exercisebase',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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=100,
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AddField(
model_name='exercisebase',
name='license_object_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to original object, if available',
),
),
migrations.AddField(
model_name='exercisebase',
name='license_title',
field=models.CharField(
blank=True,
max_length=200,
verbose_name='The original title of this object, if available',
),
),
migrations.AddField(
model_name='exerciseimage',
name='license_author_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to author profile, if available',
),
),
migrations.AddField(
model_name='exerciseimage',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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=100,
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AddField(
model_name='exerciseimage',
name='license_object_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to original object, if available',
),
),
migrations.AddField(
model_name='exerciseimage',
name='license_title',
field=models.CharField(
blank=True,
max_length=200,
verbose_name='The original title of this object, if available',
),
),
migrations.AddField(
model_name='exercisevideo',
name='license_author_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to author profile, if available',
),
),
migrations.AddField(
model_name='exercisevideo',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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=100,
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AddField(
model_name='exercisevideo',
name='license_object_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to original object, if available',
),
),
migrations.AddField(
model_name='exercisevideo',
name='license_title',
field=models.CharField(
blank=True,
max_length=200,
verbose_name='The original title of this object, if available',
),
),
migrations.AddField(
model_name='historicalexercise',
name='license_author_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to author profile, if available',
),
),
migrations.AddField(
model_name='historicalexercise',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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=100,
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AddField(
model_name='historicalexercise',
name='license_object_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to original object, if available',
),
),
migrations.AddField(
model_name='historicalexercise',
name='license_title',
field=models.CharField(
blank=True,
max_length=200,
verbose_name='The original title of this object, if available',
),
),
migrations.AddField(
model_name='historicalexercisebase',
name='license_author_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to author profile, if available',
),
),
migrations.AddField(
model_name='historicalexercisebase',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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=100,
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AddField(
model_name='historicalexercisebase',
name='license_object_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to original object, if available',
),
),
migrations.AddField(
model_name='historicalexercisebase',
name='license_title',
field=models.CharField(
blank=True,
max_length=200,
verbose_name='The original title of this object, if available',
),
),
migrations.AddField(
model_name='historicalexerciseimage',
name='license_author_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to author profile, if available',
),
),
migrations.AddField(
model_name='historicalexerciseimage',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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=100,
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AddField(
model_name='historicalexerciseimage',
name='license_object_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to original object, if available',
),
),
migrations.AddField(
model_name='historicalexerciseimage',
name='license_title',
field=models.CharField(
blank=True,
max_length=200,
verbose_name='The original title of this object, if available',
),
),
migrations.AddField(
model_name='historicalexercisevideo',
name='license_author_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to author profile, if available',
),
),
migrations.AddField(
model_name='historicalexercisevideo',
name='license_derivative_source_url',
field=models.URLField(
blank=True,
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=100,
verbose_name='Link to the original source, if this is a derivative work',
),
),
migrations.AddField(
model_name='historicalexercisevideo',
name='license_object_url',
field=models.URLField(
blank=True,
max_length=100,
verbose_name='Link to original object, if available',
),
),
migrations.AddField(
model_name='historicalexercisevideo',
name='license_title',
field=models.CharField(
blank=True,
max_length=200,
verbose_name='The original title of this object, if available',
),
),
migrations.AlterField(
model_name='exercise',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=200,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exercisebase',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=200,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=200,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exercisevideo',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=200,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercise',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=200,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercisebase',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=200,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=200,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=200,
null=True,
verbose_name='Author(s)',
),
),
]
| 15,210 | Python | .py | 408 | 23.661765 | 92 | 0.517435 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,694 | 0022_alter_exercise_license_author_and_more.py | wger-project_wger/wger/exercises/migrations/0022_alter_exercise_license_author_and_more.py | # Generated by Django 4.1.5 on 2023-02-05 11:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exercises', '0021_deletionlog'),
]
operations = [
migrations.AlterField(
model_name='exercise',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=60,
null=True,
verbose_name='Author',
),
),
migrations.AlterField(
model_name='exercisebase',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=60,
null=True,
verbose_name='Author',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=60,
null=True,
verbose_name='Author',
),
),
migrations.AlterField(
model_name='exercisevideo',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=60,
null=True,
verbose_name='Author',
),
),
migrations.AlterField(
model_name='historicalexercise',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=60,
null=True,
verbose_name='Author',
),
),
migrations.AlterField(
model_name='historicalexercisebase',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=60,
null=True,
verbose_name='Author',
),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=60,
null=True,
verbose_name='Author',
),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='license_author',
field=models.CharField(
blank=True,
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=60,
null=True,
verbose_name='Author',
),
),
]
| 3,711 | Python | .py | 96 | 25.364583 | 138 | 0.52257 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,695 | 0008_exercisebase.py | wger-project_wger/wger/exercises/migrations/0008_exercisebase.py | # Generated by Django 3.1.4 on 2020-12-11 00:37
import uuid
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0011_auto_20201201_0653'),
('exercises', '0007_auto_20201203_1042'),
]
operations = [
migrations.CreateModel(
name='ExerciseBase',
fields=[
(
'id',
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name='ID'
),
),
(
'license_author',
models.CharField(
blank=True,
help_text='If you are not the author, enter \
the name or source here. This is \
needed for some licenses e.g. the \
CC-BY-SA.',
max_length=50,
null=True,
verbose_name='Author',
),
),
(
'status',
models.CharField(
choices=[('1', 'Pending'), ('2', 'Accepted'), ('3', 'Declined')],
default='1',
editable=False,
max_length=2,
),
),
(
'category',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercisecategory',
verbose_name='Category',
),
),
(
'equipment',
models.ManyToManyField(
blank=True, to='exercises.Equipment', verbose_name='Equipment'
),
),
(
'license',
models.ForeignKey(
default=2,
on_delete=django.db.models.deletion.CASCADE,
to='core.license',
verbose_name='License',
),
),
(
'muscles',
models.ManyToManyField(
blank=True, to='exercises.Muscle', verbose_name='Primary muscles'
),
),
(
'muscles_secondary',
models.ManyToManyField(
blank=True,
related_name='secondary_muscles_base',
to='exercises.Muscle',
verbose_name='Secondary muscles',
),
),
(
'variations',
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to='exercises.variation',
verbose_name='Variations',
),
),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='exercise',
name='exercise_base',
field=models.ForeignKey(
default=None,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name='exercises',
to='exercises.exercisebase',
verbose_name='ExerciseBase',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='exercise',
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='exercises.exercisebase',
verbose_name='Exercise',
),
),
]
| 4,285 | Python | .py | 116 | 18 | 100 | 0.385594 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,696 | 0006_auto_20201203_0203.py | wger-project_wger/wger/exercises/migrations/0006_auto_20201203_0203.py | # Generated by Django 3.1.3 on 2020-12-03 01:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('exercises', '0005_auto_20190618_1617'),
]
operations = [
migrations.CreateModel(
name='Variation',
fields=[
(
'id',
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name='ID'
),
),
],
),
migrations.AddField(
model_name='exercise',
name='variations',
field=models.ForeignKey(
default='',
null=True,
on_delete=django.db.models.deletion.CASCADE,
to='exercises.variation',
verbose_name='Variations',
),
),
]
| 955 | Python | .py | 31 | 18.83871 | 95 | 0.495652 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,697 | 0001_initial.py | wger-project_wger/wger/exercises/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
import django.core.validators
import wger.exercises.models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Equipment',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('name', models.CharField(max_length=50, verbose_name='Name')),
],
options={
'ordering': ['name'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Exercise',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'license_author',
models.CharField(
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=50,
null=True,
verbose_name='Author',
blank=True,
),
),
(
'status',
models.CharField(
default=b'1',
max_length=2,
editable=False,
choices=[(b'1', 'Pending'), (b'2', 'Accepted'), (b'3', 'Declined')],
),
),
(
'description',
models.TextField(
max_length=2000,
verbose_name='Description',
validators=[django.core.validators.MinLengthValidator(40)],
),
),
('name', models.CharField(max_length=200, verbose_name='Name')),
(
'creation_date',
models.DateField(auto_now_add=True, verbose_name='Date', null=True),
),
],
options={
'ordering': ['name'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ExerciseCategory',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('name', models.CharField(max_length=100, verbose_name='Name')),
],
options={
'ordering': ['name'],
'verbose_name_plural': 'Exercise Categories',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ExerciseComment',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'comment',
models.CharField(
help_text='A comment about how to correctly do this exercise.',
max_length=200,
verbose_name='Comment',
),
),
(
'exercise',
models.ForeignKey(
editable=False,
to='exercises.Exercise',
verbose_name='Exercise',
on_delete=models.CASCADE,
),
),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name='ExerciseImage',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'license_author',
models.CharField(
help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.',
max_length=50,
null=True,
verbose_name='Author',
blank=True,
),
),
(
'status',
models.CharField(
default=b'1',
max_length=2,
editable=False,
choices=[(b'1', 'Pending'), (b'2', 'Accepted'), (b'3', 'Declined')],
),
),
(
'image',
models.ImageField(
help_text='Only PNG and JPEG formats are supported',
upload_to=wger.exercises.models.image.exercise_image_upload_dir,
verbose_name='Image',
),
),
(
'is_main',
models.BooleanField(
default=False,
help_text='Tick the box if you want to set this image as the main one for the exercise (will be shown e.g. in the search). The first image is automatically marked by the system.',
verbose_name='Is main picture',
),
),
(
'exercise',
models.ForeignKey(
verbose_name='Exercise', to='exercises.Exercise', on_delete=models.CASCADE
),
),
(
'license',
models.ForeignKey(
default=2,
verbose_name='License',
to='core.License',
on_delete=models.CASCADE,
),
),
],
options={
'ordering': ['-is_main', 'id'],
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Muscle',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
(
'name',
models.CharField(
help_text='In latin, e.g. "Pectoralis major"',
max_length=50,
verbose_name='Name',
),
),
('is_front', models.BooleanField(default=1)),
],
options={
'ordering': ['name'],
},
bases=(models.Model,),
),
migrations.AddField(
model_name='exercise',
name='category',
field=models.ForeignKey(
verbose_name='Category', to='exercises.ExerciseCategory', on_delete=models.CASCADE
),
preserve_default=True,
),
migrations.AddField(
model_name='exercise',
name='equipment',
field=models.ManyToManyField(
to='exercises.Equipment', null=True, verbose_name='Equipment', blank=True
),
preserve_default=True,
),
migrations.AddField(
model_name='exercise',
name='language',
field=models.ForeignKey(
verbose_name='Language', to='core.Language', on_delete=models.CASCADE
),
preserve_default=True,
),
migrations.AddField(
model_name='exercise',
name='license',
field=models.ForeignKey(
default=2, verbose_name='License', to='core.License', on_delete=models.CASCADE
),
preserve_default=True,
),
migrations.AddField(
model_name='exercise',
name='muscles',
field=models.ManyToManyField(
to='exercises.Muscle', null=True, verbose_name='Primary muscles', blank=True
),
preserve_default=True,
),
migrations.AddField(
model_name='exercise',
name='muscles_secondary',
field=models.ManyToManyField(
related_name='secondary_muscles',
null=True,
verbose_name='Secondary muscles',
to='exercises.Muscle',
blank=True,
),
preserve_default=True,
),
]
| 9,290 | Python | .py | 261 | 18.501916 | 203 | 0.403213 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,698 | 0029_full_text_search.py | wger-project_wger/wger/exercises/migrations/0029_full_text_search.py | # Generated by Django 4.2.6 on 2024-01-18 16:55
import django.contrib.postgres.search
from django.contrib.postgres.operations import TrigramExtension, BtreeGinExtension
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exercises', '0028_add_uuid_alias_and_comments'),
]
operations = [
BtreeGinExtension(),
TrigramExtension(),
migrations.AddIndex(
model_name='exercise',
index=django.contrib.postgres.indexes.GinIndex(
fields=['name'],
name='exercises_e_name_ac11f4_gin',
),
),
migrations.AddIndex(
model_name='alias',
index=django.contrib.postgres.indexes.GinIndex(
fields=['alias'], name='exercises_a_alias_227e38_gin'
),
),
]
| 873 | Python | .py | 25 | 26.08 | 82 | 0.620853 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,699 | 0010_auto_20201211_0205.py | wger-project_wger/wger/exercises/migrations/0010_auto_20201211_0205.py | # Generated by Django 3.1.4 on 2020-12-11 01:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('exercises', '0009_auto_20201211_0139'),
]
operations = [
migrations.RemoveField(
model_name='exercise',
name='equipment',
),
migrations.RemoveField(
model_name='exercise',
name='muscles',
),
migrations.RemoveField(
model_name='exercise',
name='muscles_secondary',
),
migrations.RemoveField(
model_name='exercise',
name='category',
),
migrations.RemoveField(
model_name='exercise',
name='variations',
),
]
| 772 | Python | .py | 28 | 18.428571 | 49 | 0.548649 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |