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,700
0026_deletionlog_replaced_by.py
wger-project_wger/wger/exercises/migrations/0026_deletionlog_replaced_by.py
# Generated by Django 4.1.9 on 2023-10-19 11:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('exercises', '0025_rename_update_date_exercise_last_update_and_more'), ] operations = [ migrations.AddField( model_name='deletionlog', name='replaced_by', field=models.UUIDField( default=None, editable=False, help_text='UUID of the object ', null=True, verbose_name='Replaced by', ), ), ]
607
Python
.py
19
21.894737
79
0.556507
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,701
0018_delete_pending_exercises.py
wger-project_wger/wger/exercises/migrations/0018_delete_pending_exercises.py
# Generated by Django 3.2.15 on 2022-08-25 17:25 from django.db import migrations from django.conf import settings def delete_pending_bases(apps, schema_editor): """ Delete all pending bases Note that we can't access STATUS_PENDING here because we are not using a real model. """ Base = apps.get_model('exercises', 'ExerciseBase') Base.objects.filter(status='1').delete() def delete_pending_translations(apps, schema_editor): """ Delete all pending translations Note that we can't access STATUS_PENDING here because we are not using a real model. """ Exercise = apps.get_model('exercises', 'Exercise') Exercise.objects.filter(status='1').delete() class Migration(migrations.Migration): dependencies = [ ('core', '0014_merge_20210818_1735'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('exercises', '0017_muscle_name_en'), ] operations = [ migrations.RunPython(delete_pending_bases), migrations.RunPython(delete_pending_translations), ]
1,074
Python
.py
29
31.827586
74
0.704348
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,702
0002_auto_20150307_1841.py
wger-project_wger/wger/exercises/migrations/0002_auto_20150307_1841.py
# -*- coding: utf-8 -*- from django.db import models, migrations import uuid def generate_uuids(apps, schema_editor): """ Generate new UUIDs for each exercise :param apps: :param schema_editor: :return: """ Excercise = apps.get_model('exercises', 'Exercise') for exercise in Excercise.objects.all(): exercise.uuid = uuid.uuid4() exercise.save() class Migration(migrations.Migration): dependencies = [ ('exercises', '0001_initial'), ] operations = [ migrations.AddField( model_name='exercise', name='uuid', field=models.CharField( editable=False, max_length=36, verbose_name='UUID', default=uuid.uuid4 ), preserve_default=True, ), migrations.RunPython(generate_uuids), ]
848
Python
.py
29
22.103448
86
0.610086
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,703
0030_increase_author_field_length.py
wger-project_wger/wger/exercises/migrations/0030_increase_author_field_length.py
# Generated by Django 4.2.6 on 2024-05-20 19:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('exercises', '0029_full_text_search'), ] 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.', max_length=3500, 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=3500, 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=3500, 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=3500, 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=3500, 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=3500, 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=3500, 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=3500, null=True, verbose_name='Author(s)', ), ), ]
3,340
Python
.py
96
21.5
86
0.496914
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,704
0003_auto_20160921_2000.py
wger-project_wger/wger/exercises/migrations/0003_auto_20160921_2000.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-09-21 18:00 from django.db import migrations, models def copy_name(apps, schema_editor): """ Copies the exercise name to the original name field """ Excercise = apps.get_model('exercises', 'Exercise') for exercise in Excercise.objects.all(): exercise.name_original = exercise.name exercise.save() def capitalize_name(apps, schema_editor): """ Capitalizes the name of the exercises The algorithm is copied here as it was implemented on the day the migration was written. """ def capitalize(input): out = [] for word in input.split(' '): if len(word) > 2 and word[0] != 'ß': out.append(word[:1].upper() + word[1:]) else: out.append(word) return ' '.join(out) Excercise = apps.get_model('exercises', 'Exercise') for exercise in Excercise.objects.all(): exercise.name = capitalize(exercise.name_original) exercise.save() class Migration(migrations.Migration): dependencies = [ ('exercises', '0002_auto_20150307_1841'), ] operations = [ migrations.AddField( model_name='exercise', name='name_original', field=models.CharField(default='', max_length=200, verbose_name='Name'), ), migrations.RunPython(copy_name, reverse_code=migrations.RunPython.noop), migrations.RunPython(capitalize_name, reverse_code=migrations.RunPython.noop), ]
1,556
Python
.py
42
29.690476
86
0.634731
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,705
0007_auto_20201203_1042.py
wger-project_wger/wger/exercises/migrations/0007_auto_20201203_1042.py
# Generated by Django 3.1.3 on 2020-12-03 09:42 from django.db import migrations exercise_variation_ids = [ # # exercises in English # # Rows [106, 108, 109, 110, 142, 202, 214, 339, 340, 362, 412, 670], # Lat Pulldowns [187, 188, 204, 212, 213, 215, 216, 424], # Deadlifts [105, 161, 209, 328, 351, 381], # Shoulder Raises [148, 149, 233, 237, 306, 421], # "Shoulder Press" [119, 123, 152, 155, 190, 227, 228, 229, 329], # "Calf Raises" [102, 103, 104, 776], # "Bench Press" [100, 101, 163, 192, 210, 211, 270, 399], # "Pushups" [168, 182, 260, 302, 790], # "Chest Fly" [122, 145, 146, 206], # "Crunches" [91, 92, 93, 94, 176, 416, 95, 170], # "Kicks" [303, 631, 125, 126, 166], # "Squats" [111, 160, 185, 191, 300, 342, 346, 355, 387, 389, 407, 650, 795], # "Lunges" [112, 113, 346, 405], # "Leg Curls" [117, 118, 154, 792], # "Leg Press" [114, 115, 130, 788], # "Bicep Curls" [74, 80, 81, 86, 129, 138, 193, 205, 208, 275, 298, 305, 768], # "Tricep Extensions" [89, 90, 274, 344], # "Tricep Presses" [84, 85, 88, 186, 217, 218, 386], # "Dips" [82, 83, 162, 360], # # exercises in German # # Bizeps Curls [44, 26, 242, 24, 3, 815, 222], # Dips [29, 68], # French press [58, 25], # Hammercurls [46, 134], # Beinpresse [6, 54], # Beinstrecker [39, 69], # Kniebeuge [358, 390, 7, 402, 200, 762, 707], # Beinheben [35, 34], # Crunches [4, 33, 51, 32, 56], # Plank [417, 712], # Bankdrücken [77, 15, 720, 17], # Butterfly [30, 52], # Fliegende [18, 73, 722], # Kabelziehen [252, 252], # Frontziehen [10, 12], # Latzug [ 158, 226, 243, 244, ], # Rudern [245, 59, 70, 224, 76], # Frontdrücken [ 19, 153, 66, ], # Shrugs [8, 137, 67], # Waden [13, 23, 297], ] def insert_variations(apps, schema_editor): """ Forward migration. Add variation data to exercises """ # We can't import the Exercise model directly as it may be a newer # version than this migration expects. We use the historical version. Exercise = apps.get_model('exercises', 'Exercise') Variation = apps.get_model('exercises', 'Variation') for group in exercise_variation_ids: variation = Variation() variation.save() for exercise_id in group: # Exercises won't be found on an empty (new) database, just ignore try: exercise = Exercise.objects.get(pk=exercise_id) exercise.variations = variation exercise.save() except Exercise.DoesNotExist: pass def remove_variations(apps, schema_editor): """ Backwards migration. Removes all variation data. """ Exercise = apps.get_model('exercises', 'Exercise') Exercise.objects.all().update(variations=None) class Migration(migrations.Migration): dependencies = [ ('exercises', '0006_auto_20201203_0203'), ] operations = [ migrations.RunPython(insert_variations, remove_variations), ]
3,303
Python
.py
129
19.782946
78
0.559494
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,706
0028_add_uuid_alias_and_comments.py
wger-project_wger/wger/exercises/migrations/0028_add_uuid_alias_and_comments.py
# Generated by Django 4.2.6 on 2024-01-06 14:01 from django.db import migrations, models import uuid def generate_aliases_uuids(apps, schema_editor): """Generate new UUIDs for each alias""" Alias = apps.get_model('exercises', 'Alias') for alias in Alias.objects.all(): alias.uuid = uuid.uuid4() alias.save(update_fields=['uuid']) def generate_comments_uuids(apps, schema_editor): """Generate new UUIDs for each comment""" Comment = apps.get_model('exercises', 'ExerciseComment') for comment in Comment.objects.all(): comment.uuid = uuid.uuid4() comment.save(update_fields=['uuid']) class Migration(migrations.Migration): dependencies = [ ('exercises', '0027_alter_deletionlog_replaced_by_and_more'), ] operations = [ migrations.AddField( model_name='exercisecomment', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=False, verbose_name='UUID', ), ), migrations.AddField( model_name='historicalexercisecomment', name='uuid', field=models.UUIDField( db_index=True, default=uuid.uuid4, editable=False, verbose_name='UUID', ), ), migrations.AddField( model_name='alias', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=False, verbose_name='UUID', ), ), migrations.AddField( model_name='historicalalias', name='uuid', field=models.UUIDField( db_index=True, default=uuid.uuid4, editable=False, verbose_name='UUID', ), ), migrations.RunPython( generate_aliases_uuids, reverse_code=migrations.RunPython.noop, ), migrations.RunPython( generate_comments_uuids, reverse_code=migrations.RunPython.noop, ), migrations.AlterField( model_name='exercisecomment', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID', ), ), migrations.AlterField( model_name='alias', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID', ), ), ]
2,820
Python
.py
89
20.146067
69
0.522969
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,707
0015_exercise_videos.py
wger-project_wger/wger/exercises/migrations/0015_exercise_videos.py
# Generated by Django 3.2.10 on 2022-01-22 14:18 from django.db import migrations, models import django.db.models.deletion import uuid import wger.exercises.models.video class Migration(migrations.Migration): dependencies = [ ('core', '0013_auto_20210726_1729'), ('exercises', '0014_exerciseimage_style'), ] operations = [ migrations.AlterField( model_name='exerciseimage', name='style', field=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, ), ), migrations.CreateModel( name='ExerciseVideo', 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', ), ), ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')), ('is_main', models.BooleanField(default=False, verbose_name='Main video')), ( 'video', models.FileField( upload_to=wger.exercises.models.video.exercise_video_upload_dir, 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' ), ), ( 'exercise_base', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='exercises.exercisebase', verbose_name='Exercise', ), ), ( 'license', models.ForeignKey( default=2, on_delete=django.db.models.deletion.CASCADE, to='core.license', verbose_name='License', ), ), ], options={ 'ordering': ['-is_main', 'id'], }, ), ]
3,962
Python
.py
104
20.365385
146
0.411002
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,708
0005_auto_20190618_1617.py
wger-project_wger/wger/exercises/migrations/0005_auto_20190618_1617.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.21 on 2019-06-18 16:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('exercises', '0004_auto_20170404_0114'), ] operations = [ migrations.AlterModelOptions( name='exercise', options={'base_manager_name': 'objects', 'ordering': ['name']}, ), migrations.AlterModelOptions( name='exerciseimage', options={'base_manager_name': 'objects', 'ordering': ['-is_main', 'id']}, ), ]
575
Python
.py
17
26.470588
85
0.590253
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,709
0011_auto_20201214_0033.py
wger-project_wger/wger/exercises/migrations/0011_auto_20201214_0033.py
# Generated by Django 3.1.4 on 2020-12-13 23:33 from django.db import migrations exercise_mapping = [ # 111 c4856da3-8454-4857-8997-336d06df590f Squats # 7 36c27886-b10b-41b6-ac60-f02ee3784041 Kniebeuge # 608 993cf4e0-e664-4cc2-aa46-683c6fc7a74f Приседания { 'en': 'c4856da3-8454-4857-8997-336d06df590f', 'de': '36c27886-b10b-41b6-ac60-f02ee3784041', 'ru': '993cf4e0-e664-4cc2-aa46-683c6fc7a74f', }, # 160 b1d6d536-7f4a-4dd3-8b76-62d7a984e115 Pistol Squat # 358 40a0019e-eaf2-491f-a134-9fdd51121358 Einbeinige Kniebeuge (Pistol Squat) {'en': 'b1d6d536-7f4a-4dd3-8b76-62d7a984e115', 'de': '40a0019e-eaf2-491f-a134-9fdd51121358'}, # 346 1d90f3a8-56e4-4c15-a4b4-94fc0e114e8c Bulgarian Split Squat # 695 cf21383b-b96a-40b5-b047-b9c3ddcab963 Bulgarian Split Squat {'en': '1d90f3a8-56e4-4c15-a4b4-94fc0e114e8c', 'de': 'cf21383b-b96a-40b5-b047-b9c3ddcab963'}, # 202 eed05679-d1cb-44a2-a17d-dd5b0097c874 Pendelay Rows # 731 196f9a72-7518-45c4-a4f2-d3ba3e0d3b3e Pendelay Rows {'en': 'eed05679-d1cb-44a2-a17d-dd5b0097c874', 'de': '196f9a72-7518-45c4-a4f2-d3ba3e0d3b3e'}, # 130 2966e4a2-4306-4cb5-a2dc-8951cd192555 Leg Press on Hackenschmidt Machine # 402 634dcf89-c346-4af8-8b09-61f238798877 Kniebeuge an Hackenschmidtmaschine {'en': '2966e4a2-4306-4cb5-a2dc-8951cd192555', 'de': '634dcf89-c346-4af8-8b09-61f238798877'}, # 104 e7677699-5e4f-49e6-a645-e8915a203c4d Calf Raises on Hackenschmitt Machine # 23 c7b98fb5-7723-471a-92a1-7b4e892a5468 Wadenheben an Hackenschmidt {'en': 'e7677699-5e4f-49e6-a645-e8915a203c4d', 'de': 'c7b98fb5-7723-471a-92a1-7b4e892a5468'}, # 105 22cca8fc-cfaf-4941-b0f7-faf9f2937c52 Deadlifts # 9 521a5e4f-6f35-43e5-9d1c-6e75c4956e96 Kreuzheben {'en': '22cca8fc-cfaf-4941-b0f7-faf9f2937c52', 'de': '521a5e4f-6f35-43e5-9d1c-6e75c4956e96'}, # 570 f4dd363c-b49c-419a-b8ae-0d8e18728d8e Sumo Squats # 762 b399006c-bb45-451e-908e-1b279b2a42a6 Sumo Squats (Pilé Squats) Kniebeuge {'en': 'f4dd363c-b49c-419a-b8ae-0d8e18728d8e', 'de': 'b399006c-bb45-451e-908e-1b279b2a42a6'}, # 91 d325dd5c-6833-41c7-8eea-6b95c4871133 Crunches # 4 0e10ac9b-ed1d-42c9-b8cc-123c22ccc5d5 Crunches {'en': 'd325dd5c-6833-41c7-8eea-6b95c4871133', 'de': '0e10ac9b-ed1d-42c9-b8cc-123c22ccc5d5'}, # 92 8d6c13c6-256d-4137-b1c6-b0e817697639 Crunches With Cable # 33 5c47b690-d19f-4523-9c47-47160693eefc Crunches am Seil {'en': '8d6c13c6-256d-4137-b1c6-b0e817697639', 'de': '5c47b690-d19f-4523-9c47-47160693eefc'}, # 94 6709577b-95ec-4053-a822-d5fe1f753966 Crunches on Machine # 51 efbece79-4384-49d1-bb88-e16fcd8de5aa Crunches an Maschine {'en': '6709577b-95ec-4053-a822-d5fe1f753966', 'de': 'efbece79-4384-49d1-bb88-e16fcd8de5aa'}, # 307 1b8b1657-40fd-4e3b-97b7-1c79b1079f8e Bear Walk # 718 e4b3da5b-1803-42af-a50e-ffbac3853cd0 Bear Walk {'en': '1b8b1657-40fd-4e3b-97b7-1c79b1079f8e', 'de': 'e4b3da5b-1803-42af-a50e-ffbac3853cd0'}, # 192 5da6340b-22ec-4c1b-a443-eef2f59f92f0 Bench Press # 15 198dcb2e-e35f-4b69-ae8b-e1124d438eae Bankdrücken LH {'en': '5da6340b-22ec-4c1b-a443-eef2f59f92f0', 'de': '198dcb2e-e35f-4b69-ae8b-e1124d438eae'}, # 88 03d821e7-e1ac-4026-903b-d406381cbf76 Bench Press Narrow Grip # 38 4def60e7-ed8d-4a9d-bf76-ceb15ecf9779 Bankdrücken Eng {'en': '03d821e7-e1ac-4026-903b-d406381cbf76', 'de': '4def60e7-ed8d-4a9d-bf76-ceb15ecf9779'}, # 97 0ec76f5d-1311-4d6d-bf79-00fa17c3061a Benchpress Dumbbells # 77 06450bcb-03a8-4bd7-8349-ef677ee57ea3 Bankdrücken KH {'en': '0ec76f5d-1311-4d6d-bf79-00fa17c3061a', 'de': '06450bcb-03a8-4bd7-8349-ef677ee57ea3'}, # 129 8c6c1544-cbf8-403c-ae12-b27b392702f8 Biceps Curl With Cable # 3 ef487de3-f071-41bf-85a6-6e76afe9c732 Bizeps am Kabel {'en': '8c6c1544-cbf8-403c-ae12-b27b392702f8', 'de': 'ef487de3-f071-41bf-85a6-6e76afe9c732'}, # 80 38919515-ce04-4383-9c3f-5846edd0e844 Biceps Curls With SZ-bar # 44 8277124a-9ef2-442a-9824-7ab4439a5f1f Bizeps Curls Mit ß-Stange {'en': '38919515-ce04-4383-9c3f-5846edd0e844', 'de': '8277124a-9ef2-442a-9824-7ab4439a5f1f'}, # 74 c56078d2-ae85-4524-a467-d1e143b6df1a Biceps Curls With Barbell # 24 2e3fa138-3894-4f61-959a-d8966804a1a3 Bizeps LH-Curls {'en': 'c56078d2-ae85-4524-a467-d1e143b6df1a', 'de': '2e3fa138-3894-4f61-959a-d8966804a1a3'}, # 275 dfa090e4-77ae-40ed-86c0-4696fe93dcf1 Dumbbell Concentration Curl # 681 ec0c53a5-15b9-4c2f-ac7c-00888db9f8ee Konzentrations-Curls {'en': 'dfa090e4-77ae-40ed-86c0-4696fe93dcf1', 'de': 'ec0c53a5-15b9-4c2f-ac7c-00888db9f8ee'}, # 86 6dcc9adb-939c-4581-9e44-d0d73753997b Hammercurls # 46 ff454f5a-70ee-40fb-9200-5e7e42960ef0 Hammercurls {'en': '6dcc9adb-939c-4581-9e44-d0d73753997b', 'de': 'ff454f5a-70ee-40fb-9200-5e7e42960ef0'}, # 138 5baf40e5-ea3c-4f8d-b60a-d294ee2de55b Hammercurls on Cable # 134 06e9de49-ac1b-45c1-b289-475118932434 Hammercurls am Seil {'en': '5baf40e5-ea3c-4f8d-b60a-d294ee2de55b', 'de': '06e9de49-ac1b-45c1-b289-475118932434'}, # 771 bdcae845-6726-457f-8e04-203754a78e1c Reverse Curl # 815 7662a76a-3ea7-4b63-86d9-c0702b554090 Reverse Curls {'en': 'bdcae845-6726-457f-8e04-203754a78e1c', 'de': '7662a76a-3ea7-4b63-86d9-c0702b554090'}, # 298 fa56d30a-7a8f-4084-aa68-46bd52f97959 Dumbbell Incline Curl # 242 0842e81e-7b90-4d68-8e6b-e9a7c0186b54 Bizeps KH-Curls Schrägbank {'en': 'fa56d30a-7a8f-4084-aa68-46bd52f97959', 'de': '0842e81e-7b90-4d68-8e6b-e9a7c0186b54'}, # 81 48a59aa8-4568-409c-8afe-f8cb99c558ea Biceps Curls With Dumbbell # 26 8cbbffcc-1989-43de-9200-03869480398c Bizeps KH-Curls {'en': '48a59aa8-4568-409c-8afe-f8cb99c558ea', 'de': '8cbbffcc-1989-43de-9200-03869480398c'}, # 227 53ca25b3-61d9-4f72-bfdb-492b83484ff5 Arnold Shoulder Press # 228 880bff63-6798-4ffc-a818-b2a1ccfec0f7 Arnold Press {'en': '53ca25b3-61d9-4f72-bfdb-492b83484ff5', 'de': '880bff63-6798-4ffc-a818-b2a1ccfec0f7'}, # 150 3721be0c-2a59-4bb9-90d3-695faaf028af Shrugs, Barbells # 137 a63d40df-a872-44e7-87d2-9b58b67d5406 Shrugs (Schulterheben) Mit LH {'en': '3721be0c-2a59-4bb9-90d3-695faaf028af', 'de': 'a63d40df-a872-44e7-87d2-9b58b67d5406'}, # 151 ee61aef0-f0c7-4a7a-882a-3b39312dfffd Shrugs, Dumbbells # 8 6dde45fc-7fdf-4523-a039-9c373677a750 Shrugs (Schulterheben) Mit KH {'en': 'ee61aef0-f0c7-4a7a-882a-3b39312dfffd', 'de': '6dde45fc-7fdf-4523-a039-9c373677a750'}, # 387 b229c57f-5363-41e2-add7-c2501a31de0b Wall Squat # 707 7f3e45fa-3b17-4cdb-90d5-cb9957212cbf Wall Squat {'en': 'b229c57f-5363-41e2-add7-c2501a31de0b', 'de': '7f3e45fa-3b17-4cdb-90d5-cb9957212cbf'}, # 93 4bd55b0a-559a-4458-aabd-e66619b63610 Negative Crunches # 32 f5e98b51-6c0e-4c77-94ec-158210669f6d Crunches an Negativbank {'en': '4bd55b0a-559a-4458-aabd-e66619b63610', 'de': 'f5e98b51-6c0e-4c77-94ec-158210669f6d'}, # 330 6572a8e9-083c-4622-8f0c-6107a013a490 Superman # 735 bd58585e-4bf4-46cc-ba38-717a7857e21c Superman {'en': '6572a8e9-083c-4622-8f0c-6107a013a490', 'de': 'bd58585e-4bf4-46cc-ba38-717a7857e21c'}, # 238 7729ffe5-a896-4deb-80e0-f4e6163c0c09 Plank # 417 257cdb33-ba8b-410a-9396-5132b08dc912 Unterarmstütze - Plank {'en': '7729ffe5-a896-4deb-80e0-f4e6163c0c09', 'de': '257cdb33-ba8b-410a-9396-5132b08dc912'}, # 325 a36f852f-a29f-4f93-81b6-1012047ac1ee Side Plank # 715 2c6cd166-40e1-4b68-96b7-c30b31e28b99 Side Plank {'en': 'a36f852f-a29f-4f93-81b6-1012047ac1ee', 'de': '2c6cd166-40e1-4b68-96b7-c30b31e28b99'}, # 116 6e862700-3d63-486c-99ae-744c68d2f753 Good Mornings # 50 a311a463-f219-4741-b4fb-247013dc8dd8 Good Mornings {'en': '6e862700-3d63-486c-99ae-744c68d2f753', 'de': 'a311a463-f219-4741-b4fb-247013dc8dd8'}, # 326 bf9e572d-d138-43e9-a486-a5c6ad9033f8 Full Sit Outs # 710 143cf744-ce94-458c-9c74-1aea6c64cfc7 Full Sit Outs {'en': 'bf9e572d-d138-43e9-a486-a5c6ad9033f8', 'de': '143cf744-ce94-458c-9c74-1aea6c64cfc7'}, # 95 fb750082-7034-4c51-b1e4-dfa0fe2dac8e Sit-ups # 57 60f329dd-f8ab-469a-8a88-39f80275b3a7 Sit Ups {'en': 'fb750082-7034-4c51-b1e4-dfa0fe2dac8e', 'de': '60f329dd-f8ab-469a-8a88-39f80275b3a7'}, # 83 aa4fcd9b-baee-41cf-b4c5-8462bc43a8be Dips Between Two Benches # 68 011b956d-33b3-4600-9e42-2e7dcbac9fb5 Dips Zwischen 2 Bänke {'en': 'aa4fcd9b-baee-41cf-b4c5-8462bc43a8be', 'de': '011b956d-33b3-4600-9e42-2e7dcbac9fb5'}, # 354 6335de72-146f-4f38-886d-6b8a27db62ff Burpees # 719 5bae16b0-cefb-4fc7-be2b-e31794335c42 Burpees {'en': '6335de72-146f-4f38-886d-6b8a27db62ff', 'de': '5bae16b0-cefb-4fc7-be2b-e31794335c42'}, # 289 6add5973-86d0-4543-928a-6bb8b3f34efc Axe Hold # 677 8e9d8968-323d-468c-9174-8cf11a105fad Axe Hold {'en': '6add5973-86d0-4543-928a-6bb8b3f34efc', 'de': '8e9d8968-323d-468c-9174-8cf11a105fad'}, # 98 3c3857f8-d224-4d5a-8cc1-f4e7982d3475 Butterfly # 30 9df24c6f-016b-4623-8878-f71c235c50fa Butterfly {'en': '3c3857f8-d224-4d5a-8cc1-f4e7982d3475', 'de': '9df24c6f-016b-4623-8878-f71c235c50fa'}, # 99 08637e04-d995-4c07-b021-a20f26b6fd97 Butterfly Narrow Grip # 52 44b0d79a-5c5b-43df-bf62-3e67148f1c33 Butterfly Eng {'en': '08637e04-d995-4c07-b021-a20f26b6fd97', 'de': '44b0d79a-5c5b-43df-bf62-3e67148f1c33'}, # 124 8715a96e-c8a2-458a-b023-4ea7d82fdab8 Butterfly Reverse # 21 605b4a25-bc1d-4604-bd93-c85b2aaf84ae Butterfly Reverse {'en': '8715a96e-c8a2-458a-b023-4ea7d82fdab8', 'de': '605b4a25-bc1d-4604-bd93-c85b2aaf84ae'}, # 394 659f3fb9-2370-42fb-9c29-9aaf65c7a7de Facepull # 415 237c8770-4c1f-433d-b8b4-b1ae5c69bbc5 Face Pulls {'en': '659f3fb9-2370-42fb-9c29-9aaf65c7a7de', 'de': '237c8770-4c1f-433d-b8b4-b1ae5c69bbc5'}, # 281 e1881607-9418-4bcc-8c69-2301a579637e L Hold # 753 6ae461d7-daea-4ac7-999b-826fe28263b0 L Hold {'en': 'e1881607-9418-4bcc-8c69-2301a579637e', 'de': '6ae461d7-daea-4ac7-999b-826fe28263b0'}, # 143 b192c4eb-31c6-458e-b566-d3f38b5aa30c Long-Pulley (low Row) # 37 91fa0487-b137-4bef-86cf-39816cd5ee48 Long-Pulley {'en': 'b192c4eb-31c6-458e-b566-d3f38b5aa30c', 'de': '91fa0487-b137-4bef-86cf-39816cd5ee48'}, # 144 bcabc8cf-c005-4630-8853-ef4922e7fd91 Long-Pulley, Narrow # 136 490a615c-4185-4560-88a5-020f3aa40be2 Long-Pulley (eng) {'en': 'bcabc8cf-c005-4630-8853-ef4922e7fd91', 'de': '490a615c-4185-4560-88a5-020f3aa40be2'}, # 103 399666e7-30a7-4b86-833d-4422e4c72b61 Sitting Calf Raises # 14 47b4d57a-3bb3-4a03-a522-a0559a254730 Wadenheben Sitzend {'en': '399666e7-30a7-4b86-833d-4422e4c72b61', 'de': '47b4d57a-3bb3-4a03-a522-a0559a254730'}, # 102 abc4c62e-27b2-4c31-8766-40f8dca84cab Standing Calf Raises # 13 283d4ec5-1b29-41bb-997d-74c30e7a68b5 Wadenheben Stehend {'en': 'abc4c62e-27b2-4c31-8766-40f8dca84cab', 'de': '283d4ec5-1b29-41bb-997d-74c30e7a68b5'}, # 308 074530d6-801a-404b-b3b7-adc207be69be Calf Press Using Leg Press Machine # 745 84afd45e-235a-41c3-8711-ea9f6d08eeb6 Wadendrücken an Beinpresse {'en': '074530d6-801a-404b-b3b7-adc207be69be', 'de': '84afd45e-235a-41c3-8711-ea9f6d08eeb6'}, # 85 ee00d53e-4482-44aa-b780-bbc570061841 French Press (skullcrusher) Dumbbells # 58 bdf8997a-84ce-434a-ae95-1f9fc50f43bb Frenchpress KH {'en': 'ee00d53e-4482-44aa-b780-bbc570061841', 'de': 'bdf8997a-84ce-434a-ae95-1f9fc50f43bb'}, # 84 ee4a350b-c681-407f-a414-6ec243809ec7 French Press (skullcrusher) SZ-bar # 25 9972e42d-43d8-43c0-b547-4638ca3e47be Frenchpress ß-Stange {'en': 'ee4a350b-c681-407f-a414-6ec243809ec7', 'de': '9972e42d-43d8-43c0-b547-4638ca3e47be'}, # 788 6c8e863c-f6c2-4ad0-a0e9-5e6d9e6a928b Leg Press # 6 a27cfdd9-5299-49ab-85f5-6e4042657549 Beinpresse {'en': '6c8e863c-f6c2-4ad0-a0e9-5e6d9e6a928b', 'de': 'a27cfdd9-5299-49ab-85f5-6e4042657549'}, # 115 560e1a20-33e1-45db-ba5b-63f8c51af76d Leg Presses (narrow) # 54 e7d0cc2d-e28b-479f-91d9-7eab7b686fd8 Beinpresse Eng {'en': '560e1a20-33e1-45db-ba5b-63f8c51af76d', 'de': 'e7d0cc2d-e28b-479f-91d9-7eab7b686fd8'}, # 112 587c0052-f2bc-48ca-8af9-415175308901 Dumbbell Lunges Standing # 55 27301836-ed7f-4510-83e7-66c0b8041a44 Ausfallschritte Stehend # 363 c38e34a7-5560-46a1-bae4-c4fce9619e55 Výpad Statický { 'en': '587c0052-f2bc-48ca-8af9-415175308901', 'de': '27301836-ed7f-4510-83e7-66c0b8041a44', 'cs': 'c38e34a7-5560-46a1-bae4-c4fce9619e55', }, # 113 ffd4ce7e-e14f-49d4-9dc9-dc1362631382 Dumbbell Lunges Walking # 5 5675ae61-6597-4806-ae5c-2dda5a5ac03c Ausfallschritte im Gehen {'en': 'ffd4ce7e-e14f-49d4-9dc9-dc1362631382', 'de': '5675ae61-6597-4806-ae5c-2dda5a5ac03c'}, # 145 754391c6-39d5-4bb6-a311-68a520f6fd3a Fly With Dumbbells # 18 c0119734-a412-4f34-91f1-cd1c1177fcb8 Fliegende KH Flachbank {'en': '754391c6-39d5-4bb6-a311-68a520f6fd3a', 'de': 'c0119734-a412-4f34-91f1-cd1c1177fcb8'}, # 146 acf1f2df-46c4-49a3-8e6c-2979ea4204b1 Fly With Dumbbells, Decline Bench # 73 3b34d81d-7882-46a6-bb83-40f84d3f8300 Fliegende KH Schrägbank {'en': 'acf1f2df-46c4-49a3-8e6c-2979ea4204b1', 'de': '3b34d81d-7882-46a6-bb83-40f84d3f8300'}, # 409 75ec610d-216a-49fe-b395-c5fd8ee14b53 Reverse Plank # 713 24e5637e-60eb-41f5-b964-31e2af990bfc Reverse Plank {'en': '75ec610d-216a-49fe-b395-c5fd8ee14b53', 'de': '24e5637e-60eb-41f5-b964-31e2af990bfc'}, # 181 f6c4e2fa-226d-46e8-87dc-75fc8cd628bd Chin-ups # 747 9e71d2a3-9021-4270-a7b9-0d8bd28e7394 Chin-ups {'en': 'f6c4e2fa-226d-46e8-87dc-75fc8cd628bd', 'de': '9e71d2a3-9021-4270-a7b9-0d8bd28e7394'}, # 346 1d90f3a8-56e4-4c15-a4b4-94fc0e114e8c Bulgarian Split Squat # 695 cf21383b-b96a-40b5-b047-b9c3ddcab963 Bulgarian Split Squat {'en': '1d90f3a8-56e4-4c15-a4b4-94fc0e114e8c', 'de': 'cf21383b-b96a-40b5-b047-b9c3ddcab963'}, # 781 7191e015-0c60-4376-9be0-733b9754b7f8 Dips # 29 41b495fd-562e-4d6e-942a-60dc52d5e194 Dips {'en': '7191e015-0c60-4376-9be0-733b9754b7f8', 'de': '41b495fd-562e-4d6e-942a-60dc52d5e194'}, # 279 88568115-5e88-4afc-b005-e2f7d453ac13 Tricep Dumbbell Kickback # 232 ebe60386-bf33-4f50-87a6-d44c5f454158 Kick-Backs {'en': '88568115-5e88-4afc-b005-e2f7d453ac13', 'de': 'ebe60386-bf33-4f50-87a6-d44c5f454158'}, # 128 f57a0c60-7d37-4eb3-a94e-1a90292e8c02 Hyperextensions # 60 913d71cc-ba7a-4902-bfa8-3c5203129d72 Hyperextensions {'en': 'f57a0c60-7d37-4eb3-a94e-1a90292e8c02', 'de': '913d71cc-ba7a-4902-bfa8-3c5203129d72'}, # 195 9d756e84-6b77-4f17-b21d-7d266d6a8bd2 Push Ups # 172 35871103-6cfe-493f-afe1-8401f88fed84 Liegestütz {'en': '9d756e84-6b77-4f17-b21d-7d266d6a8bd2', 'de': '35871103-6cfe-493f-afe1-8401f88fed84'}, # 260 36ef5f12-6f77-4754-a926-39915e4b57a5 Decline Pushups # 721 e386cd27-aef6-4565-88ad-639b0ea04e3a Negativ Pushups {'en': '36ef5f12-6f77-4754-a926-39915e4b57a5', 'de': 'e386cd27-aef6-4565-88ad-639b0ea04e3a'}, # 139 88bbdbde-c9b6-45a1-aee9-efc6f02cfab3 Triceps Machine # 27 ca03dd79-4a92-47ef-a461-e67ccc406f82 Trizepsmaschine {'en': '88bbdbde-c9b6-45a1-aee9-efc6f02cfab3', 'de': 'ca03dd79-4a92-47ef-a461-e67ccc406f82'}, # 338 20b88059-3958-4184-9134-b48656ad868d Isometric Wipers # 724 666d1c77-d74b-411c-be3e-1e60a02c548d Isometric Wipers {'en': '20b88059-3958-4184-9134-b48656ad868d', 'de': '666d1c77-d74b-411c-be3e-1e60a02c548d'}, # 90 20a76bd0-1e56-4a4e-bd79-0ab118552bde Triceps Extensions on Cable With Bar # 63 60aab5bf-ff7a-4e50-9e92-1f4813c3da75 Trizeps Seildrücken Mit Stange {'en': '20a76bd0-1e56-4a4e-bd79-0ab118552bde', 'de': '60aab5bf-ff7a-4e50-9e92-1f4813c3da75'}, # 89 f1b5e525-6232-4d60-a243-9b2cd6c55298 Triceps Extensions on Cable # 1 b83e3d85-a53d-4939-a61c-7baa2e94d358 Trizeps Seildrücken {'en': 'f1b5e525-6232-4d60-a243-9b2cd6c55298', 'de': 'b83e3d85-a53d-4939-a61c-7baa2e94d358'}, # 270 625aefd5-7ba2-40e9-bdc3-7d3ab1bcf3b8 Pause Bench # 725 5009eedc-554f-43ef-852e-77ba45a7297c Pause Bench {'en': '625aefd5-7ba2-40e9-bdc3-7d3ab1bcf3b8', 'de': '5009eedc-554f-43ef-852e-77ba45a7297c'}, # 149 79a3a34c-262f-4cae-b827-b5a85b11b860 Lateral Raises on Cable, One Armed # 132 382731d2-ae07-4a3c-a055-09dadd5f12e0 Seitheben am Kabel, Einarmig {'en': '79a3a34c-262f-4cae-b827-b5a85b11b860', 'de': '382731d2-ae07-4a3c-a055-09dadd5f12e0'}, # 148 5345766a-c092-457a-aa21-8ee6ffa855d4 Lateral Raises # 20 72e78f4d-65f7-4ddd-9247-cdc1e133fa80 Seitheben KH {'en': '5345766a-c092-457a-aa21-8ee6ffa855d4', 'de': '72e78f4d-65f7-4ddd-9247-cdc1e133fa80'}, # 191 f2e563d2-507b-4586-88c8-77652cd19648 Front Squats # 390 d23d1980-3a50-4d3f-8123-90d7e55c7804 Front Kniebeuge {'en': 'f2e563d2-507b-4586-88c8-77652cd19648', 'de': 'd23d1980-3a50-4d3f-8123-90d7e55c7804'}, # 229 89e6d2ea-9a17-4a77-9a52-d5bcf39d57fd Military Press # 153 47c33837-be38-4ebb-b19a-84c280f5f2b0 Frontdrücken LH {'en': '89e6d2ea-9a17-4a77-9a52-d5bcf39d57fd', 'de': '47c33837-be38-4ebb-b19a-84c280f5f2b0'}, # 854 37097633-de80-4271-9b7c-291f359e0ef4 Hip Thrust # 230 981ef1f0-414a-478b-bc1b-9c6afa45bc77 Beckenheben {'en': '37097633-de80-4271-9b7c-291f359e0ef4', 'de': '981ef1f0-414a-478b-bc1b-9c6afa45bc77'}, # 177 a24a0521-6391-419c-bd89-795bba0eb5ee Leg Extension # 133 da7fccca-941e-457a-a2eb-d0c56d419938 Beinbeuger Sitzend {'en': 'a24a0521-6391-419c-bd89-795bba0eb5ee', 'de': 'da7fccca-941e-457a-a2eb-d0c56d419938'}, # 109 f82c579e-c069-4dc7-8e36-a3266dfd8e4a Bent Over Rowing # 59 126d719a-4b59-4458-b182-d578cdcfee1a Rudern Vorgebeugt LH {'en': 'f82c579e-c069-4dc7-8e36-a3266dfd8e4a', 'de': '126d719a-4b59-4458-b182-d578cdcfee1a'}, # 108 57747eb3-411a-4efd-8842-a45e562320ee Rowing, Seated # 245 788ef0a5-492f-48a7-87dc-b15dda185bb8 Rudern Eng Zum Bauch {'en': '57747eb3-411a-4efd-8842-a45e562320ee', 'de': '788ef0a5-492f-48a7-87dc-b15dda185bb8'}, # 119 9926e18f-4e2b-4c20-9477-9bfb08d229bc Shoulder Press, Barbell # 266 197600e7-9bb2-448c-baca-244d679e7b07 Schulterdrücken LH {'en': '9926e18f-4e2b-4c20-9477-9bfb08d229bc', 'de': '197600e7-9bb2-448c-baca-244d679e7b07'}, # 123 1df6a1b5-7bd2-402f-9d5e-94f9ed6d8b54 Shoulder Press, Dumbbells # 241 0d4390ea-51dc-42dc-94af-ba0e94a73484 Schulterdrücken KH {'en': '1df6a1b5-7bd2-402f-9d5e-94f9ed6d8b54', 'de': '0d4390ea-51dc-42dc-94af-ba0e94a73484'}, # 107 7ce6b090-5099-4cd0-83ae-1a02725c868b Pull-ups # 36 4e741c73-d40a-4fad-b0e0-76edd9bbe8df Klimmzüge {'en': '7ce6b090-5099-4cd0-83ae-1a02725c868b', 'de': '4e741c73-d40a-4fad-b0e0-76edd9bbe8df'}, # 140 d46adbda-7c60-42a0-b1fd-9ec111b35956 Pull Ups on Machine # 48 22897ebe-cf17-44cf-97e6-87566285684d Klimmzüge an Maschine {'en': 'd46adbda-7c60-42a0-b1fd-9ec111b35956', 'de': '22897ebe-cf17-44cf-97e6-87566285684d'}, # 87 d147a6c2-ce64-424b-baf3-4ca841a51512 Dumbbells on Scott Machine # 28 d7c553b1-e84d-4dbc-9f6c-05db489b27c8 KH an Scottmaschine {'en': 'd147a6c2-ce64-424b-baf3-4ca841a51512', 'de': 'd7c553b1-e84d-4dbc-9f6c-05db489b27c8'}, # 100 b72ae8d4-ede6-4480-8fc5-7b80e369f7ed Decline Bench Press Barbell # 17 3ef8a516-d0d4-4078-9b4a-d7783da0fcf7 Negativ Bankdrücken {'en': 'b72ae8d4-ede6-4480-8fc5-7b80e369f7ed', 'de': '3ef8a516-d0d4-4078-9b4a-d7783da0fcf7'}, # 101 80d318b3-4b8a-41aa-9c6c-0a2a921fe1e6 Decline Bench Press Dumbbell # 720 341c73d5-2e9a-4f13-89c9-c984c86cc088 Negativ Bankdrücken KH {'en': '80d318b3-4b8a-41aa-9c6c-0a2a921fe1e6', 'de': '341c73d5-2e9a-4f13-89c9-c984c86cc088'}, # 318 bd07fc6b-db86-4139-b6de-e328cea0f694 Turkish Get-Up # 717 1546af08-017c-4de5-b13f-cb3a1999733d Turkish Get-Up {'en': 'bd07fc6b-db86-4139-b6de-e328cea0f694', 'de': '1546af08-017c-4de5-b13f-cb3a1999733d'}, # 154 cd4fac32-48fb-4237-a263-a44c5108790a Leg Curls (laying) # 22 8f0170a2-5274-4487-a295-1a9baf2c92a3 Beinbeuger Liegend {'en': 'cd4fac32-48fb-4237-a263-a44c5108790a', 'de': '8f0170a2-5274-4487-a295-1a9baf2c92a3'}, # 118 89c98117-dd53-4334-bfa6-72a96525629a Leg Curls (standing) # 72 9075241c-0493-4f2a-a399-a57e3634093e Beinbeuger Stehend {'en': '89c98117-dd53-4334-bfa6-72a96525629a', 'de': '9075241c-0493-4f2a-a399-a57e3634093e'}, # 263 9f622058-85a4-4272-ad99-e5696e772137 Roman Chair # 714 68f96d3e-9172-468c-9018-06f71a97faff Beinheben am Roman Chair {'en': '9f622058-85a4-4272-ad99-e5696e772137', 'de': '68f96d3e-9172-468c-9018-06f71a97faff'}, # 421 170cc52f-345f-41b3-bdae-8a5e0c9aa449 Bent-over Lateral Raises # 47 e701de98-32c6-4e9d-956d-434cf5bcaaf0 Vorgebeugtes Seitheben {'en': '170cc52f-345f-41b3-bdae-8a5e0c9aa449', 'de': 'e701de98-32c6-4e9d-956d-434cf5bcaaf0'}, # 185 bdb7bdbb-8930-46e5-8b98-eb13e604553f Squat Jumps # 296 032a38cf-b15a-4761-b684-577e41893f54 Tiefe Hocksprünge {'en': 'bdb7bdbb-8930-46e5-8b98-eb13e604553f', 'de': '032a38cf-b15a-4761-b684-577e41893f54'}, ] def create_exercise_mapping(apps, schema_editor): Exercise = apps.get_model('exercises', 'Exercise') ExerciseBase = apps.get_model('exercises', 'ExerciseBase') for exercise_group in exercise_mapping: langs = list(exercise_group.keys()) exercise_objects = [] for lang in langs: try: exercise_objects.append(Exercise.objects.get(uuid=exercise_group[lang])) except Exercise.DoesNotExist: pass # print(exercise_group[lang], "does not exist") if len(exercise_objects) > 0: exercise_base_main = exercise_objects[0].exercise_base for exercise in exercise_objects[1:]: ExerciseBase.objects.get(id=exercise.exercise_base.id).delete() exercise.exercise_base = exercise_base_main exercise.save() def remove_mappings(apps, schema_editor): """ Backwards migration. """ pass class Migration(migrations.Migration): dependencies = [ ('exercises', '0010_auto_20201211_0205'), ] operations = [ migrations.RunPython(create_exercise_mapping, remove_mappings), ]
22,082
Python
.py
314
64.789809
97
0.740563
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,710
0023_make_uuid_unique.py
wger-project_wger/wger/exercises/migrations/0023_make_uuid_unique.py
# Generated by Django 4.1.5 on 2023-03-17 20:56 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('exercises', '0022_alter_exercise_license_author_and_more'), ] operations = [ migrations.AlterField( model_name='deletionlog', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID' ), ), migrations.AlterField( model_name='exercise', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID' ), ), migrations.AlterField( model_name='exercisebase', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID' ), ), migrations.AlterField( model_name='exerciseimage', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID' ), ), migrations.AlterField( model_name='exercisevideo', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID' ), ), migrations.AlterField( model_name='historicalexercise', name='uuid', field=models.UUIDField( db_index=True, default=uuid.uuid4, editable=False, verbose_name='UUID' ), ), migrations.AlterField( model_name='historicalexercisebase', name='uuid', field=models.UUIDField( db_index=True, default=uuid.uuid4, editable=False, verbose_name='UUID' ), ), migrations.AlterField( model_name='historicalexerciseimage', name='uuid', field=models.UUIDField( db_index=True, default=uuid.uuid4, editable=False, verbose_name='UUID' ), ), migrations.AlterField( model_name='historicalexercisevideo', name='uuid', field=models.UUIDField( db_index=True, default=uuid.uuid4, editable=False, verbose_name='UUID' ), ), ]
2,487
Python
.py
72
23.152778
86
0.549564
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,711
0012_auto_20210327_1219.py
wger-project_wger/wger/exercises/migrations/0012_auto_20210327_1219.py
# Generated by Django 3.1.7 on 2021-03-27 11:19 from django.db import migrations, models import uuid def generate_uuids(apps, schema_editor): """Generate new UUIDs for each exercise image""" ExcerciseImage = apps.get_model('exercises', 'ExerciseImage') for exercise in ExcerciseImage.objects.all(): exercise.uuid = uuid.uuid4() exercise.save() class Migration(migrations.Migration): dependencies = [ ('exercises', '0011_auto_20201214_0033'), ] operations = [ migrations.AddField( model_name='exerciseimage', name='uuid', field=models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID'), ), migrations.RunPython(generate_uuids), ]
764
Python
.py
21
29.714286
92
0.668478
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,712
0013_auto_20210503_1232.py
wger-project_wger/wger/exercises/migrations/0013_auto_20210503_1232.py
# Generated by Django 3.2 on 2021-05-03 10:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('exercises', '0012_auto_20210327_1219'), ] operations = [ migrations.RenameField( model_name='exerciseimage', old_name='exercise', new_name='exercise_base', ), 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=50, null=True, verbose_name='Author', ), ), migrations.AlterField( model_name='exercisebase', name='variations', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='exercises.variation', verbose_name='Variations', ), ), ]
1,253
Python
.py
38
21.447368
80
0.528489
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,713
equipment.py
wger-project_wger/wger/exercises/views/equipment.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.urls import ( reverse, reverse_lazy, ) from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, ListView, UpdateView, ) # wger from wger.exercises.models import Equipment from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) logger = logging.getLogger(__name__) """ Exercise equipment """ class EquipmentListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): """ Generic view to list all equipments """ model = Equipment fields = ['name'] template_name = 'equipment/admin-overview.html' context_object_name = 'equipment_list' paginate_by = PAGINATION_OBJECTS_PER_PAGE permission_required = 'exercises.change_equipment' class EquipmentEditView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView): """ Generic view to update an existing equipment item """ model = Equipment fields = ['name'] permission_required = 'exercises.change_equipment' success_url = reverse_lazy('exercise:equipment:list') # Send some additional data to the template def get_context_data(self, **kwargs): context = super(EquipmentEditView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object) return context class EquipmentAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView): """ Generic view to add a new equipment item """ model = Equipment fields = ['name'] title = gettext_lazy('Add new equipment') permission_required = 'exercises.add_equipment' success_url = reverse_lazy('exercise:equipment:list') class EquipmentDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView): """ Generic view to delete an existing exercise image """ model = Equipment messages = gettext_lazy('Successfully deleted') title = gettext_lazy('Delete equipment?') permission_required = 'exercises.delete_equipment' success_url = reverse_lazy('exercise:equipment:list') def get_context_data(self, **kwargs): """ Send some additional data to the template """ pk = self.kwargs['pk'] context = super(EquipmentDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete equipment?') context['form_action'] = reverse('exercise:equipment:delete', kwargs={'pk': pk}) return context
3,414
Python
.py
96
31.458333
100
0.732403
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,714
history.py
wger-project_wger/wger/exercises/views/history.py
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU Affero General Public License # Standard Library import logging # Django from django.contrib.auth.decorators import permission_required from django.contrib.contenttypes.models import ContentType from django.http import HttpResponseRedirect from django.shortcuts import ( get_object_or_404, render, ) from django.urls import reverse # Third Party from actstream import action as actstream_action from actstream.models import Action # wger from wger.exercises.views.helper import StreamVerbs logger = logging.getLogger(__name__) @permission_required('exercises.change_exercise') def control(request): """ Admin view of the history of the exercises """ all_streams = Action.objects.all() out = [] for entry in all_streams: data = {'verb': entry.verb, 'stream': entry} if entry.verb == StreamVerbs.UPDATED.value: entry_obj = entry.action_object.history.as_of(entry.timestamp) historical_entry = entry_obj._history previous_entry = historical_entry.prev_record data['id'] = historical_entry.id data['content_type_id'] = ContentType.objects.get_for_model(entry_obj).id if previous_entry: data['delta'] = historical_entry.diff_against(previous_entry) data['history_id'] = previous_entry.history_id out.append(data) return render( request, 'history/overview.html', { 'context': out, # We can't pass the enum to the template, so we have to do this # https://stackoverflow.com/questions/35953132/ 'verbs': StreamVerbs.__members__, }, ) @permission_required('exercises.change_exercise') def history_revert(request, history_pk, content_type_id): """ Used to revert history objects """ object_type = get_object_or_404(ContentType, pk=content_type_id) object_class = object_type.model_class() history = object_class.history.get(history_id=history_pk) history.instance.save() actstream_action.send( request.user, verb=StreamVerbs.UPDATED.value, action_object=history.instance, info='reverted history by admin', ) return HttpResponseRedirect(reverse('exercise:history:overview'))
2,933
Python
.py
75
33.6
85
0.707394
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,715
helper.py
wger-project_wger/wger/exercises/views/helper.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 class StreamVerbs(enum.Enum): CREATED = 'created' UPDATED = 'updated'
749
Python
.py
17
42.411765
78
0.78738
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,716
exercises.py
wger-project_wger/wger/exercises/views/exercises.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 HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.urls import ( reverse, reverse_lazy, ) from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( DeleteView, TemplateView, ) # wger from wger.exercises.models import Exercise from wger.utils.generic_views import WgerDeleteMixin logger = logging.getLogger(__name__) def view(request, id, slug=None): """ Detail view for an exercise translation """ exercise = get_object_or_404(Exercise, pk=id) return HttpResponsePermanentRedirect( reverse( 'exercise:exercise:view-base', kwargs={'pk': exercise.exercise_base_id, 'slug': slug} ) ) class ExerciseDeleteView( WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView, ): """ Generic view to delete an existing exercise """ model = Exercise success_url = reverse_lazy('exercise:exercise:overview') delete_message_extra = gettext_lazy('This will delete the exercise from all workouts.') messages = gettext_lazy('Successfully deleted') permission_required = 'exercises.delete_exercise' def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(ExerciseDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object.name) return context
2,326
Python
.py
69
29.855072
97
0.736185
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,717
muscles.py
wger-project_wger/wger/exercises/views/muscles.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.urls import reverse_lazy from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, ListView, UpdateView, ) # wger from wger.exercises.models import Muscle from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) logger = logging.getLogger(__name__) class MuscleAdminListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): """ Overview of all muscles, for administration purposes """ model = Muscle context_object_name = 'muscle_list' permission_required = 'exercises.change_muscle' queryset = Muscle.objects.order_by('name') template_name = 'muscles/admin-overview.html' class MuscleAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView): """ Generic view to add a new muscle """ model = Muscle fields = ['name', 'is_front', 'name_en'] success_url = reverse_lazy('exercise:muscle:admin-list') title = gettext_lazy('Add muscle') permission_required = 'exercises.add_muscle' class MuscleUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView): """ Generic view to update an existing muscle """ model = Muscle fields = ['name', 'is_front', 'name_en'] success_url = reverse_lazy('exercise:muscle:admin-list') permission_required = 'exercises.change_muscle' def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(MuscleUpdateView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object.name) return context class MuscleDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView): """ Generic view to delete an existing muscle """ model = Muscle success_url = reverse_lazy('exercise:muscle:admin-list') permission_required = 'exercises.delete_muscle' messages = gettext_lazy('Successfully deleted') def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(MuscleDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object.name) return context
3,165
Python
.py
87
32.114943
97
0.725638
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,718
categories.py
wger-project_wger/wger/exercises/views/categories.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.urls import reverse_lazy from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, ListView, UpdateView, ) # wger from wger.exercises.models import ExerciseCategory from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) from wger.utils.language import load_language logger = logging.getLogger(__name__) class ExerciseCategoryListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): """ Overview of all categories, for administration purposes """ model = ExerciseCategory permission_required = 'exercises.change_exercisecategory' template_name = 'categories/admin-overview.html' class ExerciseCategoryAddView( WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView, ): """ Generic view to add a new exercise category """ model = ExerciseCategory fields = ['name'] success_url = reverse_lazy('exercise:category:list') title = gettext_lazy('Add category') permission_required = 'exercises.add_exercisecategory' def form_valid(self, form): form.instance.language = load_language() return super(ExerciseCategoryAddView, self).form_valid(form) class ExerciseCategoryUpdateView( WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView, ): """ Generic view to update an existing exercise category """ model = ExerciseCategory fields = ['name'] success_url = reverse_lazy('exercise:category:list') permission_required = 'exercises.change_exercisecategory' # Send some additional data to the template def get_context_data(self, **kwargs): context = super(ExerciseCategoryUpdateView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object.name) return context def form_valid(self, form): form.instance.language = load_language() return super(ExerciseCategoryUpdateView, self).form_valid(form) class ExerciseCategoryDeleteView( WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView, ): """ Generic view to delete an existing exercise category """ model = ExerciseCategory fields = ('name',) success_url = reverse_lazy('exercise:category:list') delete_message_extra = gettext_lazy('This will also delete all exercises in this category.') messages = gettext_lazy('Successfully deleted') permission_required = 'exercises.delete_exercisecategory' # Send some additional data to the template def get_context_data(self, **kwargs): context = super(ExerciseCategoryDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object.name) return context
3,684
Python
.py
105
30.885714
96
0.742335
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,719
serializers.py
wger-project_wger/wger/exercises/api/serializers.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.cache import cache from django.db.models import Q # Third Party from rest_framework import serializers # wger from wger.exercises.models import ( Alias, DeletionLog, Equipment, Exercise, ExerciseBase, ExerciseCategory, ExerciseComment, ExerciseImage, ExerciseVideo, Muscle, Variation, ) from wger.utils.cache import CacheKeyMapper class ExerciseBaseSerializer(serializers.ModelSerializer): """ Exercise base serializer """ class Meta: model = ExerciseBase fields = [ 'id', 'uuid', 'created', 'last_update', 'category', 'muscles', 'muscles_secondary', 'equipment', 'variations', 'license_author', ] class EquipmentSerializer(serializers.ModelSerializer): """ Equipment serializer """ class Meta: model = Equipment fields = ['id', 'name'] class DeletionLogSerializer(serializers.ModelSerializer): """ Deletion log serializer """ class Meta: model = DeletionLog fields = [ 'model_type', 'uuid', 'replaced_by', 'timestamp', 'comment', ] class ExerciseImageSerializer(serializers.ModelSerializer): """ ExerciseImage serializer """ author_history = serializers.ListSerializer(child=serializers.CharField(), read_only=True) exercise_base_uuid = serializers.ReadOnlyField(source='exercise_base.uuid') class Meta: model = ExerciseImage fields = [ 'id', 'uuid', 'exercise_base', 'exercise_base_uuid', 'image', 'is_main', 'style', 'license', 'license_title', 'license_object_url', 'license_author', 'license_author_url', 'license_derivative_source_url', 'author_history', ] class ExerciseVideoSerializer(serializers.ModelSerializer): """ ExerciseVideo serializer """ exercise_base_uuid = serializers.ReadOnlyField(source='exercise_base.uuid') author_history = serializers.ListSerializer(child=serializers.CharField(), read_only=True) class Meta: model = ExerciseVideo fields = [ 'id', 'uuid', 'exercise_base', 'exercise_base_uuid', 'video', 'is_main', 'size', 'duration', 'width', 'height', 'codec', 'codec_long', 'license', 'license_title', 'license_object_url', 'license_author', 'license_author_url', 'license_derivative_source_url', 'author_history', ] class ExerciseVideoInfoSerializer(serializers.ModelSerializer): """ ExerciseVideo serializer for the info endpoint """ author_history = serializers.ListSerializer(child=serializers.CharField(), read_only=True) class Meta: model = ExerciseVideo fields = [ 'id', 'uuid', 'exercise_base', 'video', 'is_main', 'size', 'duration', 'width', 'height', 'codec', 'codec_long', 'license', 'license_title', 'license_object_url', 'license_author', 'license_author_url', 'license_derivative_source_url', 'author_history', ] class ExerciseCommentSerializer(serializers.ModelSerializer): """ ExerciseComment serializer """ id = serializers.IntegerField(required=False, read_only=True) class Meta: model = ExerciseComment fields = [ 'id', 'uuid', 'exercise', 'comment', ] class ExerciseAliasSerializer(serializers.ModelSerializer): """ ExerciseAlias serializer """ class Meta: model = Alias fields = [ 'id', 'uuid', 'exercise', 'alias', ] class ExerciseVariationSerializer(serializers.ModelSerializer): """ Exercise variation serializer """ class Meta: model = Variation fields = [ 'id', ] class ExerciseInfoAliasSerializer(serializers.ModelSerializer): """ Exercise alias serializer for info endpoint """ class Meta: model = Alias fields = [ 'id', 'uuid', 'alias', ] class ExerciseCategorySerializer(serializers.ModelSerializer): """ ExerciseCategory serializer """ class Meta: model = ExerciseCategory fields = ['id', 'name'] class MuscleSerializer(serializers.ModelSerializer): """ Muscle serializer """ image_url_main = serializers.CharField() image_url_secondary = serializers.CharField() class Meta: model = Muscle fields = [ 'id', 'name', 'name_en', 'is_front', 'image_url_main', 'image_url_secondary', ] class ExerciseSerializer(serializers.ModelSerializer): """ Exercise serializer The fields from the new ExerciseBase are retrieved here as to retain compatibility with the old model where all the fields where in Exercise. """ category = serializers.PrimaryKeyRelatedField(queryset=ExerciseCategory.objects.all()) muscles = serializers.PrimaryKeyRelatedField(many=True, queryset=Muscle.objects.all()) muscles_secondary = serializers.PrimaryKeyRelatedField(many=True, queryset=Muscle.objects.all()) equipment = serializers.PrimaryKeyRelatedField(many=True, queryset=Equipment.objects.all()) variations = serializers.PrimaryKeyRelatedField(many=True, queryset=Variation.objects.all()) author_history = serializers.ListSerializer(child=serializers.CharField()) class Meta: model = Exercise fields = ( 'id', 'uuid', 'name', 'exercise_base', 'description', 'created', 'category', 'muscles', 'muscles_secondary', 'equipment', 'language', 'license', 'license_author', 'variations', 'author_history', ) class ExerciseTranslationBaseInfoSerializer(serializers.ModelSerializer): """ Exercise translation serializer for the base info endpoint """ id = serializers.IntegerField(required=False, read_only=True) uuid = serializers.UUIDField(required=False, read_only=True) exercise_base = serializers.PrimaryKeyRelatedField( queryset=ExerciseBase.objects.all(), required=True, ) aliases = ExerciseInfoAliasSerializer(source='alias_set', many=True, read_only=True) notes = ExerciseCommentSerializer(source='exercisecomment_set', many=True, read_only=True) author_history = serializers.ListSerializer(child=serializers.CharField()) class Meta: model = Exercise fields = ( 'id', 'uuid', 'name', 'exercise_base', 'description', 'created', 'language', 'aliases', 'notes', 'license', 'license_title', 'license_object_url', 'license_author', 'license_author_url', 'license_derivative_source_url', 'author_history', ) class ExerciseTranslationSerializer(serializers.ModelSerializer): """ Exercise translation serializer """ id = serializers.IntegerField(required=False, read_only=True) uuid = serializers.UUIDField(required=False, read_only=True) exercise_base = serializers.PrimaryKeyRelatedField( queryset=ExerciseBase.objects.all(), required=True, ) class Meta: model = Exercise fields = ( 'id', 'uuid', 'name', 'exercise_base', 'description', 'created', 'language', 'license_author', ) def validate(self, value): """ Check that there is only one language per exercise """ if value.get('language'): # Editing an existing object # -> Check if the language already exists, excluding the current object if self.instance: if self.instance.exercise_base.exercises.filter( ~Q(id=self.instance.pk), language=value['language'] ).exists(): raise serializers.ValidationError( f"There is already a translation for this exercise in {value['language']}" ) # Creating a new object # -> Check if the language already exists else: if Exercise.objects.filter( exercise_base=value['exercise_base'], language=value['language'] ).exists(): raise serializers.ValidationError( f"There is already a translation for this exercise in {value['language']}" ) return super().validate(value) class ExerciseInfoSerializer(serializers.ModelSerializer): """ Exercise info serializer """ images = ExerciseImageSerializer(many=True, read_only=True) videos = ExerciseVideoSerializer(many=True, read_only=True) comments = ExerciseCommentSerializer(source='exercisecomment_set', many=True, read_only=True) category = ExerciseCategorySerializer(read_only=True) muscles = MuscleSerializer(many=True, read_only=True) muscles_secondary = MuscleSerializer(many=True, read_only=True) equipment = EquipmentSerializer(many=True, read_only=True) variations = serializers.PrimaryKeyRelatedField(many=True, read_only=True) aliases = ExerciseInfoAliasSerializer(source='alias_set', many=True, read_only=True) author_history = serializers.ListSerializer(child=serializers.CharField()) class Meta: model = Exercise depth = 1 fields = [ 'id', 'name', 'aliases', 'uuid', 'exercise_base_id', 'description', 'created', 'category', 'muscles', 'muscles_secondary', 'equipment', 'language', 'license', 'license_author', 'images', 'videos', 'comments', 'variations', 'author_history', ] class ExerciseBaseInfoSerializer(serializers.ModelSerializer): """ Exercise base info serializer """ images = ExerciseImageSerializer(source='exerciseimage_set', many=True, read_only=True) category = ExerciseCategorySerializer(read_only=True) muscles = MuscleSerializer(many=True, read_only=True) muscles_secondary = MuscleSerializer(many=True, read_only=True) equipment = EquipmentSerializer(many=True, read_only=True) exercises = ExerciseTranslationBaseInfoSerializer(many=True, read_only=True) videos = ExerciseVideoInfoSerializer(source='exercisevideo_set', many=True, read_only=True) variations = serializers.PrimaryKeyRelatedField(read_only=True) author_history = serializers.ListSerializer(child=serializers.CharField()) total_authors_history = serializers.ListSerializer(child=serializers.CharField()) last_update_global = serializers.DateTimeField(read_only=True) class Meta: model = ExerciseBase depth = 1 fields = [ 'id', 'uuid', 'created', 'last_update', 'last_update_global', 'category', 'muscles', 'muscles_secondary', 'equipment', 'license', 'license_author', 'images', 'exercises', 'variations', 'images', 'videos', 'author_history', 'total_authors_history', ] def to_representation(self, instance): """ Cache the response """ key = CacheKeyMapper.get_exercise_api_key(instance.uuid) representation = cache.get(key) if representation: return representation representation = super().to_representation(instance) cache.set(key, representation, settings.WGER_SETTINGS['EXERCISE_CACHE_TTL']) return representation
13,546
Python
.py
417
23.393285
100
0.599663
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,720
endpoints.py
wger-project_wger/wger/exercises/api/endpoints.py
EXERCISE_ENDPOINT = 'exercisebaseinfo' DELETION_LOG_ENDPOINT = 'deletion-log' CATEGORY_ENDPOINT = 'exercisecategory' MUSCLE_ENDPOINT = 'muscle' EQUIPMENT_ENDPOINT = 'equipment' IMAGE_ENDPOINT = 'exerciseimage' VIDEO_ENDPOINT = 'video'
235
Python
.py
7
32.571429
38
0.807018
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,721
permissions.py
wger-project_wger/wger/exercises/api/permissions.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/>. # Third Party from rest_framework.permissions import BasePermission class CanContributeExercises(BasePermission): """ Checks that users are allowed to create or edit an exercise. Regular users that are "trustworthy" (see Userprofile model for details) and administrator users with the appropriate exercise permission are allowed to perform CRUD operations TODO: at the moment the "exercises.delete_exercise" is hard coded here and while it is enough and works, ideally we would want to set the individual permissions for e.g. aliases or videos. """ SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] ADD_METHODS = ['POST', 'PUT', 'PATCH'] DELETE_METHODS = ['DELETE'] def has_permission(self, request, view): # Everybody can read if request.method in self.SAFE_METHODS: return True # Only logged-in users can perform CRUD operations if not request.user.is_authenticated: return False # Creating or updating if request.method in self.ADD_METHODS: return request.user.userprofile.is_trustworthy or request.user.has_perm( 'exercises.add_exercise' ) # Only admins are allowed to delete entries if request.method in self.DELETE_METHODS: return request.user.has_perm('exercises.delete_exercise')
2,108
Python
.py
44
42.045455
84
0.720058
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,722
views.py
wger-project_wger/wger/exercises/api/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 # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. # Standard Library import logging from uuid import UUID # Django from django.conf import settings from django.contrib.postgres.search import TrigramSimilarity from django.db.models import Q from django.utils.decorators import method_decorator from django.utils.translation import gettext as _ from django.views.decorators.cache import cache_page # Third Party import bleach from actstream import action as actstream_action from bleach.css_sanitizer import CSSSanitizer from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import ( OpenApiParameter, extend_schema, inline_serializer, ) from easy_thumbnails.alias import aliases from easy_thumbnails.exceptions import InvalidImageFormatError from easy_thumbnails.files import get_thumbnailer from rest_framework import viewsets from rest_framework.decorators import ( action, api_view, ) from rest_framework.fields import ( CharField, IntegerField, ) from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet # wger from wger.exercises.api.permissions import CanContributeExercises from wger.exercises.api.serializers import ( DeletionLogSerializer, EquipmentSerializer, ExerciseAliasSerializer, ExerciseBaseInfoSerializer, ExerciseBaseSerializer, ExerciseCategorySerializer, ExerciseCommentSerializer, ExerciseImageSerializer, ExerciseInfoSerializer, ExerciseSerializer, ExerciseTranslationSerializer, ExerciseVariationSerializer, ExerciseVideoSerializer, MuscleSerializer, ) from wger.exercises.models import ( Alias, DeletionLog, Equipment, Exercise, ExerciseBase, ExerciseCategory, ExerciseComment, ExerciseImage, ExerciseVideo, Muscle, Variation, ) from wger.exercises.views.helper import StreamVerbs from wger.utils.constants import ( ENGLISH_SHORT_NAME, HTML_ATTRIBUTES_WHITELIST, HTML_STYLES_WHITELIST, HTML_TAG_WHITELIST, SEARCH_ALL_LANGUAGES, ) from wger.utils.db import is_postgres_db from wger.utils.language import load_language logger = logging.getLogger(__name__) class ExerciseBaseViewSet(ModelViewSet): """ API endpoint for exercise base objects. For a read-only endpoint with all the information of an exercise, see /api/v2/exercisebaseinfo/ """ queryset = ExerciseBase.translations.all() serializer_class = ExerciseBaseSerializer permission_classes = (CanContributeExercises,) ordering_fields = '__all__' filterset_fields = ( 'category', 'muscles', 'muscles_secondary', 'equipment', ) def perform_create(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.CREATED.value, action_object=serializer.instance, ) def perform_update(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.UPDATED.value, action_object=serializer.instance, ) def perform_destroy(self, instance: ExerciseBase): """Manually delete the exercise and set the replacement, if any""" uuid = self.request.query_params.get('replaced_by', '') try: UUID(uuid, version=4) except ValueError: uuid = None instance.delete(replace_by=uuid) class ExerciseTranslationViewSet(ModelViewSet): """ API endpoint for editing or adding exercise translation objects. """ queryset = Exercise.objects.all() permission_classes = (CanContributeExercises,) serializer_class = ExerciseTranslationSerializer ordering_fields = '__all__' filterset_fields = ( 'uuid', 'created', 'exercise_base', 'description', 'name', ) def perform_create(self, serializer): """ Save entry to activity stream """ # Clean the description HTML if serializer.validated_data.get('description'): serializer.validated_data['description'] = bleach.clean( serializer.validated_data['description'], tags=HTML_TAG_WHITELIST, attributes=HTML_ATTRIBUTES_WHITELIST, css_sanitizer=CSSSanitizer(allowed_css_properties=HTML_STYLES_WHITELIST), strip=True, ) super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.CREATED.value, action_object=serializer.instance, ) def perform_update(self, serializer): """ Save entry to activity stream """ # Don't allow to change the base or the language over the API if serializer.validated_data.get('exercise_base'): del serializer.validated_data['exercise_base'] if serializer.validated_data.get('language'): del serializer.validated_data['language'] # Clean the description HTML if serializer.validated_data.get('description'): serializer.validated_data['description'] = bleach.clean( serializer.validated_data['description'], tags=HTML_TAG_WHITELIST, attributes=HTML_ATTRIBUTES_WHITELIST, css_sanitizer=CSSSanitizer(allowed_css_properties=HTML_STYLES_WHITELIST), strip=True, ) super().perform_update(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.UPDATED.value, action_object=serializer.instance, ) class ExerciseViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for exercise objects, use /api/v2/exercisebaseinfo/ instead. This is only kept for backwards compatibility and will be removed in the future """ queryset = Exercise.objects.all() permission_classes = (CanContributeExercises,) serializer_class = ExerciseSerializer ordering_fields = '__all__' filterset_fields = ( 'uuid', 'created', 'exercise_base', 'description', 'language', 'name', ) @method_decorator(cache_page(settings.WGER_SETTINGS['EXERCISE_CACHE_TTL'])) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) @extend_schema(deprecated=True) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) @extend_schema(deprecated=True) def retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs) def get_queryset(self): """Add additional filters for fields from exercise base""" qs = Exercise.objects.all() category = self.request.query_params.get('category') muscles = self.request.query_params.get('muscles') muscles_secondary = self.request.query_params.get('muscles_secondary') equipment = self.request.query_params.get('equipment') license = self.request.query_params.get('license') if category: try: qs = qs.filter(exercise_base__category_id=int(category)) except ValueError: logger.info(f'Got {category} as category ID') if muscles: try: qs = qs.filter(exercise_base__muscles__in=[int(m) for m in muscles.split(',')]) except ValueError: logger.info(f'Got {muscles} as muscle IDs') if muscles_secondary: try: muscle_ids = [int(m) for m in muscles_secondary.split(',')] qs = qs.filter(exercise_base__muscles_secondary__in=muscle_ids) except ValueError: logger.info(f"Got '{muscles_secondary}' as secondary muscle IDs") if equipment: try: qs = qs.filter(exercise_base__equipment__in=[int(e) for e in equipment.split(',')]) except ValueError: logger.info(f'Got {equipment} as equipment IDs') if license: try: qs = qs.filter(exercise_base__license_id=int(license)) except ValueError: logger.info(f'Got {license} as license ID') return qs @extend_schema( parameters=[ OpenApiParameter( 'term', OpenApiTypes.STR, OpenApiParameter.QUERY, description='The name of the exercise to search', required=True, ), OpenApiParameter( 'language', OpenApiTypes.STR, OpenApiParameter.QUERY, description='Comma separated list of language codes to search', required=True, ), ], # yapf: disable responses={ 200: inline_serializer( name='ExerciseSearchResponse', fields={ 'value': CharField(), 'data': inline_serializer( name='ExerciseSearchItemResponse', fields={ 'id': IntegerField(), 'base_id': IntegerField(), 'name': CharField(), 'category': CharField(), 'image': CharField(), 'image_thumbnail': CharField(), }, ), }, ) }, # yapf: enable ) @api_view(['GET']) def search(request): """ Searches for exercises. This format is currently used by the exercise search autocompleter """ q = request.GET.get('term', None) language_codes = request.GET.get('language', ENGLISH_SHORT_NAME) response = {} results = [] if not q: return Response(response) # Filter the appropriate languages languages = [load_language(l) for l in language_codes.split(',')] if language_codes == SEARCH_ALL_LANGUAGES: query = Exercise.objects.all() else: query = Exercise.objects.filter(language__in=languages) query = query.only('name') # Postgres uses a full-text search if is_postgres_db(): query = ( query.annotate(similarity=TrigramSimilarity('name', q)) .filter(Q(similarity__gt=0.15) | Q(alias__alias__icontains=q)) .order_by('-similarity', 'name') ) else: query = query.filter(Q(name__icontains=q) | Q(alias__alias__icontains=q)) for translation in query: image = None thumbnail = None if translation.main_image: image_obj = translation.main_image image = image_obj.image.url t = get_thumbnailer(image_obj.image) thumbnail = None try: thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url except InvalidImageFormatError as e: logger.info(f'InvalidImageFormatError while processing a thumbnail: {e}') except OSError as e: logger.info(f'OSError while processing a thumbnail: {e}') result_json = { 'value': translation.name, 'data': { 'id': translation.id, 'base_id': translation.exercise_base_id, 'name': translation.name, 'category': _(translation.category.name), 'image': image, 'image_thumbnail': thumbnail, }, } results.append(result_json) response['suggestions'] = results return Response(response) class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet): """ API endpoint for exercise objects, use /api/v2/exercisebaseinfo/ instead. """ queryset = Exercise.objects.all() serializer_class = ExerciseInfoSerializer ordering_fields = '__all__' filterset_fields = ( 'created', 'description', 'name', 'exercise_base', 'license', 'license_author', ) @method_decorator(cache_page(settings.WGER_SETTINGS['EXERCISE_CACHE_TTL'])) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) @extend_schema(deprecated=True) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) @extend_schema(deprecated=True) def retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs) class ExerciseBaseInfoViewset(viewsets.ReadOnlyModelViewSet): """ Read-only info API endpoint for exercise objects, grouped by the exercise base. Returns nested data structures for more easy and faster parsing and is the recommended way to access the exercise data. """ queryset = ExerciseBase.objects.all() serializer_class = ExerciseBaseInfoSerializer ordering_fields = '__all__' filterset_fields = ( 'uuid', 'category', 'muscles', 'muscles_secondary', 'equipment', 'variations', 'license', 'license_author', ) class EquipmentViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for equipment objects """ queryset = Equipment.objects.all() serializer_class = EquipmentSerializer ordering_fields = '__all__' filterset_fields = ('name',) @method_decorator(cache_page(settings.WGER_SETTINGS['EXERCISE_CACHE_TTL'])) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) class DeletionLogViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for exercise deletion logs This lists objects that where deleted on a wger instance and should be deleted as well when performing a sync (e.g. because many exercises where submitted at once or an image was uploaded that hasn't a CC license) """ queryset = DeletionLog.objects.all() serializer_class = DeletionLogSerializer ordering_fields = '__all__' filterset_fields = ('model_type',) class ExerciseCategoryViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for exercise categories objects """ queryset = ExerciseCategory.objects.all() serializer_class = ExerciseCategorySerializer ordering_fields = '__all__' filterset_fields = ('name',) @method_decorator(cache_page(settings.WGER_SETTINGS['EXERCISE_CACHE_TTL'])) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) class ExerciseImageViewSet(ModelViewSet): """ API endpoint for exercise image objects """ queryset = ExerciseImage.objects.all() serializer_class = ExerciseImageSerializer permission_classes = (CanContributeExercises,) ordering_fields = '__all__' filterset_fields = ( 'is_main', 'exercise_base', 'license', 'license_author', ) @method_decorator(cache_page(settings.WGER_SETTINGS['EXERCISE_CACHE_TTL'])) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) @action(detail=True) def thumbnails(self, request, pk): """ Return a list of the image's thumbnails """ try: image = ExerciseImage.objects.get(pk=pk) except ExerciseImage.DoesNotExist: return Response([]) thumbnails = {} for alias in aliases.all(): t = get_thumbnailer(image.image) thumbnails[alias] = { 'url': t.get_thumbnail(aliases.get(alias)).url, 'settings': aliases.get(alias), } thumbnails['original'] = image.image.url return Response(thumbnails) def perform_create(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.CREATED.value, action_object=serializer.instance, ) def perform_update(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.UPDATED.value, action_object=serializer.instance, ) class ExerciseVideoViewSet(ModelViewSet): """ API endpoint for exercise video objects """ queryset = ExerciseVideo.objects.all() serializer_class = ExerciseVideoSerializer permission_classes = (CanContributeExercises,) ordering_fields = '__all__' filterset_fields = ( 'is_main', 'exercise_base', 'license', 'license_author', ) def perform_create(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.CREATED.value, action_object=serializer.instance, ) def perform_update(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.UPDATED.value, action_object=serializer.instance, ) class ExerciseCommentViewSet(ModelViewSet): """ API endpoint for exercise comment objects """ serializer_class = ExerciseCommentSerializer permission_classes = (CanContributeExercises,) ordering_fields = '__all__' filterset_fields = ('comment', 'exercise') def get_queryset(self): """Filter by language for exercise comments""" qs = ExerciseComment.objects.all() language = self.request.query_params.get('language') if language: exercises = Exercise.objects.filter(language=language) qs = ExerciseComment.objects.filter(exercise__in=exercises) return qs def perform_create(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.CREATED.value, action_object=serializer.instance, ) def perform_update(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.UPDATED.value, action_object=serializer.instance, ) class ExerciseAliasViewSet(ModelViewSet): """ API endpoint for exercise aliases objects """ serializer_class = ExerciseAliasSerializer queryset = Alias.objects.all() permission_classes = (CanContributeExercises,) ordering_fields = '__all__' filterset_fields = ('alias', 'exercise') def perform_create(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.CREATED.value, action_object=serializer.instance, ) def perform_update(self, serializer): """ Save entry to activity stream """ super().perform_create(serializer) actstream_action.send( self.request.user, verb=StreamVerbs.UPDATED.value, action_object=serializer.instance, ) class ExerciseVariationViewSet(ModelViewSet): """ API endpoint for exercise variation objects """ serializer_class = ExerciseVariationSerializer queryset = Variation.objects.all() permission_classes = (CanContributeExercises,) class MuscleViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for muscle objects """ queryset = Muscle.objects.all() serializer_class = MuscleSerializer ordering_fields = '__all__' filterset_fields = ('name', 'is_front', 'name_en') @method_decorator(cache_page(settings.WGER_SETTINGS['EXERCISE_CACHE_TTL'])) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs)
21,284
Python
.py
595
27.736134
99
0.642881
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,723
test_change_exercise_author.py
wger-project_wger/wger/exercises/tests/test_change_exercise_author.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 io import StringIO # Django from django.core.management import call_command # wger from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models.base import ExerciseBase from wger.exercises.models.exercise import Exercise class ChangeExerciseAuthorTestCase(WgerTestCase): """ Tests the change exercise author command """ def setUp(self): super(ChangeExerciseAuthorTestCase, self).setUp() self.out = StringIO() def test_missing_author(self): """ Test to ensure command handles a missing author parameter """ call_command('change-exercise-author', stdout=self.out, no_color=True) self.assertIn('Please enter an author name', self.out.getvalue()) def test_missing_exercise(self): """ Test to ensure command handles a missing exercise parameters """ args = ['--author-name', 'tom'] call_command('change-exercise-author', *args, stdout=self.out, no_color=True) self.assertIn('Please enter an exercise base or exercise ID', self.out.getvalue()) def test_can_update_exercise_base(self): """ Test to ensure command can handle an exercise base id passed """ exercise = ExerciseBase.objects.get(id=2) self.assertNotEqual(exercise.license_author, 'tom') args = ['--author-name', 'tom', '--exercise-base-id', '2'] call_command('change-exercise-author', *args, stdout=self.out, no_color=True) self.assertIn('Exercise and/or exercise base has been updated', self.out.getvalue()) exercise = ExerciseBase.objects.get(id=2) self.assertEqual(exercise.license_author, 'tom') def test_can_update_exercise(self): """ Test to ensure command can handle an exercise id passed """ exercise = Exercise.objects.get(id=1) self.assertNotEqual(exercise.license_author, 'tom') args = ['--author-name', 'tom', '--exercise-id', '1'] call_command('change-exercise-author', *args, stdout=self.out, no_color=True) self.assertIn('Exercise and/or exercise base has been updated', self.out.getvalue()) exercise = Exercise.objects.get(id=1) self.assertEqual(exercise.license_author, 'tom')
2,943
Python
.py
63
40.793651
92
0.703768
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,724
test_exercise_model.py
wger-project_wger/wger/exercises/tests/test_exercise_model.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 WgerTestCase from wger.exercises.models import Exercise class ExerciseModelTestCase(WgerTestCase): """ Test the logic in the exercise model """ def test_absolute_url_name(self): """Test that the get_absolute_url returns the correct URL""" exercise = Exercise(exercise_base_id=1, description='abc', name='foo') self.assertEqual(exercise.get_absolute_url(), '/en/exercise/1/view-base/foo') def test_absolute_url_no_name(self): """Test that the get_absolute_url returns the correct URL""" exercise = Exercise(exercise_base_id=2, description='abc', name='') self.assertEqual(exercise.get_absolute_url(), '/en/exercise/2/view-base') def test_absolute_url_no_name2(self): """Test that the get_absolute_url returns the correct URL""" exercise = Exercise(exercise_base_id=42, description='abc', name='@@@@@') self.assertEqual(exercise.get_absolute_url(), '/en/exercise/42/view-base')
1,666
Python
.py
32
47.875
85
0.733415
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,725
test_exercise_base_model.py
wger-project_wger/wger/exercises/tests/test_exercise_base_model.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 # wger from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( Exercise, ExerciseBase, ) class ExerciseBaseTranslationHandlingTestCase(WgerTestCase): """ Test the logic used to handle bases without translations """ def setUp(self): super().setUp() Exercise.objects.get(pk=1).delete() Exercise.objects.get(pk=5).delete() def test_managers(self): self.assertEqual(ExerciseBase.translations.all().count(), 7) self.assertEqual(ExerciseBase.no_translations.all().count(), 1) self.assertEqual(ExerciseBase.objects.all().count(), 8) def test_checks(self): out = ExerciseBase.check() self.assertEqual(len(out), 1) self.assertEqual(out[0].id, 'wger.W002') class ExerciseBaseModelTestCase(WgerTestCase): """ Test custom model logic """ exercise: ExerciseBase def setUp(self): super().setUp() self.exercise = ExerciseBase.objects.get(pk=1) def test_access_date(self): utc = datetime.timezone.utc self.assertEqual( self.exercise.last_update_global, datetime.datetime(2023, 8, 9, 23, 0, tzinfo=utc) ) self.assertEqual( self.exercise.last_update, datetime.datetime(2020, 11, 1, 21, 10, tzinfo=utc) ) self.assertEqual( max(*[translation.last_update for translation in self.exercise.exercises.all()]), datetime.datetime(2022, 2, 2, 5, 45, 11, tzinfo=utc), ) self.assertEqual( max(*[video.last_update for video in self.exercise.exerciseimage_set.all()]), datetime.datetime(2023, 8, 9, 23, 0, tzinfo=utc), ) def test_exercise_en(self): translation = self.exercise.get_translation() self.assertEqual(translation.language.short_name, 'en') def test_get_exercise_fr(self): translation = self.exercise.get_translation('fr') self.assertEqual(translation.language.short_name, 'fr') def test_get_exercise_unknown(self): translation = self.exercise.get_translation('kg') self.assertEqual(translation.language.short_name, 'en') def test_get_languages(self): languages = self.exercise.languages self.assertEqual(languages[0].short_name, 'en') self.assertEqual(languages[1].short_name, 'fr')
3,067
Python
.py
74
35.108108
94
0.69267
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,726
test_history.py
wger-project_wger/wger/exercises/tests/test_history.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 time import sleep # Django from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.urls import reverse # Third Party from actstream import action as actstream_action # wger from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import Exercise from wger.exercises.views.helper import StreamVerbs class ExerciseHistoryControl(WgerTestCase): """ Test the history control view """ def test_admin_control_view(self): """ Test that admin control page is accessible """ self.user_login() exercise = Exercise.objects.get(pk=2) exercise.save() exercise.name = 'Very cool exercise!' exercise.save() exercise = Exercise.objects.get(pk=2) actstream_action.send( User.objects.all().first(), verb=StreamVerbs.UPDATED.value, action_object=exercise, ) response = self.client.get(reverse('exercise:history:overview')) self.assertEqual(StreamVerbs.__members__, response.context['verbs']) self.assertEqual(1, len(response.context['context'])) def test_admin_revert_view(self): """ Test that revert is accessible """ self.user_login() exercise = Exercise.objects.get(pk=2) exercise.description = 'Boring exercise' exercise.save() most_recent_history = exercise.history.order_by('history_date').last() exercise.description = 'Very cool exercise!' exercise.save() self.client.get( reverse( 'exercise:history:revert', kwargs={ 'history_pk': most_recent_history.history_id, 'content_type_id': ContentType.objects.get_for_model(exercise).id, }, ) ) exercise = Exercise.objects.get(pk=2) self.assertEqual(exercise.description, 'Boring exercise')
2,678
Python
.py
69
31.898551
86
0.682221
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,727
test_search_api.py
wger-project_wger/wger/exercises/tests/test_search_api.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/>. # Third Party from rest_framework import status # wger from wger.core.tests.api_base_test import ApiBaseTestCase from wger.core.tests.base_testcase import BaseTestCase class SearchExerciseApiTestCase(BaseTestCase, ApiBaseTestCase): url = '/api/v2/exercise/search/' def setUp(self): super().setUp() self.init_media_root() def test_basic_search_logged_out(self): """ Logged-out users are also allowed to use the search """ response = self.client.get(self.url + '?term=exercise') result1 = response.data['suggestions'][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 4) self.assertEqual(result1['value'], 'An exercise') self.assertEqual(result1['data']['id'], 1) def test_basic_search_logged_in(self): """ Logged-in users get the same results """ self.authenticate('test') response = self.client.get(self.url + '?term=exercise') result1 = response.data['suggestions'][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 4) self.assertEqual(result1['value'], 'An exercise') self.assertEqual(result1['data']['id'], 1) def test_search_language_code_en(self): """ Explicitly passing the en language code (same as no code) """ response = self.client.get(self.url + '?term=exercise&language=en') result1 = response.data['suggestions'][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 4) self.assertEqual(result1['value'], 'An exercise') self.assertEqual(result1['data']['id'], 1) def test_search_language_code_en_no_results(self): """ The "Testübung" exercise should not be found when searching in English """ response = self.client.get(self.url + '?term=Testübung&language=en') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 0) def test_search_language_code_de(self): """ The "Testübung" exercise should be only found when searching in German """ response = self.client.get(self.url + '?term=Testübung&language=de') result1 = response.data['suggestions'][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 1) self.assertEqual(result1['value'], 'Weitere Testübung') self.assertEqual(result1['data']['id'], 7) def test_search_several_language_codes(self): """ Passing different language codes works correctly """ response = self.client.get(self.url + '?term=demo&language=en,de') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 4) def test_search_all_languages(self): """ Passing different language codes works correctly """ response = self.client.get(self.url + '?term=demo&language=*') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 4)
4,105
Python
.py
86
40.732558
78
0.681602
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,728
test_exercise_images.py
wger-project_wger/wger/exercises/tests/test_exercise_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.core.files import File from django.urls import reverse # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.exercises.models import ( Exercise, ExerciseImage, ) class MainImageTestCase(WgerTestCase): """ Tests the methods to make sure there is always a main image per picture """ def save_image(self, exercise, filename, db_filename=None) -> int: """ Helper function to save an image to an exercise """ with open(f'wger/exercises/tests/{filename}', 'rb') as inFile: if not db_filename: db_filename = filename image = ExerciseImage() image.exercise_base = exercise.exercise_base image.image.save(db_filename, File(inFile)) image.save() return image.pk def test_auto_main_image(self): """ Tests that the first uploaded image is automatically a main image """ exercise = Exercise.objects.get(pk=2) pk = self.save_image(exercise, 'protestschwein.jpg') image = ExerciseImage.objects.get(pk=pk) self.assertTrue(image.is_main) def test_auto_main_image_multiple(self): """ Tests that there is always a main image after deleting one """ exercise = Exercise.objects.get(pk=2) pk1 = self.save_image(exercise, 'protestschwein.jpg') pk2 = self.save_image(exercise, 'wildschwein.jpg') image = ExerciseImage.objects.get(pk=pk1) self.assertTrue(image.is_main) image = ExerciseImage.objects.get(pk=pk2) self.assertFalse(image.is_main) def test_delete_main_image(self): """ Tests that there is always a main image after deleting one """ exercise = Exercise.objects.get(pk=2) pk1 = self.save_image(exercise, 'protestschwein.jpg') pk2 = self.save_image(exercise, 'protestschwein.jpg') pk3 = self.save_image(exercise, 'wildschwein.jpg') pk4 = self.save_image(exercise, 'wildschwein.jpg') pk5 = self.save_image(exercise, 'wildschwein.jpg') image = ExerciseImage.objects.get(pk=pk1) self.assertTrue(image.is_main) image.delete() self.assertFalse(ExerciseImage.objects.get(pk=pk2).is_main) self.assertFalse(ExerciseImage.objects.get(pk=pk3).is_main) self.assertFalse(ExerciseImage.objects.get(pk=pk4).is_main) self.assertFalse(ExerciseImage.objects.get(pk=pk5).is_main) image = ExerciseImage.objects.get(pk=pk2) self.assertFalse(image.is_main) image.delete() self.assertFalse(ExerciseImage.objects.get(pk=pk3).is_main) self.assertFalse(ExerciseImage.objects.get(pk=pk4).is_main) self.assertFalse(ExerciseImage.objects.get(pk=pk5).is_main) # TODO: add POST and DELETE tests class ExerciseImagesApiTestCase( api_base_test.BaseTestCase, api_base_test.ApiBaseTestCase, api_base_test.ApiGetTestCase, ): """ Tests the exercise image resource """ pk = 1 private_resource = False resource = ExerciseImage overview_cached = True
3,922
Python
.py
99
33.111111
78
0.6899
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,729
test_categories.py
wger-project_wger/wger/exercises/tests/test_categories.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 import api_base_test from wger.core.tests.base_testcase import ( WgerAccessTestCase, WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.exercises.models import ExerciseCategory class ExerciseCategoryRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(ExerciseCategory.objects.get(pk=1)), 'Category') class CategoryOverviewTestCase(WgerAccessTestCase): """ Test that only admins see the edit links """ url = 'exercise:category:list' anonymous_fail = True user_success = 'admin' user_fail = ( 'manager1', 'manager2' 'general_manager1', 'manager3', 'manager4', 'test', 'member1', 'member2', 'member3', 'member4', 'member5', ) class DeleteExerciseCategoryTestCase(WgerDeleteTestCase): """ Exercise category delete test case """ object_class = ExerciseCategory url = 'exercise:category:delete' pk = 4 user_success = 'admin' user_fail = 'test' class EditExerciseCategoryTestCase(WgerEditTestCase): """ Tests editing an exercise category """ object_class = ExerciseCategory url = 'exercise:category:edit' pk = 3 data = {'name': 'A different name'} class AddExerciseCategoryTestCase(WgerAddTestCase): """ Tests adding an exercise category """ object_class = ExerciseCategory url = 'exercise:category:add' data = {'name': 'A new category'} class ExerciseCategoryApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the exercise category overview resource """ pk = 2 resource = ExerciseCategory private_resource = False overview_cached = True
2,592
Python
.py
83
26.481928
78
0.71004
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,730
test_exercise_comments.py
wger-project_wger/wger/exercises/tests/test_exercise_comments.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.api_base_test import ExerciseCrudApiTestCase from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ExerciseComment class ExerciseCommentRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(ExerciseComment.objects.get(pk=1)), 'test 123') class ExerciseCommentApiTestCase(ExerciseCrudApiTestCase): """ Tests the exercise comment overview resource """ pk = 1 resource = ExerciseComment data = { 'comment': 'a cool comment', 'exercise': '1', 'id': 1, }
1,399
Python
.py
37
33.918919
78
0.743911
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,731
test_deletion_log.py
wger-project_wger/wger/exercises/tests/test_deletion_log.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 uuid import UUID # wger from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( DeletionLog, Exercise, ExerciseBase, ) class DeletionLogTestCase(WgerTestCase): """ Test that the deletion log entries are correctly generated """ def test_base(self): """ Test that an entry is generated when a base is deleted """ self.assertEqual(DeletionLog.objects.all().count(), 0) base = ExerciseBase.objects.get(pk=1) base.delete() # Base is deleted count_base_logs = DeletionLog.objects.filter( model_type=DeletionLog.MODEL_BASE, uuid=base.uuid, ).count() log = DeletionLog.objects.get(pk=1) self.assertEqual(count_base_logs, 1) self.assertEqual(log.model_type, 'base') self.assertEqual(log.uuid, base.uuid) self.assertEqual(log.comment, 'Exercise base of An exercise') self.assertEqual(log.replaced_by, None) # All translations are also deleted count = DeletionLog.objects.filter(model_type=DeletionLog.MODEL_TRANSLATION).count() self.assertEqual(count, 2) # First translation log2 = DeletionLog.objects.get(pk=4) self.assertEqual(log2.model_type, 'translation') self.assertEqual(log2.uuid, UUID('9838235c-e38f-4ca6-921e-9d237d8e0813')) self.assertEqual(log2.comment, 'An exercise') self.assertEqual(log2.replaced_by, None) # Second translation log3 = DeletionLog.objects.get(pk=5) self.assertEqual(log3.model_type, 'translation') self.assertEqual(log3.uuid, UUID('13b532f9-d208-462e-a000-7b9982b2b53e')) self.assertEqual(log3.comment, 'Test exercise 123') self.assertEqual(log3.replaced_by, None) def test_base_with_replaced_by(self): """ Test that an entry is generated when a base is deleted and the replaced by is set correctly """ self.assertEqual(DeletionLog.objects.all().count(), 0) exercise = ExerciseBase.objects.get(pk=1) exercise.delete(replace_by='ae3328ba-9a35-4731-bc23-5da50720c5aa') # Base is deleted log = DeletionLog.objects.get(pk=1) self.assertEqual(log.model_type, 'base') self.assertEqual(log.uuid, exercise.uuid) self.assertEqual(log.replaced_by, UUID('ae3328ba-9a35-4731-bc23-5da50720c5aa')) def test_base_with_nonexistent_replaced_by(self): """ Test that an entry is generated when a base is deleted and the replaced by is set correctly. If the UUID is not found in the DB, it's set to None """ self.assertEqual(DeletionLog.objects.all().count(), 0) exercise = ExerciseBase.objects.get(pk=1) exercise.delete(replace_by='12345678-1234-1234-1234-1234567890ab') # Base is deleted log = DeletionLog.objects.get(pk=1) self.assertEqual(log.model_type, 'base') self.assertEqual(log.replaced_by, None) def test_translation(self): """ Test that an entry is generated when a translation is deleted """ self.assertEqual(DeletionLog.objects.all().count(), 0) translation = Exercise.objects.get(pk=1) translation.delete() # Translation is deleted count = DeletionLog.objects.filter( model_type=DeletionLog.MODEL_TRANSLATION, uuid=translation.uuid ).count() self.assertEqual(count, 1)
4,185
Python
.py
96
36.322917
92
0.686009
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,732
test_exercise_base.py
wger-project_wger/wger/exercises/tests/test_exercise_base.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 uuid import UUID # Third Party from rest_framework import status # wger from wger.core.tests.api_base_test import ExerciseCrudApiTestCase from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( DeletionLog, Exercise, ExerciseBase, ) from wger.utils.constants import CC_BY_SA_4_ID class ExerciseBaseTestCase(WgerTestCase): """ Test the different features of an exercise and its base """ @staticmethod def get_ids(queryset): """Helper to return the IDs of the objects in a queryset""" return sorted([i.id for i in queryset.all()]) def test_base(self): """ Test that the properties return the correct data """ translation = Exercise.objects.get(pk=1) exercise = translation.exercise_base self.assertEqual(exercise.category, translation.category) self.assertListEqual(self.get_ids(exercise.equipment), self.get_ids(translation.equipment)) self.assertListEqual(self.get_ids(exercise.muscles), self.get_ids(translation.muscles)) self.assertListEqual( self.get_ids(exercise.muscles_secondary), self.get_ids(translation.muscles_secondary), ) def test_language_utils_translation_exists(self): """ Test that the base correctly returns translated exercises """ exercise = ExerciseBase.objects.get(pk=1).get_translation('de') self.assertEqual(exercise.name, 'An exercise') def test_language_utils_no_translation_exists(self): """ Test that the base correctly returns the English translation if the requested language does not exist """ exercise = ExerciseBase.objects.get(pk=1).get_translation('fr') self.assertEqual(exercise.name, 'Test exercise 123') def test_language_utils_no_translation_fallback(self): """ Test that the base correctly returns the first translation if for whatever reason English is not available """ exercise = ExerciseBase.objects.get(pk=2).get_translation('pt') self.assertEqual(exercise.name, 'Very cool exercise') def test_variations(self): """Test that the variations are correctly returned""" # Even if these exercises have the same base, only the variations for # their respective languages are returned. exercise = ExerciseBase.objects.get(pk=1) self.assertListEqual(sorted([i.id for i in exercise.base_variations]), [2]) exercise2 = ExerciseBase.objects.get(pk=3) self.assertEqual(sorted([i.id for i in exercise2.base_variations]), [4]) def test_images(self): """Test that the correct images are returned for the exercises""" translation = Exercise.objects.get(pk=1) exercise = translation.exercise_base self.assertListEqual( self.get_ids(translation.images), self.get_ids(exercise.exerciseimage_set) ) class ExerciseCustomApiTestCase(ExerciseCrudApiTestCase): pk = 1 data = { 'category': 3, 'muscles': [1, 3], 'muscles_secondary': [2], 'equipment': [3], 'variations': 4, } def get_resource_name(self): return 'exercise-base' def test_delete_replace_by(self): """Test that setting the replaced_by attribute works""" self.authenticate('admin') url = self.url_detail + '?replaced_by=ae3328ba-9a35-4731-bc23-5da50720c5aa' response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) log = DeletionLog.objects.get(pk=1) self.assertEqual(log.model_type, 'base') self.assertEqual(log.uuid, UUID('acad3949-36fb-4481-9a72-be2ddae2bc05')) self.assertEqual(log.replaced_by, UUID('ae3328ba-9a35-4731-bc23-5da50720c5aa')) def test_cant_change_license(self): """ Test that it is not possible to change the license of an existing exercise base """ exercise = ExerciseBase.objects.get(pk=self.pk) self.assertEqual(exercise.license_id, 2) self.authenticate('trainer1') response = self.client.patch(self.url_detail, data={'license': 3}) self.assertEqual(response.status_code, status.HTTP_200_OK) exercise = ExerciseBase.objects.get(pk=self.pk) self.assertEqual(exercise.license_id, 2) def test_cant_set_license(self): """ Test that it is not possible to set the license for a newly created exercise base (the license is always set to the default) """ self.data['license'] = 3 self.authenticate('trainer1') response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) exercise = ExerciseBase.objects.get(pk=self.pk) self.assertEqual(exercise.license_id, CC_BY_SA_4_ID)
5,633
Python
.py
126
37.626984
99
0.691802
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,733
test_exercise_api_cache.py
wger-project_wger/wger/exercises/tests/test_exercise_api_cache.py
# This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # Django from django.core.cache import cache # wger from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( Alias, Exercise, ExerciseBase, ExerciseComment, ) from wger.utils.cache import cache_mapper class ExerciseApiCacheTestCase(WgerTestCase): """ Tests the API cache for the exercisebaseinfo endpoint """ exercise_id = 1 exercise_uuid = 'acad3949-36fb-4481-9a72-be2ddae2bc05' url = '/api/v2/exercisebaseinfo/1/' cache_key = cache_mapper.get_exercise_api_key('acad3949-36fb-4481-9a72-be2ddae2bc05') def test_edit_exercise(self): """ Tests editing an exercise """ self.assertFalse(cache.get(self.cache_key)) self.client.get(self.url) self.assertTrue(cache.get(self.cache_key)) exercise = ExerciseBase.objects.get(pk=1) exercise.category_id = 1 exercise.save() self.assertFalse(cache.get(self.cache_key)) def test_delete_exercise(self): """ Tests deleting an exercise """ self.assertFalse(cache.get(self.cache_key)) self.client.get(self.url) self.assertTrue(cache.get(self.cache_key)) exercise = ExerciseBase.objects.get(pk=1) exercise.delete() self.assertFalse(cache.get(self.cache_key)) def test_edit_translation(self): """ Tests editing a translation """ self.assertFalse(cache.get(self.cache_key)) self.client.get(self.url) self.assertTrue(cache.get(self.cache_key)) translation = Exercise.objects.get(pk=1) translation.name = 'something else' translation.save() self.assertFalse(cache.get(self.cache_key)) def test_delete_translation(self): """ Tests deleting a translation """ self.assertFalse(cache.get(self.cache_key)) self.client.get(self.url) self.assertTrue(cache.get(self.cache_key)) translation = Exercise.objects.get(pk=1) translation.delete() self.assertFalse(cache.get(self.cache_key)) def test_edit_comment(self): """ Tests editing a comment """ self.assertFalse(cache.get(self.cache_key)) self.client.get(self.url) self.assertTrue(cache.get(self.cache_key)) comment = ExerciseComment.objects.get(pk=1) comment.name = 'The Shiba Inu (柴犬) is a breed of hunting dog from Japan' comment.save() self.assertFalse(cache.get(self.cache_key)) def test_delete_comment(self): """ Tests deleting a comment """ self.assertFalse(cache.get(self.cache_key)) self.client.get(self.url) self.assertTrue(cache.get(self.cache_key)) comment = ExerciseComment.objects.get(pk=1) comment.delete() self.assertFalse(cache.get(self.cache_key)) def test_edit_alias(self): """ Tests editing an alias """ self.assertFalse(cache.get(self.cache_key)) self.client.get(self.url) self.assertTrue(cache.get(self.cache_key)) alias = Alias.objects.get(pk=1) alias.name = 'Hachikō' alias.save() self.assertFalse(cache.get(self.cache_key)) def test_delete_alias(self): """ Tests deleting an alias """ self.assertFalse(cache.get(self.cache_key)) self.client.get(self.url) self.assertTrue(cache.get(self.cache_key)) alias = Alias.objects.get(pk=1) alias.delete() self.assertFalse(cache.get(self.cache_key))
4,275
Python
.py
116
29.655172
89
0.665131
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,734
test_alias.py
wger-project_wger/wger/exercises/tests/test_alias.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.api_base_test import ExerciseCrudApiTestCase class AliasCustomApiTestCase(ExerciseCrudApiTestCase): pk = 1 data = { 'exercise': 1, 'alias': 'Alias 123', } def get_resource_name(self): return 'exercisealias'
919
Python
.py
23
37
78
0.760943
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,735
test_equipment.py
wger-project_wger/wger/exercises/tests/test_equipment.py
# This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. # Django from django.urls import reverse # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.exercises.models import Equipment from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE class EquipmentRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(Equipment.objects.get(pk=1)), 'Dumbbells') class AddEquipmentTestCase(WgerAddTestCase): """ Tests adding a new equipment """ object_class = Equipment url = 'exercise:equipment:add' data = {'name': 'A new equipment'} class DeleteEquipmentTestCase(WgerDeleteTestCase): """ Tests deleting an equipment """ object_class = Equipment url = 'exercise:equipment:delete' pk = 1 class EditEquipmentTestCase(WgerEditTestCase): """ Tests editing an equipment """ object_class = Equipment url = 'exercise:equipment:edit' pk = 1 data = {'name': 'A new name'} class EquipmentListTestCase(WgerTestCase): """ Tests the equipment list page (admin view) """ def test_overview(self): # Add more equipments so we can test the pagination self.user_login('admin') data = {'name': 'A new entry'} for i in range(0, 50): self.client.post(reverse('exercise:equipment:add'), data) # Page exists and the pagination works response = self.client.get(reverse('exercise:equipment:list')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['equipment_list']), PAGINATION_OBJECTS_PER_PAGE) response = self.client.get(reverse('exercise:equipment:list'), {'page': 2}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['equipment_list']), PAGINATION_OBJECTS_PER_PAGE) response = self.client.get(reverse('exercise:equipment:list'), {'page': 3}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['equipment_list']), 3) # 'last' is a special case response = self.client.get(reverse('exercise:equipment:list'), {'page': 'last'}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['equipment_list']), 3) # Page does not exist response = self.client.get(reverse('exercise:equipment:list'), {'page': 100}) self.assertEqual(response.status_code, 404) response = self.client.get(reverse('exercise:equipment:list'), {'page': 'foobar'}) self.assertEqual(response.status_code, 404) class EquipmentApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the equipment overview resource """ pk = 1 resource = Equipment private_resource = False overview_cached = True
3,786
Python
.py
94
34.957447
94
0.708129
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,736
test_exercise_translation.py
wger-project_wger/wger/exercises/tests/test_exercise_translation.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 # Django from django.core.cache import cache from django.template import ( Context, Template, ) from django.urls import reverse # Third Party from rest_framework import status # wger from wger.core.tests import api_base_test from wger.core.tests.api_base_test import ExerciseCrudApiTestCase from wger.core.tests.base_testcase import ( WgerDeleteTestCase, WgerTestCase, ) from wger.exercises.models import ( Exercise, Muscle, ) from wger.utils.cache import cache_mapper from wger.utils.constants import CC_BY_SA_4_ID class ExerciseRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(Exercise.objects.get(pk=1)), 'An exercise') class ExercisesTestCase(WgerTestCase): """ Exercise test case """ def search_exercise(self, fail=True): """ Helper function to test searching for exercises """ # 1 hit, "Very cool exercise" response = self.client.get(reverse('exercise-search'), {'term': 'cool'}) self.assertEqual(response.status_code, 200) result = json.loads(response.content.decode('utf8')) self.assertEqual(len(result), 1) self.assertEqual(result['suggestions'][0]['value'], 'Very cool exercise') self.assertEqual(result['suggestions'][0]['data']['id'], 2) self.assertEqual(result['suggestions'][0]['data']['category'], 'Another category') self.assertEqual(result['suggestions'][0]['data']['image'], None) self.assertEqual(result['suggestions'][0]['data']['image_thumbnail'], None) # 0 hits, "Pending exercise" response = self.client.get(reverse('exercise-search'), {'term': 'Foobar'}) self.assertEqual(response.status_code, 200) result = json.loads(response.content.decode('utf8')) self.assertEqual(len(result['suggestions']), 0) def test_search_exercise_anonymous(self): """ Test deleting an exercise by an anonymous user """ self.search_exercise() def test_search_exercise_logged_in(self): """ Test deleting an exercise by a logged-in user """ self.user_login('test') self.search_exercise() def test_exercise_records_historical_data(self): """ Test that changing exercise details generates a historical record """ exercise = Exercise.objects.get(pk=2) self.assertEqual(len(exercise.history.all()), 0) exercise.name = 'Very cool exercise 2' exercise.description = 'New description' exercise.exercise_base.muscles_secondary.add(Muscle.objects.get(pk=2)) exercise.save() exercise = Exercise.objects.get(pk=2) self.assertEqual(len(exercise.history.all()), 1) class MuscleTemplateTagTest(WgerTestCase): def test_render_main_muscles(self): """ Test that the tag renders only the main muscles """ context = Context({'muscles': Muscle.objects.get(pk=2)}) template = Template('{% load wger_extras %}' '{% render_muscles muscles %}') rendered_template = template.render(context) self.assertIn('images/muscles/main/muscle-2.svg', rendered_template) self.assertNotIn('images/muscles/secondary/', rendered_template) self.assertIn('images/muscles/muscular_system_back.svg', rendered_template) def test_render_main_muscles_empty_secondary(self): """ Test that the tag works when giben main muscles and empty secondary ones """ context = Context({'muscles': Muscle.objects.get(pk=2), 'muscles_sec': []}) template = Template('{% load wger_extras %}' '{% render_muscles muscles muscles_sec %}') rendered_template = template.render(context) self.assertIn('images/muscles/main/muscle-2.svg', rendered_template) self.assertNotIn('images/muscles/secondary/', rendered_template) self.assertIn('images/muscles/muscular_system_back.svg', rendered_template) def test_render_secondary_muscles(self): """ Test that the tag renders only the secondary muscles """ context = Context({'muscles': Muscle.objects.get(pk=1)}) template = Template('{% load wger_extras %}' '{% render_muscles muscles_sec=muscles %}') rendered_template = template.render(context) self.assertIn('images/muscles/secondary/muscle-1.svg', rendered_template) self.assertNotIn('images/muscles/main/', rendered_template) self.assertIn('images/muscles/muscular_system_front.svg', rendered_template) def test_render_secondary_muscles_empty_primary(self): """ Test that the tag works when given secondary muscles and empty main ones """ context = Context({'muscles_sec': Muscle.objects.get(pk=1), 'muscles': []}) template = Template('{% load wger_extras %}' '{% render_muscles muscles muscles_sec %}') rendered_template = template.render(context) self.assertIn('images/muscles/secondary/muscle-1.svg', rendered_template) self.assertNotIn('images/muscles/main/', rendered_template) self.assertIn('images/muscles/muscular_system_front.svg', rendered_template) def test_render_secondary_muscles_list(self): """ Test that the tag works when given a list for secondary muscles and empty main ones """ context = Context({'muscles_sec': Muscle.objects.filter(is_front=True), 'muscles': []}) template = Template('{% load wger_extras %}' '{% render_muscles muscles muscles_sec %}') rendered_template = template.render(context) self.assertIn('images/muscles/secondary/muscle-1.svg', rendered_template) self.assertNotIn('images/muscles/secondary/muscle-2.svg', rendered_template) self.assertNotIn('images/muscles/secondary/muscle-3.svg', rendered_template) self.assertIn('images/muscles/muscular_system_front.svg', rendered_template) self.assertNotIn('images/muscles/muscular_system_back.svg', rendered_template) def test_render_muscle_list(self): """ Test that the tag works when given a list for main and secondary muscles """ context = Context( { 'muscles_sec': Muscle.objects.filter(id__in=[5, 6]), 'muscles': Muscle.objects.filter(id__in=[1, 4]), } ) template = Template('{% load wger_extras %}' '{% render_muscles muscles muscles_sec %}') rendered_template = template.render(context) self.assertIn('images/muscles/main/muscle-1.svg', rendered_template) self.assertNotIn('images/muscles/main/muscle-2.svg', rendered_template) self.assertNotIn('images/muscles/main/muscle-3.svg', rendered_template) self.assertIn('images/muscles/main/muscle-4.svg', rendered_template) self.assertIn('images/muscles/secondary/muscle-5.svg', rendered_template) self.assertIn('images/muscles/secondary/muscle-6.svg', rendered_template) self.assertIn('images/muscles/muscular_system_front.svg', rendered_template) self.assertNotIn('images/muscles/muscular_system_back.svg', rendered_template) def test_render_empty(self): """ Test that the tag works when given empty input """ context = Context({'muscles': [], 'muscles_sec': []}) template = Template('{% load wger_extras %}' '{% render_muscles muscles muscles_sec %}') rendered_template = template.render(context) self.assertEqual(rendered_template, '\n\n') def test_render_no_parameters(self): """ Test that the tag works when given no parameters """ template = Template('{% load wger_extras %}' '{% render_muscles %}') rendered_template = template.render(Context({})) self.assertEqual(rendered_template, '\n\n') class WorkoutCacheTestCase(WgerTestCase): """ Workout cache test case """ def test_canonical_form_cache_save(self): """ Tests the workout cache when saving """ exercise = Exercise.objects.get(pk=2) for setting in exercise.exercise_base.setting_set.all(): setting.set.exerciseday.training.canonical_representation workout_id = setting.set.exerciseday.training_id self.assertTrue(cache.get(cache_mapper.get_workout_canonical(workout_id))) exercise.save() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(workout_id))) def test_canonical_form_cache_delete(self): """ Tests the workout cache when deleting """ exercise = Exercise.objects.get(pk=2) workout_ids = [] for setting in exercise.exercise_base.setting_set.all(): workout_id = setting.set.exerciseday.training_id workout_ids.append(workout_id) setting.set.exerciseday.training.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(workout_id))) exercise.delete() for workout_id in workout_ids: self.assertFalse(cache.get(cache_mapper.get_workout_canonical(workout_id))) # TODO: fix test, all registered users can upload exercises class ExerciseApiTestCase( api_base_test.BaseTestCase, api_base_test.ApiBaseTestCase, api_base_test.ApiGetTestCase ): """ Tests the exercise overview resource """ pk = 1 resource = Exercise private_resource = False overview_cached = True class ExerciseInfoApiTestCase( api_base_test.BaseTestCase, api_base_test.ApiBaseTestCase, api_base_test.ApiGetTestCase, ): """ Tests the exercise info resource """ pk = 1 private_resource = False overview_cached = True def get_resource_name(self): return 'exerciseinfo' class ExerciseBaseInfoApiTestCase( api_base_test.BaseTestCase, api_base_test.ApiBaseTestCase, api_base_test.ApiGetTestCase, ): """ Tests the exercise base info resource """ pk = 1 private_resource = False overview_cached = True def get_resource_name(self): return 'exercisebaseinfo' class ExerciseCustomApiTestCase(ExerciseCrudApiTestCase): pk = 1 data = { 'name': 'A new name', 'description': 'The wild boar is a suid native to much of Eurasia and North Africa', 'language': 1, 'exercise_base': 2, } def get_resource_name(self): return 'exercise-translation' def test_cant_change_base_id(self): """ Test that it is not possible to change the base id of an existing exercise translation. """ exercise = Exercise.objects.get(pk=self.pk) self.assertEqual(exercise.exercise_base_id, 1) self.authenticate('trainer1') response = self.client.patch(self.url_detail, data={'exercise_base': 2}) self.assertEqual(response.status_code, status.HTTP_200_OK) exercise = Exercise.objects.get(pk=self.pk) self.assertEqual(exercise.exercise_base_id, 1) def test_cant_change_language(self): """ Test that it is not possible to change the language id of an existing exercise translation. """ exercise = Exercise.objects.get(pk=self.pk) self.assertEqual(exercise.language_id, 2) self.authenticate('trainer1') response = self.client.patch(self.url_detail, data={'language': 1}) self.assertEqual(response.status_code, status.HTTP_200_OK) exercise = Exercise.objects.get(pk=self.pk) self.assertEqual(exercise.language_id, 2) def test_cant_change_license(self): """ Test that it is not possible to change the license of an existing exercise translation. """ exercise = Exercise.objects.get(pk=self.pk) self.assertEqual(exercise.license_id, 2) self.authenticate('trainer1') response = self.client.patch(self.url_detail, data={'license': 3}) self.assertEqual(response.status_code, status.HTTP_200_OK) exercise = Exercise.objects.get(pk=self.pk) self.assertEqual(exercise.license_id, 2) def test_cant_set_license(self): """ Test that it is not possible to set the license for a newly created exercise translation (the license is always set to the default) """ self.data['license'] = 3 self.authenticate('trainer1') response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) exercise = Exercise.objects.get(pk=self.pk) self.assertEqual(exercise.license_id, CC_BY_SA_4_ID) def test_patch_clean_html(self): """ Test that the description field has its HTML stripped before saving """ description = '<script>alert();</script> The wild boar is a suid native...' self.authenticate('trainer1') response = self.client.patch(self.url_detail, data={'description': description}) self.assertEqual(response.status_code, status.HTTP_200_OK) exercise = Exercise.objects.get(pk=self.pk) self.assertEqual(exercise.description, 'alert(); The wild boar is a suid native...') def test_post_only_one_language_per_base(self): """ Test that it's not possible to add a second translation for the same base in the same language. """ self.authenticate('trainer1') response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) response = self.client.post(self.url, data=self.data) self.assertTrue(response.data['non_field_errors']) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_set_existing_language(self): """ Test that it is possible to set the language if it doesn't duplicate a translation """ self.authenticate('trainer1') response = self.client.patch(self.url_detail, data={'language': 1, 'name': '123456'}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertFalse(response.data.get('non_field_errors')) def test_edit_only_one_language_per_base(self): """ Test that it's not possible to edit a translation to a second language for the same base """ self.authenticate('trainer1') response = self.client.patch(self.url_detail, data={'language': 3}) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertTrue(response.data['non_field_errors'])
15,538
Python
.py
340
38.123529
96
0.674051
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,737
test_management_commands.py
wger-project_wger/wger/exercises/tests/test_management_commands.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 io import StringIO from unittest.mock import patch # Django from django.core.management import call_command from django.test import SimpleTestCase # wger from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( Exercise, ExerciseBase, ) class TestSyncManagementCommands(SimpleTestCase): @patch('wger.exercises.sync.handle_deleted_entries') @patch('wger.exercises.sync.sync_muscles') @patch('wger.exercises.sync.sync_languages') @patch('wger.exercises.sync.sync_exercises') @patch('wger.exercises.sync.sync_equipment') @patch('wger.exercises.sync.sync_categories') @patch('wger.exercises.sync.sync_licenses') def test_sync_exercises( self, mock_sync_licenses, mock_sync_categories, mock_sync_equipment, mock_sync_exercises, mock_sync_languages, mock_sync_muscles, mock_delete_entries, ): call_command('sync-exercises') mock_sync_licenses.assert_called() mock_sync_categories.assert_called() mock_sync_equipment.assert_called() mock_sync_exercises.assert_called() mock_sync_languages.assert_called() mock_sync_muscles.assert_called() mock_delete_entries.assert_called() @patch('wger.exercises.sync.download_exercise_images') def test_download_exercise_images(self, mock_download_exercise_images): call_command('download-exercise-images') mock_download_exercise_images.assert_called() @patch('wger.exercises.sync.download_exercise_videos') def test_download_exercise_videos(self, mock_download_exercise_videos): call_command('download-exercise-videos') mock_download_exercise_videos.assert_called() class TestHealthCheckManagementCommands(WgerTestCase): def setUp(self): super().setUp() self.out = StringIO() def test_find_no_problems(self): call_command('exercises-health-check', stdout=self.out) self.assertEqual('', self.out.getvalue()) def test_find_untranslated(self): Exercise.objects.get(pk=1).delete() Exercise.objects.get(pk=5).delete() call_command('exercises-health-check', stdout=self.out) self.assertIn( 'Exercise acad3949-36fb-4481-9a72-be2ddae2bc05 has no translations!', self.out.getvalue(), ) self.assertNotIn('-> deleted', self.out.getvalue()) def atest_fix_untranslated(self): Exercise.objects.get(pk=1).delete() call_command('exercises-health-check', '--delete-untranslated', stdout=self.out) self.assertIn('-> deleted', self.out.getvalue()) self.assertRaises(ExerciseBase.DoesNotExist, ExerciseBase.objects.get, pk=1) def test_find_no_english_translation(self): Exercise.objects.get(pk=1).delete() call_command('exercises-health-check', stdout=self.out) self.assertIn( 'Exercise acad3949-36fb-4481-9a72-be2ddae2bc05 has no English translation!', self.out.getvalue(), ) self.assertNotIn('-> deleted', self.out.getvalue()) def test_fix_no_english_translation(self): Exercise.objects.get(pk=1).delete() call_command('exercises-health-check', '--delete-no-english', stdout=self.out) self.assertIn('-> deleted', self.out.getvalue()) self.assertRaises(ExerciseBase.DoesNotExist, ExerciseBase.objects.get, pk=1) def test_find_duplicate_translations(self): exercise = Exercise.objects.get(pk=1) exercise.language_id = 3 exercise.save() call_command('exercises-health-check', stdout=self.out) self.assertIn( 'Exercise acad3949-36fb-4481-9a72-be2ddae2bc05 has duplicate translations!', self.out.getvalue(), ) self.assertNotIn('-> deleted', self.out.getvalue()) def test_fix_duplicate_translations(self): exercise = Exercise.objects.get(pk=1) exercise.language_id = 3 exercise.save() call_command('exercises-health-check', '--delete-duplicate-translations', stdout=self.out) self.assertIn('Deleting all but first fr translation', self.out.getvalue()) self.assertRaises(Exercise.DoesNotExist, Exercise.objects.get, pk=5)
4,960
Python
.py
110
38.309091
98
0.704103
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,738
test_muscles.py
wger-project_wger/wger/exercises/tests/test_muscles.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 import api_base_test from wger.core.tests.base_testcase import ( WgerAccessTestCase, WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.exercises.models import Muscle class MuscleRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(Muscle.objects.get(pk=1)), 'Anterior testoid') # Check image URL properties self.assertIn('images/muscles/main/muscle-2.svg', Muscle.objects.get(pk=2).image_url_main) self.assertIn( 'images/muscles/secondary/muscle-1.svg', Muscle.objects.get(pk=1).image_url_secondary ) class MuscleAdminOverviewTest(WgerAccessTestCase): """ Tests the admin muscle overview page """ url = 'exercise:muscle:admin-list' anonymous_fail = True user_success = 'admin' user_fail = ( 'manager1', 'manager2' 'general_manager1', 'manager3', 'manager4', 'test', 'member1', 'member2', 'member3', 'member4', 'member5', ) class AddMuscleTestCase(WgerAddTestCase): """ Tests adding a muscle """ object_class = Muscle url = 'exercise:muscle:add' data = {'name': 'A new muscle', 'is_front': True, 'name_en': 'Other muscle'} class EditMuscleTestCase(WgerEditTestCase): """ Tests editing a muscle """ object_class = Muscle url = 'exercise:muscle:edit' pk = 1 data = {'name': 'The new name', 'is_front': True, 'name_en': 'Edited muscle'} class DeleteMuscleTestCase(WgerDeleteTestCase): """ Tests deleting a muscle """ object_class = Muscle url = 'exercise:muscle:delete' pk = 1 class MuscleApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the muscle overview resource """ pk = 1 resource = Muscle private_resource = False overview_cached = True data = {'name': 'The name', 'is_front': True, 'name_en': 'name en'} def test_get_detail(self): super().test_get_detail() # Check that image URLs are present in response response = self.client.get(self.url_detail) response_object = response.json() self.assertIn('images/muscles/main/muscle-1.svg', response_object['image_url_main']) self.assertIn( 'images/muscles/secondary/muscle-1.svg', response_object['image_url_secondary'] )
3,247
Python
.py
96
28.385417
98
0.67977
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,739
test_sync.py
wger-project_wger/wger/exercises/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 unittest.mock import patch # wger from wger.core.models import ( Language, License, ) from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( Equipment, Exercise, ExerciseBase, ExerciseCategory, Muscle, ) from wger.exercises.sync import ( handle_deleted_entries, sync_categories, sync_equipment, sync_exercises, sync_languages, sync_licenses, sync_muscles, ) from wger.manager.models import ( Setting, WorkoutLog, ) from wger.utils.requests import wger_headers class MockLanguageResponse: def __init__(self): self.status_code = 200 self.content = b'1234' # yapf: disable @staticmethod def json(): return { "count": 24, "next": None, "previous": None, "results": [ { "id": 1, "short_name": "de", "full_name": "Daitsch", "full_name_en": "Kraut" }, { "id": 2, "short_name": "en", "full_name": "English", "full_name_en": "English" }, { "id": 3, "short_name": "fr", "full_name": "Français", "full_name_en": "French" }, { "id": 4, "short_name": "es", "full_name": "Español", "full_name_en": "Spanish" }, { "id": 19, "short_name": "eo", "full_name": "Esperanto", "full_name_en": "Esperanto" } ] } # yapf: enable class MockLicenseResponse: def __init__(self): self.status_code = 200 self.content = b'' # yapf: disable @staticmethod def json(): return { "count": 4, "next": None, "previous": None, "results": [ { "id": 1, "full_name": "A cool and free license - Germany", "short_name": "ACAFL - DE", "url": "http://creativecommons.org/licenses/aca/fl/4.0/" }, { "id": 2, "full_name": " Another cool license 2.1", "short_name": "ACL 2.1", "url": "https://another-cool-license.org/acl-2.1" }, { "id": 5, "url": "https://another-cool-license.org/acl-2.2", "full_name": "Another cool license 2.2", "short_name": "ACL 2.2" }, { "id": 3, "full_name": "Creative Commons Attribution Share Alike 4", "short_name": "CC-BY-SA 4", "url": "https://creativecommons.org/licenses/by-sa/4.0/deed.en" }, ] } # yapf: enable class MockCategoryResponse: def __init__(self): self.status_code = 200 self.content = b'1234' # yapf: disable @staticmethod def json(): return { "count": 6, "next": None, "previous": None, "results": [ { "id": 1, "name": "A cooler, swaggier category" }, { "id": 2, "name": "Another category" }, { "id": 3, "name": "Yet another category" }, { "id": 4, "name": "Calves" }, { "id": 5, "name": "Cardio" }, { "id": 16, "name": "Chest" } ] } # yapf: enable class MockMuscleResponse: def __init__(self): self.status_code = 200 self.content = b'' # yapf: disable @staticmethod def json(): return { "count": 4, "next": None, "previous": None, "results": [ { "id": 1, "name": "Anterior testoid", "name_en": "Testoulders", "is_front": True, "image_url_main": "/static/images/muscles/main/muscle-1.svg", "image_url_secondary": "/static/images/muscles/secondary/muscle-1.svg" }, { "id": 2, "name": "Novum musculus nomen eius", "name_en": "Testceps", "is_front": True, "image_url_main": "/static/images/muscles/main/muscle-2.svg", "image_url_secondary": "/static/images/muscles/secondary/muscle-2.svg" }, { "id": 3, "name": "Biceps notusensis", "name_en": "", "is_front": False, "image_url_main": "/static/images/muscles/main/muscle-3.svg", "image_url_secondary": "/static/images/muscles/secondary/muscle-3.svg" }, { "id": 10, "name": "Pectoralis major", "name_en": "Chest", "is_front": True, "image_url_main": "/static/images/muscles/main/muscle-10.svg", "image_url_secondary": "/static/images/muscles/secondary/muscle-10.svg" }, ] } # yapf: enable class MockEquipmentResponse: def __init__(self): self.status_code = 200 self.content = b'' # yapf: disable @staticmethod def json(): return { "count": 4, "next": None, "previous": None, "results": [ { "id": 1, "name": "Dumbbells" }, { "id": 2, "name": "Kettlebell" }, { "id": 3, "name": "A big rock" }, { "id": 42, "name": "Gym mat" }, ] } # yapf: enable class MockDeletionLogResponse: def __init__(self): self.status_code = 200 self.content = b'' # yapf: disable @staticmethod def json(): return { "count": 4, "next": None, "previous": None, "results": [ { "model_type": "base", "uuid": "acad3949-36fb-4481-9a72-be2ddae2bc05", "replaced_by": "ae3328ba-9a35-4731-bc23-5da50720c5aa", "timestamp": "2023-01-30T19:32:56.761426+01:00", "comment": "Exercise base with ID 1" }, { "model_type": "base", "uuid": "577ee012-70c6-4517-b0fe-dcf340926ae7", "replaced_by": None, "timestamp": "2023-01-30T19:32:56.761426+01:00", "comment": "Unknown Exercise base" }, { "model_type": "translation", "uuid": "0ef4cec8-d9c9-464f-baf9-3dbdf20083cb", "replaced_by": None, "timestamp": "2023-01-30T19:32:56.764582+01:00", "comment": "Translation that is not in this DB" }, { "model_type": "translation", "uuid": "946afe7b-54a6-44a6-9c36-c3e31e6b4c3b", "replaced_by": None, "timestamp": "2023-01-30T19:32:56.765350+01:00", "comment": "Translation with ID 3" }, { "model_type": "image", "uuid": "c72b4463-48ae-4c7d-8093-2c347c38e05a", "replaced_by": None, "timestamp": "2023-01-30T19:32:56.765350+01:00", "comment": "Unknown image" }, { "model_type": "video", "uuid": "e0d25624-348b-4a23-adcd-17190f96f005", "replaced_by": None, "timestamp": "2023-01-30T19:32:56.765350+01:00", "comment": "Unknown video" }, { "model_type": "foobar", "uuid": "37b5813c-76bd-4658-820a-572d9dd93f31", "replaced_by": None, "timestamp": "2023-01-30T19:32:56.765350+01:00", "comment": "UUID of existing translation but other model type" }, ] } # yapf: enable class MockExerciseResponse: def __init__(self): self.status_code = 200 self.content = b'' # yapf: disable @staticmethod def json(): return { "count": 1, "next": None, "previous": None, "results": [ { "id": 123, "uuid": "1b020b3a-3732-4c7e-92fd-a0cec90ed69b", "created": "2022-10-11T19:45:01.914000+01:00", "last_update": "2023-02-05T19:45:01.914000+01:00", "last_update_global": "2023-02-05T19:45:01.914000+01:00", "category": { "id": 2, "name": "Another category" }, "muscles": [ { "id": 2, "name": "Biceps testii", "name_en": "Testceps", "is_front": True, "image_url_main": "/static/images/muscles/main/muscle-2.svg", "image_url_secondary": "/static/images/muscles/secondary/muscle-2.svg" } ], "muscles_secondary": [ { "id": 4, "name": "Bigus Pectoralis", "name_en": "Testch", "is_front": True, "image_url_main": "/static/images/muscles/main/muscle-4.svg", "image_url_secondary": "/static/images/muscles/secondary/muscle-4.svg" } ], "equipment": [ { "id": 2, "name": "Kettlebell" } ], "license": { "id": 2, "full_name": "Creative Commons Attribution Share Alike 4", "short_name": "CC-BY-SA 4", "url": "https://creativecommons.org/licenses/by-sa/4.0/deed.en" }, "license_author": "Mr X", "images": [], "exercises": [ { "id": 100, "uuid": "c788d643-150a-4ac7-97ef-84643c6419bf", "name": "Zweihandiges Kettlebell", "exercise_base": 123, "description": "Hier könnte Ihre Werbung stehen!", "created": "2015-08-03", "language": 1, "aliases": [ { "id": 1, "uuid": "9a9ab323-5f47-431f-9289-cc21ad1de171", "alias": "Kettlebell mit zwei Händen" } ], "notes": [ { "id": 1, "uuid": "f46e1610-b729-4948-b80a-c5ae52672c6a", "exercise": 100, "comment": "Wichtig die Übung richtig zu machen" }, ], "license": 2, "license_author": "Tester von der Testen", "author_history": [ "wger Team", "Jürgen", "Tester von der Testen" ] }, { "id": 101, "uuid": "ab4185dd-2e68-4579-af1f-0c03957c0a9e", "name": "2 Handed Kettlebell Swing", "exercise_base": 123, "description": "TBD", "created": "2023-08-03", "language": 2, "aliases": [], "notes": [], "license": 2, "license_author": "Tester McTest", "author_history": [ "Mrs Winterbottom", "Tester McTest" ] } ], "variations": 47, "videos": [], "author_history": [ "Mrs Winterbottom" ], "total_authors_history": [ "Mrs Winterbottom", "Tester McTest", "wger Team", "Jürgen", "Tester von der Testen" ] }, { "id": 2, "uuid": "ae3328ba-9a35-4731-bc23-5da50720c5aa", "created": "2022-10-11T13:11:01.779000+01:00", "last_update": "2023-02-05T19:45:01.779000+01:00", "last_update_global": "2023-08-15T23:33:11.779000+01:00", "category": { "id": 3, "name": "Yet another category" }, "muscles": [ { "id": 2, "name": "Biceps testii", "name_en": "Testceps", "is_front": True, "image_url_main": "/static/images/muscles/main/muscle-2.svg", "image_url_secondary": "/static/images/muscles/secondary/muscle-2.svg" } ], "muscles_secondary": [ { "id": 4, "name": "Bigus Pectoralis", "name_en": "Testch", "is_front": True, "image_url_main": "/static/images/muscles/main/muscle-4.svg", "image_url_secondary": "/static/images/muscles/secondary/muscle-4.svg" } ], "equipment": [ { "id": 2, "name": "Kettlebell" } ], "license": { "id": 2, "full_name": "Creative Commons Attribution Share Alike 4", "short_name": "CC-BY-SA 4", "url": "https://creativecommons.org/licenses/by-sa/4.0/deed.en" }, "license_author": "Mr X", "images": [], "exercises": [ { "id": 123, "uuid": "7524ca8d-032e-482d-ab18-40e8a97851f6", "name": "A new, better, updated name", "exercise_base": 2, "description": "Two Handed Russian Style Kettlebell swing", "created": "2015-08-03", "language": 1, "aliases": [ { "id": 2, "uuid": "65250c7c-d02e-4f3d-be01-beb39ff5ef0f", "alias": "A new alias here" }, { "id": 500, "uuid": "6544ce61-69a8-413e-9662-189d3aadd1b9", "alias": "yet another name" }, ], "notes": [ { "id": 147, "uuid": "53906cd1-61f1-4d56-ac60-e4fcc5824861", "exercise": 123, "comment": "Foobar" }, ], "license": 2, "license_author": "Mr X", "author_history": [ "Mr X" ] }, { "id": 345, "uuid": "581338a1-8e52-405b-99eb-f0724c528bc8", "name": "Balançoire Kettlebell à 2 mains", "exercise_base": 2, "description": "Balançoire Kettlebell à deux mains de style russe", "created": "2015-08-03", "language": 3, "aliases": [], "notes": [], "license": 2, "license_author": "Mr Y", "author_history": [ "Mr Y", "Mr Z" ] } ], "variations": 47, "videos": [], "author_history": [ "Mr X" ], "total_authors_history": [ "Mr X", "Mr Z" ] }, ] } # yapf: enable class TestSyncMethods(WgerTestCase): @patch('requests.get', return_value=MockLanguageResponse()) def test_language_sync(self, mock_request): language1 = Language.objects.get(pk=1) self.assertEqual(Language.objects.count(), 3) self.assertEqual(language1.full_name, 'Deutsch') self.assertEqual(language1.full_name_en, 'German') # Act sync_languages(lambda x: x) mock_request.assert_called_with( 'https://wger.de/api/v2/language/', headers=wger_headers(), ) # Assert language1 = Language.objects.get(pk=1) self.assertEqual(language1.full_name, 'Daitsch') self.assertEqual(language1.full_name_en, 'Kraut') self.assertEqual(Language.objects.get(pk=5).full_name, 'Esperanto') self.assertEqual(Language.objects.count(), 5) @patch('requests.get', return_value=MockLicenseResponse()) def test_license_sync(self, mock_request): self.assertEqual(License.objects.count(), 3) self.assertEqual(License.objects.get(pk=1).url, '') sync_licenses(lambda x: x) mock_request.assert_called_with( 'https://wger.de/api/v2/license/', headers=wger_headers(), ) self.assertEqual( License.objects.get(pk=1).url, 'http://creativecommons.org/licenses/aca/fl/4.0/', ) self.assertEqual( License.objects.get(pk=6).full_name, 'Creative Commons Attribution Share Alike 4', ) self.assertEqual(License.objects.count(), 4) @patch('requests.get', return_value=MockCategoryResponse()) def test_categories_sync(self, mock_request): self.assertEqual(ExerciseCategory.objects.count(), 4) self.assertEqual(ExerciseCategory.objects.get(pk=1).name, 'Category') sync_categories(lambda x: x) mock_request.assert_called_with( 'https://wger.de/api/v2/exercisecategory/', headers=wger_headers(), ) self.assertEqual(ExerciseCategory.objects.count(), 6) self.assertEqual(ExerciseCategory.objects.get(pk=1).name, 'A cooler, swaggier category') self.assertEqual(ExerciseCategory.objects.get(pk=16).name, 'Chest') @patch('requests.get', return_value=MockMuscleResponse()) def test_muscle_sync(self, mock_request): self.assertEqual(Muscle.objects.count(), 6) self.assertEqual(Muscle.objects.get(pk=2).name, 'Biceps testii') self.assertFalse(Muscle.objects.get(pk=2).is_front) sync_muscles(lambda x: x) mock_request.assert_called_with( 'https://wger.de/api/v2/muscle/', headers=wger_headers(), ) self.assertEqual(Muscle.objects.count(), 7) self.assertTrue(Muscle.objects.get(pk=2).is_front) self.assertEqual(Muscle.objects.get(pk=2).name, 'Novum musculus nomen eius') self.assertEqual(Muscle.objects.get(pk=10).name, 'Pectoralis major') @patch('requests.get', return_value=MockEquipmentResponse()) def test_equipment_sync(self, mock_request): self.assertEqual(Equipment.objects.count(), 3) self.assertEqual(Equipment.objects.get(pk=3).name, 'Something else') sync_equipment(lambda x: x) mock_request.assert_called_with( 'https://wger.de/api/v2/equipment/', headers=wger_headers(), ) self.assertEqual(Equipment.objects.count(), 4) self.assertEqual(Equipment.objects.get(pk=3).name, 'A big rock') self.assertEqual(Equipment.objects.get(pk=42).name, 'Gym mat') @patch('requests.get', return_value=MockDeletionLogResponse()) def test_deletion_log(self, mock_request): self.assertEqual(ExerciseBase.objects.count(), 8) self.assertEqual(Exercise.objects.count(), 11) base = ExerciseBase.objects.get(pk=1) base2 = ExerciseBase.objects.get(pk=3) self.assertFalse(Setting.objects.filter(exercise_base=base2).count()) self.assertFalse(WorkoutLog.objects.filter(exercise_base=base2).count()) settings = Setting.objects.filter(exercise_base=base) logs = WorkoutLog.objects.filter(exercise_base=base) handle_deleted_entries(print) mock_request.assert_called_with( 'https://wger.de/api/v2/deletion-log/?limit=100', headers=wger_headers(), ) self.assertEqual(ExerciseBase.objects.count(), 7) self.assertEqual(Exercise.objects.count(), 8) self.assertRaises(Exercise.DoesNotExist, Exercise.objects.get, pk=3) self.assertRaises(ExerciseBase.DoesNotExist, ExerciseBase.objects.get, pk=1) # Workouts and logs have been moved for setting_pk in settings: self.assertEqual(Setting.objects.get(pk=setting_pk).exercise_base_id, 2) for setting_pk in logs: self.assertEqual(WorkoutLog.objects.get(pk=setting_pk).exercise_base_id, 2) @patch('requests.get', return_value=MockExerciseResponse()) def test_exercise_sync(self, mock_request): self.assertEqual(ExerciseBase.objects.count(), 8) self.assertEqual(Exercise.objects.count(), 11) base = ExerciseBase.objects.get(uuid='ae3328ba-9a35-4731-bc23-5da50720c5aa') self.assertEqual(base.category_id, 2) sync_exercises(lambda x: x) mock_request.assert_called_with( 'https://wger.de/api/v2/exercisebaseinfo/?limit=100', headers=wger_headers(), ) self.assertEqual(ExerciseBase.objects.count(), 9) self.assertEqual(Exercise.objects.count(), 14) # New base was created new_base = ExerciseBase.objects.get(uuid='1b020b3a-3732-4c7e-92fd-a0cec90ed69b') self.assertEqual(new_base.category_id, 2) self.assertEqual([e.id for e in new_base.equipment.all()], [2]) self.assertEqual([m.id for m in new_base.muscles.all()], [2]) self.assertEqual([m.id for m in new_base.muscles_secondary.all()], [4]) translation_de = new_base.get_translation('de') self.assertEqual(translation_de.language_id, 1) self.assertEqual(translation_de.name, 'Zweihandiges Kettlebell') self.assertEqual(translation_de.description, 'Hier könnte Ihre Werbung stehen!') self.assertEqual(translation_de.alias_set.first().alias, 'Kettlebell mit zwei Händen') self.assertEqual( translation_de.exercisecomment_set.first().comment, 'Wichtig die Übung richtig zu machen', ) translation_en = new_base.get_translation('en') self.assertEqual(translation_en.language_id, 2) self.assertEqual(translation_en.name, '2 Handed Kettlebell Swing') self.assertEqual(translation_en.description, 'TBD') # Existing base was updated base = ExerciseBase.objects.get(uuid='ae3328ba-9a35-4731-bc23-5da50720c5aa') self.assertEqual(base.category_id, 3) translation_de = base.get_translation('de') self.assertEqual(translation_de.name, 'A new, better, updated name') self.assertEqual(translation_de.pk, 2) self.assertEqual(translation_de.alias_set.count(), 2) self.assertEqual(translation_de.alias_set.all()[0].alias, 'A new alias here') self.assertEqual(translation_de.alias_set.all()[1].alias, 'yet another name') self.assertEqual(translation_de.exercisecomment_set.count(), 1) self.assertEqual(translation_de.exercisecomment_set.first().comment, 'Foobar') translation_fr = base.get_translation('fr') self.assertEqual(str(translation_fr.uuid), '581338a1-8e52-405b-99eb-f0724c528bc8')
27,880
Python
.py
680
23.916176
98
0.441165
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,740
read-exercise-cleanup.py
wger-project_wger/wger/exercises/management/commands/read-exercise-cleanup.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 csv import pathlib import re # Django from django.core.files import File from django.core.management.base import BaseCommand # wger from wger.core.models import ( Language, License, ) from wger.exercises.models import ( Alias, Equipment, Exercise, ExerciseBase, ExerciseCategory, ExerciseVideo, Variation, ) from wger.utils.constants import CC_BY_SA_4_ID UUID_NEW = 'NEW' VIDEO_AUTHOR = 'Goulart' VIDEO_PATH = pathlib.Path('videos-tmp') VIDEO_EXTENSIONS = ('.MP4', '.MOV') class Command(BaseCommand): """ ONE OFF SCRIPT! Note that running this script more than once will result in duplicate entries (specially the entries with 'NEW' as their UUID) This script reads back into the database corrections made to a CSV generated with exercise-cleanup.py """ help = 'Update the exercise database based on the exercise cleanup spreadsheet' def add_arguments(self, parser): parser.add_argument( '--process-videos', action='store_true', dest='process_videos', default=False, help='Flag indicating whether to process and add videos to the exercises', ) parser.add_argument( '--create-on-new', action='store_true', dest='create_on_new', default=True, help="Controls whether we create new bases or exercises if they have the UUID 'NEW'", ) def handle(self, **options): self.process_new_exercises(options) # self.delete_duplicates(options) def process_new_exercises(self, options): csv_file = open('exercises_cleanup.csv', 'r', newline='') file_reader = csv.DictReader(csv_file) # # Sanity check # languages = Language.objects.all() columns = ['uuid', 'name', 'description', 'aliases', 'license', 'author'] for language in [l.short_name for l in languages]: for column in columns: name = f'{language}:{column}' assert name in file_reader.fieldnames, f'{name} not in {file_reader.fieldnames}' default_license = License.objects.get(pk=CC_BY_SA_4_ID) # # Process the exercises # for row in file_reader: base_uuid = row['base:uuid'] base_equipment = row['base:equipment'] base_category = row['base:category'] base_variation_id = row['base:variation'] base_video = row['base:video'] if not base_uuid: # self.stdout.write('No base uuid, skipping') continue self.stdout.write(f'\n*** Processing base-UUID {base_uuid}\n') self.stdout.write('-------------------------------------------------------------\n') # # Load and update the base data # new_base = base_uuid == UUID_NEW if not options['create_on_new'] and new_base: self.stdout.write(f' Skipping creating new exercise base...\n') continue base = ( ExerciseBase.objects.get_or_create( uuid=base_uuid, defaults={'category': ExerciseCategory.objects.get(name=base_category)}, )[0] if not new_base else ExerciseBase() ) # Update the base data base.category = ExerciseCategory.objects.get(name=base_category) if new_base: base.save() base_equipment_list = [] if base_equipment: base_equipment_list = [ Equipment.objects.get(name=e.strip()) for e in base_equipment.split(',') ] base.equipment.set(base_equipment_list) # Variations if base_variation_id: variation, created = Variation.objects.get_or_create(id=base_variation_id) base.variations = variation base.save() # Save the video # Note we can't really know if the video is new or not since the name is # a generated UUID. We could read the content and compare the size, etc. # but that is too much work for this script that will be used only once. if base_video and options['process_videos']: for video_name in base_video.split('/'): video_processed = False for extension in VIDEO_EXTENSIONS: path = VIDEO_PATH / pathlib.Path(video_name.strip() + extension) if video_processed or not path.exists(): continue with path.open('rb') as video_file: video = ExerciseVideo() video.exercise_base = base video.license = default_license video.license_author = VIDEO_AUTHOR video.video.save( path.name, File(video_file), ) video.save() self.stdout.write(f'Saving video {path}\n') video_processed = True # # Process the translations and create new exercises if necessary # for language in languages: language_short = language.short_name exercise_uuid = row[f'{language_short}:uuid'] exercise_name = row[f'{language_short}:name'] exercise_description = row[f'{language_short}:description'] exercise_license = row[f'{language_short}:license'] exercise_author = row[f'{language_short}:author'] exercise_aliases = row[f'{language_short}:aliases'] # Load translation if exercise_uuid: message = f'{language_short}: translation uuid: {exercise_uuid}\n' self.stdout.write(message) else: # self.stdout.write(f'{language_short}: No UUID for translation, skipping...\n') continue if not exercise_name: continue new_translation = exercise_uuid == UUID_NEW if not new_translation: continue translation = ( Exercise.objects.get_or_create( uuid=exercise_uuid, defaults={'exercise_base': base, 'language': language} )[0] if not new_translation else Exercise() ) translation.exercise_base = base translation.language = language translation.name = exercise_name translation.name_original = exercise_name translation.description = exercise_description # Set the license if exercise_license: try: exercise_license = License.objects.get(short_name=exercise_license) except License.DoesNotExist: self.stdout.write( self.style.WARNING( f' License does not exist: {exercise_license}!!!\n' ) ) exercise_license = default_license else: exercise_license = default_license translation.license = exercise_license translation.license_author = exercise_author if not translation.id: message = f' New translation saved - {exercise_name} ({translation.uuid})' self.stdout.write(self.style.SUCCESS(message)) if '(imported from Feeel)' in exercise_author: exercise_author = re.sub('\(imported from Feeel\)', '', exercise_author) for author in exercise_author.split(','): author = author.strip() author = f'{author} (imported from Feeel)' self.stdout.write(f' - Saving individual author {author}') if len(author) >= 60: self.stdout.write( self.style.WARNING( f' Author name is longer than 60 characters, skipping...' ) ) continue translation.license_author = author translation.save() # Set the aliases (replaces existing ones) if exercise_aliases: Alias.objects.filter(exercise=translation).delete() for a in exercise_aliases.split(','): Alias(exercise=translation, alias=a.strip()).save() csv_file.close() def delete_duplicates(self, options): csv_file = open('exercises_cleanup_duplicates.csv', 'r', newline='') file_reader = csv.DictReader(csv_file) self.stdout.write( self.style.WARNING(f'---> Deleting duplicate bases and translations now...') ) for row in file_reader: base_uuid = row['baseUUID:toDelete'] translation_uuid = row['exerciseUUID:toDelete'] variation_id = row['variations:toDelete'] if base_uuid: try: ExerciseBase.objects.filter(uuid=base_uuid).delete() self.stdout.write(f'* Deleted base {base_uuid}') except ExerciseBase.DoesNotExist: pass if translation_uuid: try: Exercise.objects.filter(uuid=translation_uuid).delete() self.stdout.write(f'* Deleted translation {translation_uuid}') except Exercise.DoesNotExist: pass if variation_id: try: Variation.objects.filter(id=variation_id).delete() self.stdout.write(f'* Deleted variation {variation_id}') except Exercise.DoesNotExist: pass csv_file.close()
11,248
Python
.py
249
30.51004
100
0.538026
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,741
sync-exercises.py
wger-project_wger/wger/exercises/management/commands/sync-exercises.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.exercises.sync import ( handle_deleted_entries, sync_categories, sync_equipment, sync_exercises, sync_languages, sync_licenses, sync_muscles, ) class Command(BaseCommand): """ Synchronizes exercise data from a wger instance to the local database """ remote_url = settings.WGER_SETTINGS['WGER_INSTANCE'] help = """Synchronizes exercise data from a wger instance to the local database. This script also deletes entries that were removed on the server such as exercises, images or videos. Please note that at the moment the following objects can only identified by their id. If you added new objects they might have the same IDs as the remote ones and will be overwritten: - categories - muscles - equipment """ 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 exercises from (default: WGER_SETTINGS' f'["WGER_INSTANCE"] - {settings.WGER_SETTINGS["WGER_INSTANCE"]})', ) parser.add_argument( '--dont-delete', action='store_true', dest='skip_delete', default=False, help='Skips deleting any entries', ) 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') # Process everything sync_languages(self.stdout.write, self.remote_url, self.style.SUCCESS) sync_categories(self.stdout.write, self.remote_url, self.style.SUCCESS) sync_muscles(self.stdout.write, self.remote_url, self.style.SUCCESS) sync_equipment(self.stdout.write, self.remote_url, self.style.SUCCESS) sync_licenses(self.stdout.write, self.remote_url, self.style.SUCCESS) sync_exercises(self.stdout.write, self.remote_url, self.style.SUCCESS) if not options['skip_delete']: handle_deleted_entries(self.stdout.write, self.remote_url, self.style.SUCCESS)
3,259
Python
.py
79
33.974684
90
0.679609
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,742
download-exercise-images.py
wger-project_wger/wger/exercises/management/commands/download-exercise-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.exercises.sync import download_exercise_images class Command(BaseCommand): """ Download exercise images from wger.de and updates the local database Both the exercises and the images are identified by their UUID, which can't be modified via the GUI. """ help = ( 'Download exercise 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 exercises. The exercises 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 images 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_exercise_images(self.stdout.write, remote_url, self.style.SUCCESS)
2,446
Python
.py
59
35.610169
87
0.694573
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,743
exercise-cleanup.py
wger-project_wger/wger/exercises/management/commands/exercise-cleanup.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 csv # Django from django.core.management.base import BaseCommand # wger from wger.core.models import Language from wger.exercises.models import ( Exercise, ExerciseBase, ) class Command(BaseCommand): """ ONE OFF SCRIPT! This script reads out the exercise database and writes it to a CSV file, so that mass corrections can be done. The file can be read in with read-exercises-cleanup.py """ def handle(self, **options): out = [] languages = Language.objects.all() for base in ExerciseBase.objects.all(): data = { 'base': { 'uuid': base.uuid, 'category': base.category.name, 'equipment': ','.join([e.name for e in base.equipment.all()]), 'variations': base.variations.id if base.variations else '', } } for language in languages: exercise_data = { 'uuid': '', 'name': '', 'description': '', 'aliases': '', 'license': '', 'author': '', } exercise = Exercise.objects.filter(exercise_base=base, language=language).first() if exercise: exercise_data['uuid'] = exercise.uuid exercise_data['name'] = exercise.name exercise_data['description'] = exercise.description exercise_data['license'] = exercise.license.short_name exercise_data['author'] = exercise.license_author exercise_data['aliases'] = ','.join([a.alias for a in exercise.alias_set.all()]) data[language.short_name] = exercise_data out.append(data) with open('exercise_cleanup.csv', 'w', newline='') as csvfile: file_writer = csv.writer( csvfile, ) header = ['base:uuid', 'base:category', 'base:equipment', 'base:variations'] for language in languages: header += [ f'{language.short_name}:uuid', f'{language.short_name}:name', f'{language.short_name}:alias', f'{language.short_name}:description', f'{language.short_name}:license', f'{language.short_name}:author', ] file_writer.writerow(header) for entry in out: data = [ entry['base']['uuid'], entry['base']['category'], entry['base']['equipment'], entry['base']['variations'], ] for language in languages: data += [ entry[language.short_name]['uuid'], entry[language.short_name]['name'], entry[language.short_name]['aliases'], entry[language.short_name]['description'], entry[language.short_name]['license'], entry[language.short_name]['author'], ] file_writer.writerow(data)
3,979
Python
.py
93
29.612903
100
0.539018
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,744
submitted-exercises.py
wger-project_wger/wger/exercises/management/commands/submitted-exercises.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.base import BaseCommand # wger from wger.exercises.models import Exercise class Command(BaseCommand): """ Read out the user submitted exercise. Used to generate the AUTHORS file for a release """ help = 'Read out the user submitted exercise' def handle(self, **options): exercises = Exercise.objects.all() usernames = [] for exercise in exercises: if exercise.user not in usernames: usernames.append(exercise.user) self.stdout.write(exercise.user)
1,223
Python
.py
30
36.466667
78
0.73946
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,745
warmup-exercise-api-cache.py
wger-project_wger/wger/exercises/management/commands/warmup-exercise-api-cache.py
# This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # Django from django.core.management.base import BaseCommand # wger from wger.exercises.api.serializers import ExerciseBaseInfoSerializer from wger.exercises.models import ExerciseBase from wger.utils.cache import reset_exercise_api_cache class Command(BaseCommand): """ Calls the exercise api to get all exercises and caches them in the database. """ def add_arguments(self, parser): parser.add_argument( '--exercise-base-id', action='store', dest='exercise_base_id', help='The ID of the exercise base, otherwise all exercises will be updated', ) parser.add_argument( '--force', action='store_true', dest='force', default=False, help='Force the update of the cache', ) def handle(self, **options): exercise_base_id = options['exercise_base_id'] force = options['force'] if exercise_base_id: exercise = ExerciseBase.objects.get(pk=exercise_base_id) self.handle_cache(exercise, force) return for exercise in ExerciseBase.translations.all(): self.handle_cache(exercise, force) def handle_cache(self, exercise: ExerciseBase, force: bool): if force: self.stdout.write(f'Force updating cache for exercise base {exercise.uuid}') else: self.stdout.write(f'Warming cache for exercise base {exercise.uuid}') if force: reset_exercise_api_cache(exercise.uuid) serializer = ExerciseBaseInfoSerializer(exercise) serializer.data
2,286
Python
.py
55
34.527273
88
0.687247
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,746
change-exercise-author.py
wger-project_wger/wger/exercises/management/commands/change-exercise-author.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.base import BaseCommand # wger from wger.exercises.models import ExerciseBase from wger.exercises.models.exercise import Exercise class Command(BaseCommand): """ Alter the author name in the exercise models. """ help = ( 'Used to alter exercise license authors\n' 'Must provide at least the exercise base id using --exercise-base-id\n' 'or the exercise id using --exercise-id.\n' 'Must also provide the new author name using --author-name\n' ) def add_arguments(self, parser): parser.add_argument( '--author-name', action='store', dest='author_name', help='The name of the new author' ) parser.add_argument( '--exercise-base-id', action='store', dest='exercise_base_id', help='The ID of the exercise base', ) parser.add_argument( '--exercise-id', action='store', dest='exercise_id', help='The ID of the exercise' ) def handle(self, **options): author_name = options['author_name'] exercise_base_id = options['exercise_base_id'] exercise_id = options['exercise_id'] if author_name is None: self.print_error('Please enter an author name') return if exercise_base_id is None and exercise_id is None: self.print_error('Please enter an exercise base or exercise ID') return if exercise_base_id is not None: try: exercise_base = ExerciseBase.objects.get(id=exercise_base_id) except ExerciseBase.DoesNotExist: self.print_error('Failed to find exercise base') return exercise_base.license_author = author_name exercise_base.save() if exercise_id is not None: try: exercise = Exercise.objects.get(id=exercise_id) except ExerciseBase.DoesNotExist: self.print_error('Failed to find exercise') return exercise.license_author = author_name exercise.save() self.stdout.write(self.style.SUCCESS(f'Exercise and/or exercise base has been updated')) def print_error(self, error_message): self.stdout.write(self.style.WARNING(f'{error_message}'))
3,013
Python
.py
70
34.771429
98
0.655631
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,747
delete-unused-exercises.py
wger-project_wger/wger/exercises/management/commands/delete-unused-exercises.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 collections # Django from django.core.management.base import BaseCommand # wger from wger.core.models import Language from wger.exercises.models import ExerciseBase from wger.manager.models import ( Setting, WorkoutLog, ) from wger.utils.constants import ENGLISH_SHORT_NAME class Command(BaseCommand): """ Deletes all unused exercises """ help = """Deletes all unused exercises from the database. After running this script, sync the database with ´python manage.py sync-exercises` """ def handle(self, **options): # Collect all exercise bases that are not used in any workout or log entry out = f'{ExerciseBase.objects.all().count()} exercises currently in the database' self.stdout.write(out) bases = set(Setting.objects.all().values_list('exercise_base', flat=True)) bases_logs = set(WorkoutLog.objects.all().values_list('exercise_base', flat=True)) bases.update(bases_logs) # Ask for confirmation out = f'{len(bases)} exercises are in use, delete the rest?' self.stdout.write(out) response = '' while response not in ('y', 'n'): response = input('Type y to delete or n to exit: ') if response == 'y': ExerciseBase.objects.exclude(pk__in=bases).delete() out = self.style.SUCCESS('Done! You can now run python manage.py sync-exercises') self.stdout.write(out) else: out = self.style.SUCCESS('Exiting without deleting anything') self.stdout.write(out)
2,256
Python
.py
52
37.807692
93
0.704649
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,748
exercises-health-check.py
wger-project_wger/wger/exercises/management/commands/exercises-health-check.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 collections from argparse import RawTextHelpFormatter # Django from django.core.management.base import BaseCommand # wger from wger.core.models import Language from wger.exercises.models import ExerciseBase from wger.utils.constants import ENGLISH_SHORT_NAME class Command(BaseCommand): """ Performs some sanity checks on the exercise database """ english: Language help = ( 'Performs some sanity checks on the exercise database. ' 'At the moment this script checks that each exercise:\n' '- has at least one translation\n' '- has a translation in English\n' '- has no duplicate translations\n\n' 'Each problem can be fixed individually by using the --delete-* flags\n' ) def create_parser(self, *args, **kwargs): parser = super(Command, self).create_parser(*args, **kwargs) parser.formatter_class = RawTextHelpFormatter return parser def add_arguments(self, parser): parser.add_argument( '--delete-untranslated', action='store_true', dest='delete_untranslated', default=False, help="Delete exercises without translations (safe to use since these can't be " 'accessed over the UI)', ) parser.add_argument( '--delete-duplicate-translations', action='store_true', dest='delete_duplicates', default=False, help='Delete duplicate translations (e.g. if an exercise has two French entries, ' 'the first one will be removed)', ) parser.add_argument( '--delete-no-english', action='store_true', dest='delete_no_english', default=False, help='Delete exercises without a fallback English translations', ) parser.add_argument( '--delete-all', action='store_true', dest='delete_all', default=False, help='Sets all deletion flags to true', ) def handle(self, **options): delete_untranslated = options['delete_untranslated'] or options['delete_all'] delete_duplicates = options['delete_duplicates'] or options['delete_all'] delete_no_english = options['delete_no_english'] or options['delete_all'] self.english = Language.objects.get(short_name=ENGLISH_SHORT_NAME) for base in ExerciseBase.objects.all(): self.handle_untranslated(base, delete_untranslated) self.handle_no_english(base, delete_no_english) self.handle_duplicate_translations(base, delete_duplicates) def handle_untranslated(self, base: ExerciseBase, delete: bool): """ Delete exercises without translations """ if not base.pk or base.exercises.count(): return self.stdout.write(self.style.WARNING(f'Exercise {base.uuid} has no translations!')) if delete: base.delete() self.stdout.write(' -> deleted') def handle_no_english(self, base: ExerciseBase, delete: bool): if not base.pk or base.exercises.filter(language=self.english).exists(): return self.stdout.write(self.style.WARNING(f'Exercise {base.uuid} has no English translation!')) if delete: base.delete() self.stdout.write(' -> deleted') def handle_duplicate_translations(self, base: ExerciseBase, delete: bool): if not base.pk: return exercise_languages = base.exercises.values_list('language', flat=True) duplicates = [ Language.objects.get(pk=item) for item, count in collections.Counter(exercise_languages).items() if count > 1 ] if not duplicates: return warning = f'Exercise {base.uuid} has duplicate translations!' self.stdout.write(self.style.WARNING(warning)) # Output the duplicates for language in duplicates: translations = base.exercises.filter(language=language) self.stdout.write(f'language {language.short_name}:') for translation in translations: self.stdout.write(f' * {translation.name} {translation.uuid}') self.stdout.write('') # And delete them if delete: self.stdout.write(f' Deleting all but first {language.short_name} translation') for translation in translations[1:]: translation.delete()
5,257
Python
.py
121
34.471074
98
0.648405
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,749
download-exercise-videos.py
wger-project_wger/wger/exercises/management/commands/download-exercise-videos.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.exercises.sync import download_exercise_videos class Command(BaseCommand): """ Download exercise videos from wger.de and updates the local database Both the exercises and the videos are identified by their UUID, which can't be modified via the GUI. """ help = 'Download exercise videos from wger.de and update the local database' def add_arguments(self, parser): parser.add_argument( '--remote-url', action='store', dest='remote_url', default='https://wger.de', help='Remote URL to fetch the exercises from (default: ' 'https://wger.de)', ) 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_exercise_videos(self.stdout.write, remote_url)
1,993
Python
.py
51
33.72549
88
0.713768
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,750
signals.py
wger-project_wger/wger/core/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 datetime # Django from django.contrib.auth.models import User from django.db.models.signals import ( post_save, pre_save, ) from django.dispatch import receiver # wger from wger.core.models import ( UserCache, UserProfile, ) from wger.utils.helpers import disable_for_loaddata @disable_for_loaddata def create_user_profile(sender, instance, created, **kwargs): """ Every new user gets a profile """ if created: UserProfile.objects.create(user=instance) @disable_for_loaddata def create_user_cache(sender, instance, created, **kwargs): """ Every new user gets a cache table """ if created: UserCache.objects.create(user=instance) @receiver(pre_save, sender=UserProfile) def set_user_age(sender, instance, **kwargs): """ Inputting or changing a user's birthdate will auto-update the user's age as well if user's age has not been set """ if instance.age is None and instance.birthdate is not None: today = datetime.date.today() birthday = instance.birthdate instance.age = ( today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day)) ) post_save.connect(create_user_profile, sender=User) post_save.connect(create_user_cache, sender=User)
1,994
Python
.py
57
31.526316
100
0.737662
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,751
demo.py
wger-project_wger/wger/core/demo.py
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # Standard Library import datetime import logging import random import uuid # Django from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.http import HttpRequest from django.utils.translation import gettext as _ # wger from wger.core.models import DaysOfWeek from wger.exercises.models import ( Exercise, ExerciseBase, ) from wger.manager.models import ( Day, Schedule, ScheduleStep, Set, Setting, Workout, WorkoutLog, ) from wger.nutrition.models import ( Ingredient, IngredientWeightUnit, Meal, MealItem, NutritionPlan, ) from wger.utils.language import load_language from wger.weight.models import WeightEntry logger = logging.getLogger(__name__) UUID_SQUATS = 'a2f5b6ef-b780-49c0-8d96-fdaff23e27ce' UUID_CURLS = '1ae6a28d-10e7-4ecf-af4f-905f8193e2c6' UUID_FRENCH_PRESS = '95a7e546-e8f8-4521-a76b-983d94161b25' UUID_CRUNCHES = 'b186f1f8-4957-44dc-bf30-d0b00064ce6f' UUID_LEG_RAISES = 'c2078aac-e4e2-4103-a845-6252a3eb795e' def create_temporary_user(request: HttpRequest): """ Creates a temporary user """ username = uuid.uuid4().hex[:-2] password = uuid.uuid4().hex[:-2] email = '' user = User.objects.create_user(username, email, password) user.save() user_profile = user.userprofile user_profile.is_temporary = True user_profile.age = 25 user_profile.height = 175 user_profile.save() user = authenticate(request=request, username=username, password=password) return user def create_demo_entries(user): """ Creates some demo data for temporary users """ # (this is a bit ugly and long...) language = load_language() # # Workout and exercises # setting_list = [] weight_log = [] workout = Workout(user=user, name=_('Sample workout')) workout.save() monday = DaysOfWeek.objects.get(pk=1) wednesday = DaysOfWeek.objects.get(pk=3) day = Day(training=workout, description=_('Sample day')) day.save() day.day.add(monday) day2 = Day(training=workout, description=_('Another sample day')) day2.save() day2.day.add(wednesday) # Biceps curls with dumbbell exercise = ExerciseBase.objects.get(uuid=UUID_CURLS) day_set = Set(exerciseday=day, sets=4, order=2) day_set.save() setting = Setting(set=day_set, exercise_base=exercise, reps=8, order=1) setting.save() # Weight log entries for reps in (8, 10, 12): for i in range(1, 8): log = WorkoutLog( user=user, exercise_base=exercise, workout=workout, reps=reps, weight=18 - reps + random.randint(1, 4), date=datetime.date.today() - datetime.timedelta(weeks=i), ) weight_log.append(log) # French press exercise = ExerciseBase.objects.get(uuid=UUID_FRENCH_PRESS) day_set = Set(exerciseday=day, sets=4, order=2) day_set.save() setting_list.append(Setting(set=day_set, exercise_base=exercise, reps=8, order=1)) # Weight log entries for reps in (7, 10): for i in range(1, 8): log = WorkoutLog( user=user, exercise_base=exercise, workout=workout, reps=reps, weight=30 - reps + random.randint(1, 4), date=datetime.date.today() - datetime.timedelta(weeks=i), ) weight_log.append(log) # Squats exercise = ExerciseBase.objects.get(uuid=UUID_SQUATS) day_set = Set(exerciseday=day, sets=4, order=3) day_set.save() setting_list.append(Setting(set=day_set, exercise_base=exercise, reps=10, order=1)) # Weight log entries for reps in (5, 10, 12): for i in range(1, 8): log = WorkoutLog( user=user, exercise_base=exercise, workout=workout, reps=reps, weight=110 - reps + random.randint(1, 10), date=datetime.date.today() - datetime.timedelta(weeks=i), ) weight_log.append(log) # Crunches exercise = ExerciseBase.objects.get(uuid=UUID_CRUNCHES) day_set = Set(exerciseday=day, sets=4, order=4) day_set.save() setting_list.append(Setting(set=day_set, exercise_base=exercise, reps=30, order=1)) setting_list.append(Setting(set=day_set, exercise_base=exercise, reps=99, order=2)) setting_list.append(Setting(set=day_set, exercise_base=exercise, reps=35, order=3)) # Leg raises, supersets with crunches exercise = ExerciseBase.objects.get(uuid=UUID_LEG_RAISES) setting_list.append(Setting(set=day_set, exercise_base=exercise, reps=30, order=1)) setting_list.append(Setting(set=day_set, exercise_base=exercise, reps=40, order=2)) setting_list.append(Setting(set=day_set, exercise_base=exercise, reps=99, order=3)) Setting.objects.bulk_create(setting_list) # Save all the log entries WorkoutLog.objects.bulk_create(weight_log) # # (Body) weight entries # temp = [] existing_entries = [i.date for i in WeightEntry.objects.filter(user=user)] for i in range(1, 20): creation_date = datetime.date.today() - datetime.timedelta(days=i) if creation_date not in existing_entries: entry = WeightEntry( user=user, weight=80 + 0.5 * i + random.randint(1, 3), date=creation_date, ) temp.append(entry) WeightEntry.objects.bulk_create(temp) # # Nutritional plan # plan = NutritionPlan() plan.user = user plan.language = language plan.description = _('Sample nutritional plan') plan.save() # Breakfast meal = Meal() meal.plan = plan meal.order = 1 meal.time = datetime.time(7, 30) meal.save() # Oatmeal if language.short_name == 'de': ingredient = Ingredient.objects.get(pk=8197) else: ingredient = Ingredient.objects.get(pk=2126) mealitem = MealItem() mealitem.meal = meal mealitem.ingredient = ingredient mealitem.order = 1 mealitem.amount = 100 mealitem.save() # Milk if language.short_name == 'de': ingredient = Ingredient.objects.get(pk=8198) else: ingredient = Ingredient.objects.get(pk=154) mealitem = MealItem() mealitem.meal = meal mealitem.ingredient = ingredient mealitem.order = 2 mealitem.amount = 100 mealitem.save() # Protein powder if language.short_name == 'de': ingredient = Ingredient.objects.get(pk=8244) else: ingredient = Ingredient.objects.get(pk=196) mealitem = MealItem() mealitem.meal = meal mealitem.ingredient = ingredient mealitem.order = 3 mealitem.amount = 30 mealitem.save() # # 11 o'clock meal meal = Meal() meal.plan = plan meal.order = 2 meal.time = datetime.time(11, 0) meal.save() # Bread, in slices if language.short_name == 'de': ingredient = Ingredient.objects.get(pk=8225) unit = None amount = 80 else: ingredient = Ingredient.objects.get(pk=5370) unit = IngredientWeightUnit.objects.get(pk=9874) amount = 2 mealitem = MealItem() mealitem.meal = meal mealitem.ingredient = ingredient mealitem.weight_unit = unit mealitem.order = 1 mealitem.amount = amount mealitem.save() # Turkey if language.short_name == 'de': ingredient = Ingredient.objects.get(pk=8201) else: ingredient = Ingredient.objects.get(pk=1643) mealitem = MealItem() mealitem.meal = meal mealitem.order = 2 mealitem.ingredient = ingredient mealitem.amount = 100 mealitem.save() # Cottage cheese if language.short_name == 'de': ingredient = Ingredient.objects.get(pk=8222) # TODO: check this! else: ingredient = Ingredient.objects.get(pk=17) mealitem = MealItem() mealitem.meal = meal mealitem.ingredient = ingredient mealitem.order = 3 mealitem.amount = 50 mealitem.save() # Tomato, one if language.short_name == 'de': ingredient = Ingredient.objects.get(pk=8217) unit = None amount = 120 else: ingredient = Ingredient.objects.get(pk=3208) unit = IngredientWeightUnit.objects.get(pk=5950) amount = 1 mealitem = MealItem() mealitem.meal = meal mealitem.weight_unit = unit mealitem.ingredient = ingredient mealitem.order = 4 mealitem.amount = amount mealitem.save() # # Lunch (leave empty so users can add their own ingredients) meal = Meal() meal.plan = plan meal.order = 3 meal.time = datetime.time(13, 0) meal.save() # # Workout schedules # # create some empty workouts to fill the list workout2 = Workout(user=user, name=_('Placeholder workout nr {0} for schedule').format(1)) workout2.save() workout3 = Workout(user=user, name=_('Placeholder workout nr {0} for schedule').format(2)) workout3.save() workout4 = Workout(user=user, name=_('Placeholder workout nr {0} for schedule').format(3)) workout4.save() schedule = Schedule() schedule.user = user schedule.name = _('My cool workout schedule') schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=4) schedule.is_active = True schedule.is_loop = True schedule.save() # Add the workouts step = ScheduleStep() step.schedule = schedule step.workout = workout2 step.duration = 2 step.order = 1 step.save() step = ScheduleStep() step.schedule = schedule step.workout = workout step.duration = 4 step.order = 2 step.save() step = ScheduleStep() step.schedule = schedule step.workout = workout3 step.duration = 1 step.order = 3 step.save() step = ScheduleStep() step.schedule = schedule step.workout = workout4 step.duration = 6 step.order = 4 step.save() # # Add two more schedules, to make the overview more interesting schedule = Schedule() schedule.user = user schedule.name = _('Empty placeholder schedule') schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=15) schedule.is_active = False schedule.is_loop = False schedule.save() step = ScheduleStep() step.schedule = schedule step.workout = workout2 step.duration = 2 step.order = 1 step.save() schedule = Schedule() schedule.user = user schedule.name = _('Empty placeholder schedule') schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=30) schedule.is_active = False schedule.is_loop = False schedule.save() step = ScheduleStep() step.schedule = schedule step.workout = workout4 step.duration = 2 step.order = 1 step.save()
11,684
Python
.py
358
26.664804
94
0.661903
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,752
checks.py
wger-project_wger/wger/core/checks.py
# Django from django.conf import settings from django.core.checks import ( Error, Warning, register, ) # wger from wger.utils.constants import DOWNLOAD_INGREDIENT_OPTIONS @register() def settings_check(app_configs, **kwargs): errors = [] # Upstream wger instance should be configured if not settings.WGER_SETTINGS.get('WGER_INSTANCE'): errors.append( Warning( 'wger instance not set', hint='No wger instance configured, sync commands will not work', obj=settings, id='wger.W001', ) ) # Only one setting should be set if settings.WGER_SETTINGS['DOWNLOAD_INGREDIENTS_FROM'] not in DOWNLOAD_INGREDIENT_OPTIONS: errors.append( Error( 'Ingredient images configuration error', hint=f'Origin for ingredient images misconfigured. Valid options are ' f'{DOWNLOAD_INGREDIENT_OPTIONS}', obj=settings, id='wger.E001', ) ) return errors
1,089
Python
.py
34
23.235294
94
0.607619
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,753
urls.py
wger-project_wger/wger/core/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.contrib.auth import views from django.urls import ( path, re_path, ) from django.views.generic import TemplateView # wger from wger.core.forms import UserLoginForm from wger.core.views import ( languages, license, misc, repetition_units, user, weight_units, ) # sub patterns for languages patterns_language = [ path( 'list', languages.LanguageListView.as_view(), name='overview', ), path( '<int:pk>/view', languages.LanguageDetailView.as_view(), name='view', ), path( '<int:pk>/delete', languages.LanguageDeleteView.as_view(), name='delete', ), path( '<int:pk>/edit', languages.LanguageEditView.as_view(), name='edit', ), path( 'add', languages.LanguageCreateView.as_view(), name='add', ), ] # sub patterns for user patterns_user = [ path( 'login', views.LoginView.as_view(template_name='user/login.html', authentication_form=UserLoginForm), name='login', ), path('logout', user.logout, name='logout'), path('delete', user.delete, name='delete'), path('<int:user_pk>/delete', user.delete, name='delete'), path('confirm-email', user.confirm_email, name='confirm-email'), path('<int:user_pk>/trainer-login', user.trainer_login, name='trainer-login'), path('registration', user.registration, name='registration'), path('preferences', user.preferences, name='preferences'), path('api-key', user.api_key, name='api-key'), path('demo-entries', misc.demo_entries, name='demo-entries'), path('<int:pk>/activate', user.UserActivateView.as_view(), name='activate'), path('<int:pk>/deactivate', user.UserDeactivateView.as_view(), name='deactivate'), path('<int:pk>/edit', user.UserEditView.as_view(), name='edit'), path('<int:pk>/overview', user.UserDetailView.as_view(), name='overview'), path('list', user.UserListView.as_view(), name='list'), # Password reset is implemented by Django, no need to cook our own soup here # (besides the templates) path( 'password/change', user.WgerPasswordChangeView.as_view(), name='change-password', ), path( 'password/reset/', user.WgerPasswordResetView.as_view(), name='password_reset', ), path( 'password/reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done', ), re_path( r'^password/reset/check/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$', user.WgerPasswordResetConfirmView.as_view(), name='password_reset_confirm', ), path( 'password/reset/complete/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete', ), ] # sub patterns for licenses patterns_license = [ path( 'license/list', license.LicenseListView.as_view(), name='list', ), path( 'license/add', license.LicenseAddView.as_view(), name='add', ), path( 'license/<int:pk>/edit', license.LicenseUpdateView.as_view(), name='edit', ), path( 'license/<int:pk>/delete', license.LicenseDeleteView.as_view(), name='delete', ), ] # sub patterns for setting units patterns_repetition_units = [ path( 'list', repetition_units.ListView.as_view(), name='list', ), path( 'add', repetition_units.AddView.as_view(), name='add', ), path( '<int:pk>/edit', repetition_units.UpdateView.as_view(), name='edit', ), path( '<int:pk>/delete', repetition_units.DeleteView.as_view(), name='delete', ), ] # sub patterns for setting units patterns_weight_units = [ path( 'list', weight_units.ListView.as_view(), name='list', ), path( 'add', weight_units.AddView.as_view(), name='add', ), path( '<int:pk>)/edit', weight_units.UpdateView.as_view(), name='edit', ), path( '<int:pk>/delete', weight_units.DeleteView.as_view(), name='delete', ), ] # # Actual patterns # urlpatterns = [ # The landing page path('', misc.index, name='index'), # The dashboard path('dashboard', misc.dashboard, name='dashboard'), # Others path( 'imprint', TemplateView.as_view(template_name='misc/about.html'), name='imprint', ), path( 'feedback', misc.FeedbackClass.as_view(), name='feedback', ), path('language/', include((patterns_language, 'language'), namespace='language')), path('user/', include((patterns_user, 'user'), namespace='user')), path('license/', include((patterns_license, 'license'), namespace='license')), path( 'repetition-unit/', include((patterns_repetition_units, 'repetition-unit'), namespace='repetition-unit'), ), path('weight-unit/', include((patterns_weight_units, 'weight-unit'), namespace='weight-unit')), ]
5,940
Python
.py
206
23.145631
109
0.62369
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,754
apps.py
wger-project_wger/wger/core/apps.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.apps import AppConfig class CoreConfig(AppConfig): name = 'wger.core' verbose_name = 'Core' def ready(self): import wger.core.signals import wger.core.checks
850
Python
.py
21
37.952381
78
0.770909
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,755
__init__.py
wger-project_wger/wger/core/__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.core.apps.CoreConfig'
851
Python
.py
19
43.578947
78
0.775362
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,756
forms.py
wger-project_wger/wger/core/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 # Standard Library from datetime import date # Django from django import forms from django.contrib.auth import authenticate from django.contrib.auth.forms import ( AuthenticationForm, UserCreationForm, ) from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ( CharField, EmailField, Form, PasswordInput, widgets, ) from django.utils.translation import gettext as _ # Third Party from crispy_forms.helper import FormHelper from crispy_forms.layout import ( HTML, ButtonHolder, Column, Fieldset, Layout, Row, Submit, ) from django_recaptcha.fields import ReCaptchaField from django_recaptcha.widgets import ReCaptchaV3 # wger from wger.core.models import UserProfile class UserLoginForm(AuthenticationForm): """ Form for logins """ authenticate_on_clean = True def __init__(self, authenticate_on_clean=True, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) self.authenticate_on_clean = authenticate_on_clean self.helper = FormHelper() self.helper.add_input(Submit('submit', _('Login'), css_class='btn-success btn-block')) self.helper.form_class = 'wger-form' self.helper.layout = Layout( Row( Column('username', css_class='col-6'), Column('password', css_class='col-6'), css_class='form-row', ) ) def clean(self): """ Note: this clean method needs to be able to toggle authenticating directly or not. This is needed because django axes expects an explicit request parameter and otherwise the login endpoint won't work See https://github.com/wger-project/wger/issues/1163 """ if self.authenticate_on_clean: self.authenticate(self.request) return self.cleaned_data def authenticate(self, request): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: self.user_cache = authenticate( request=request, username=username, password=password, ) if self.user_cache is None: raise self.get_invalid_login_error() else: self.confirm_login_allowed(self.user_cache) class UserPreferencesForm(forms.ModelForm): first_name = forms.CharField(label=_('First name'), required=False) last_name = forms.CharField(label=_('Last name'), required=False) email = EmailField( label=_('Email'), help_text=_('Used for password resets and, optionally, e-mail reminders.'), required=False, ) birthdate = forms.DateField( label=_('Date of Birth'), required=False, widget=forms.DateInput( attrs={ 'type': 'date', 'max': str(date.today().replace(year=date.today().year - 10)), 'min': str(date.today().replace(year=date.today().year - 100)), }, ), ) class Meta: model = UserProfile fields = ( 'show_comments', 'show_english_ingredients', 'workout_reminder_active', 'workout_reminder', 'workout_duration', 'notification_language', 'weight_unit', 'ro_access', 'num_days_weight_reminder', 'birthdate', ) def __init__(self, *args, **kwargs): super(UserPreferencesForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'wger-form' self.helper.layout = Layout( Fieldset( _('Personal data'), 'email', Row( Column('first_name', css_class='col-6'), Column('last_name', css_class='col-6'), css_class='form-row', ), 'birthdate', HTML('<hr>'), ), Fieldset( _('Workout reminders'), 'workout_reminder_active', 'workout_reminder', 'workout_duration', HTML('<hr>'), ), Fieldset( _('Other settings'), 'ro_access', 'notification_language', 'weight_unit', 'show_comments', 'show_english_ingredients', 'num_days_weight_reminder', ), ButtonHolder(Submit('submit', _('Save'), css_class='btn-success btn-block')), ) class UserEmailForm(forms.ModelForm): email = EmailField( label=_('Email'), help_text=_('Used for password resets and, optionally, email reminders.'), required=False, ) class Meta: model = User fields = ('email',) def clean_email(self): """ E-mail must be unique system-wide However, this check should only be performed when the user changes e-mail address, otherwise the uniqueness check will because it will find one user (the current one) using the same e-mail. Only when the user changes it, do we want to check that nobody else has that e-mail address. """ email = self.cleaned_data['email'] if not email: return email try: # Performs a case-insensitive lookup user = User.objects.get(email__iexact=email) if user.email == self.instance.email: return email except User.DoesNotExist: return email raise ValidationError(_('This e-mail address is already in use.')) class UserPersonalInformationForm(UserEmailForm): first_name = forms.CharField(label=_('First name'), required=False) last_name = forms.CharField(label=_('Last name'), required=False) class Meta: model = User fields = ('first_name', 'last_name', 'email') class PasswordConfirmationForm(Form): """ A simple password confirmation form. This can be used to make sure the user really wants to perform a dangerous action. The form must be initialised with a user object. """ password = CharField( label=_('Password'), widget=PasswordInput, help_text=_('Please enter your current password.'), ) def __init__(self, user, data=None): self.user = user super(PasswordConfirmationForm, self).__init__(data=data) self.helper = FormHelper() self.helper.layout = Layout( 'password', ButtonHolder(Submit('submit', _('Delete'), css_class='btn-danger btn-block')), ) def clean_password(self): """ Check that the password supplied matches the one for the user """ password = self.cleaned_data.get('password', None) if not self.user.check_password(password): raise ValidationError(_('Invalid password')) return self.cleaned_data.get('password') class RegistrationForm(UserCreationForm, UserEmailForm): """ Registration form with reCAPTCHA field """ captcha = ReCaptchaField( widget=ReCaptchaV3, label='reCaptcha', help_text=_('The form is secured with reCAPTCHA'), ) def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'wger-form' self.helper.layout = Layout( 'username', 'email', Row( Column('password1', css_class='col-md-6 col-12'), Column('password2', css_class='col-md-6 col-12'), css_class='form-row', ), 'captcha', ButtonHolder(Submit('submitBtn', _('Register'), css_class='btn-success btn-block')), ) class RegistrationFormNoCaptcha(UserCreationForm, UserEmailForm): """ Registration form without CAPTCHA field """ def __init__(self, *args, **kwargs): super(RegistrationFormNoCaptcha, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'wger-form' self.helper.layout = Layout( 'username', 'email', Row( Column('password1', css_class='col-md-6 col-12'), Column('password2', css_class='col-md-6 col-12'), css_class='form-row', ), ButtonHolder( Submit('submit', _('Register'), css_class='btn-success col-sm-6 col-12'), css_class='text-center', ), ) class FeedbackRegisteredForm(forms.Form): """ Feedback form used for logged-in users """ contact = forms.CharField( max_length=50, min_length=10, label=_('Contact'), help_text=_('Some way of answering you (e-mail, etc.)'), required=False, ) comment = forms.CharField( max_length=500, min_length=10, widget=widgets.Textarea, label=_('Comment'), help_text=_('What do you want to say?'), required=True, ) class FeedbackAnonymousForm(FeedbackRegisteredForm): """ Feedback form used for anonymous users (has additionally a reCAPTCHA field) """ captcha = ReCaptchaField( widget=ReCaptchaV3, label='reCaptcha', help_text=_('The form is secured with reCAPTCHA'), )
10,374
Python
.py
290
26.906897
96
0.598904
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,757
profile.py
wger-project_wger/wger/core/models/profile.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 decimal # Django from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.validators import ( MaxValueValidator, MinValueValidator, ) from django.db import models from django.db.models import IntegerField from django.utils.translation import gettext_lazy as _ # wger from wger.gym.models import Gym from wger.utils.constants import TWOPLACES from wger.utils.units import ( AbstractHeight, AbstractWeight, ) from wger.weight.models import WeightEntry # Local from .language import Language def birthdate_validator(birthdate): """ Checks to see if entered birthdate (datetime.date object) is between 10 and 100 years of age. """ max_year = birthdate.replace(year=(birthdate.year + 100)) min_year = birthdate.replace(year=(birthdate.year + 10)) today = datetime.date.today() if today > max_year or today < min_year: raise ValidationError( _('%(birthdate)s is not a valid birthdate'), params={'birthdate': birthdate}, ) class UserProfile(models.Model): GENDER_MALE = '1' GENDER_FEMALE = '2' GENDER = ( (GENDER_MALE, _('Male')), (GENDER_FEMALE, _('Female')), ) INTENSITY_LOW = '1' INTENSITY_MEDIUM = '2' INTENSITY_HIGH = '3' INTENSITY = ( (INTENSITY_LOW, _('Low')), (INTENSITY_MEDIUM, _('Medium')), (INTENSITY_HIGH, _('High')), ) UNITS_KG = 'kg' UNITS_LB = 'lb' UNITS = ( (UNITS_KG, _('Metric (kilogram)')), (UNITS_LB, _('Imperial (pound)')), ) user = models.OneToOneField( User, editable=False, on_delete=models.CASCADE, ) """ The user """ gym = models.ForeignKey( Gym, editable=False, null=True, blank=True, on_delete=models.SET_NULL, ) """ The gym this user belongs to, if any """ email_verified = models.BooleanField(default=False) """Flag indicating whether the user's email has been verified""" is_temporary = models.BooleanField(default=False, editable=False) """ Flag to mark a temporary user (demo account) """ # # User preferences # show_comments = models.BooleanField( verbose_name=_('Show exercise comments'), help_text=_('Check to show exercise comments on the ' 'workout view'), default=True, ) """ Show exercise comments on workout view """ # Also show ingredients in english while composing a nutritional plan # (obviously this is only meaningful if the user has a language other than english) show_english_ingredients = models.BooleanField( verbose_name=_('Also use ingredients in English'), help_text=_( """Check to also show ingredients in English while creating a nutritional plan. These ingredients are extracted from a list provided by the US Department of Agriculture. It is extremely complete, with around 7000 entries, but can be somewhat overwhelming and make the search difficult.""" ), default=True, ) workout_reminder_active = models.BooleanField( verbose_name=_('Activate workout reminders'), help_text=_( 'Check to activate automatic ' 'reminders for workouts. You need ' 'to provide a valid email for this ' 'to work.' ), default=False, ) workout_reminder = IntegerField( verbose_name=_('Remind before expiration'), help_text=_('The number of days you want to be reminded ' 'before a workout expires.'), default=14, validators=[MinValueValidator(1), MaxValueValidator(30)], ) workout_duration = IntegerField( verbose_name=_('Default duration of workouts'), help_text=_( 'Default duration in weeks of workouts not ' 'in a schedule. Used for email workout ' 'reminders.' ), default=12, validators=[MinValueValidator(1), MaxValueValidator(30)], ) last_workout_notification = models.DateField(editable=False, blank=False, null=True) """ The last time the user got a workout reminder email This is needed e.g. to check daily per cron for old workouts but only send users an email once per week """ notification_language = models.ForeignKey( Language, verbose_name=_('Notification language'), help_text=_( 'Language to use when sending you email ' 'notifications, e.g. email reminders for ' 'workouts. This does not affect the ' 'language used on the website.' ), default=2, on_delete=models.CASCADE, ) @property def is_trustworthy(self) -> bool: """ Flag indicating whether the user "is trustworthy" and can submit or edit exercises At the moment the criteria are: - the account has existed for 3 weeks - the email address has been verified """ # Superusers are always trustworthy if self.user.is_superuser: return True # Temporary users are never trustworthy if self.is_temporary: return False days_since_joined = datetime.date.today() - self.user.date_joined.date() minimum_account_age = settings.WGER_SETTINGS['MIN_ACCOUNT_AGE_TO_TRUST'] return days_since_joined.days > minimum_account_age and self.email_verified # # User statistics # age = IntegerField( verbose_name=_('Age'), blank=False, null=True, validators=[MinValueValidator(10), MaxValueValidator(100)], ) """The user's age""" birthdate = models.DateField( verbose_name=_('Date of Birth'), blank=False, null=True, validators=[birthdate_validator], ) """The user's date of birth""" height = IntegerField( verbose_name=_('Height (cm)'), blank=False, validators=[MinValueValidator(140), MaxValueValidator(230)], null=True, ) """The user's height""" gender = models.CharField( max_length=1, choices=GENDER, default=GENDER_MALE, blank=False, null=True, ) """Gender""" sleep_hours = IntegerField( verbose_name=_('Hours of sleep'), help_text=_('The average hours of sleep per day'), default=7, blank=False, null=True, validators=[MinValueValidator(4), MaxValueValidator(10)], ) """The average hours of sleep per day""" work_hours = IntegerField( verbose_name=_('Work'), help_text=_('Average hours per day'), default=8, blank=False, null=True, validators=[MinValueValidator(1), MaxValueValidator(15)], ) """The average hours at work per day""" work_intensity = models.CharField( verbose_name=_('Physical intensity'), help_text=_('Approximately'), max_length=1, choices=INTENSITY, default=INTENSITY_LOW, blank=False, null=True, ) """Physical intensity of work""" sport_hours = IntegerField( verbose_name=_('Sport'), help_text=_('Average hours per week'), default=3, blank=False, null=True, validators=[MinValueValidator(1), MaxValueValidator(30)], ) """The average hours performing sports per week""" sport_intensity = models.CharField( verbose_name=_('Physical intensity'), help_text=_('Approximately'), max_length=1, choices=INTENSITY, default=INTENSITY_MEDIUM, blank=False, null=True, ) """Physical intensity of sport activities""" freetime_hours = IntegerField( verbose_name=_('Free time'), help_text=_('Average hours per day'), default=8, blank=False, null=True, validators=[MinValueValidator(1), MaxValueValidator(15)], ) """The average hours of free time per day""" freetime_intensity = models.CharField( verbose_name=_('Physical intensity'), help_text=_('Approximately'), max_length=1, choices=INTENSITY, default=INTENSITY_LOW, blank=False, null=True, ) """Physical intensity during free time""" calories = IntegerField( verbose_name=_('Total daily calories'), help_text=_('Total caloric intake, including e.g. any surplus'), default=2500, blank=False, null=True, validators=[MinValueValidator(1500), MaxValueValidator(5000)], ) """Basic caloric intake based on physical activity""" # # Others # weight_unit = models.CharField( verbose_name=_('Weight unit'), max_length=2, choices=UNITS, default=UNITS_KG, ) """Preferred weight unit""" ro_access = models.BooleanField( verbose_name=_('Allow external access'), help_text=_( 'Allow external users to access your workouts and ' 'logs in a read-only mode. You need to set this ' 'before you can share links e.g. to social media.' ), default=False, ) """Allow anonymous read-only access""" num_days_weight_reminder = models.IntegerField( verbose_name=_('Automatic reminders for weight ' 'entries'), help_text=_('Number of days after the last ' 'weight entry (enter 0 to ' 'deactivate)'), validators=[MinValueValidator(0), MaxValueValidator(30)], default=0, ) """Number of Days for email weight reminder""" # # API # added_by = models.ForeignKey( User, editable=False, null=True, related_name='added_by', on_delete=models.CASCADE, ) """User that originally registered this user via REST API""" can_add_user = models.BooleanField(default=False, editable=False) """ Flag to indicate whether the (app) user can register other users on his behalf over the REST API """ @property def weight(self): """ Returns the last weight entry, done here to make the behaviour more consistent with the other settings (age, height, etc.) """ try: weight = WeightEntry.objects.filter(user=self.user).latest().weight except WeightEntry.DoesNotExist: weight = 0 return weight @property def address(self): """ Return the address as saved in the current contract (user's gym) """ out = { 'zip_code': '', 'city': '', 'street': '', 'phone': '', } if self.user.contract_member.exists(): last_contract = self.user.contract_member.last() out['zip_code'] = last_contract.zip_code out['city'] = last_contract.city out['street'] = last_contract.street out['phone'] = last_contract.phone return out def clean(self): """ Make sure the total amount of hours is 24 """ if (self.sleep_hours and self.freetime_hours and self.work_hours) and ( self.sleep_hours + self.freetime_hours + self.work_hours ) > 24: raise ValidationError(_('The sum of all hours has to be 24')) def __str__(self): """ Return a more human-readable representation """ return f'Profile for user {self.user}' @property def use_metric(self): """ Simple helper that checks whether the user uses metric units or not :return: Boolean """ return self.weight_unit == 'kg' def calculate_bmi(self): """ Calculates the user's BMI Formula: weight/height^2 - weight in kg - height in m """ # If not all the data is available, return 0, otherwise the result # of the calculation below breaks django's template filters if not self.weight or not self.height: return 0 weight = self.weight if self.use_metric else AbstractWeight(self.weight, 'lb').kg height = self.height if self.use_metric else AbstractHeight(self.height, 'inches').inches return weight / pow(height / decimal.Decimal(100), 2) def calculate_basal_metabolic_rate(self, formula=1): """ Calculates the basal metabolic rate. Currently only the Mifflin-St.Jeor formula is supported """ factor = 5 if self.gender == self.GENDER_MALE else -161 weight = self.weight if self.use_metric else AbstractWeight(self.weight, 'lb').kg try: rate = ( (10 * weight) # in kg + (decimal.Decimal(6.25) * self.height) # in cm - (5 * self.age) # in years + factor ) # Any of the entries is missing except TypeError: rate = 0 return decimal.Decimal(str(rate)).quantize(TWOPLACES) def calculate_activities(self): """ Calculates the calories needed by additional physical activities Factors taken from * https://en.wikipedia.org/wiki/Physical_activity_level * http://www.fao.org/docrep/007/y5686e/y5686e07.htm """ # Sleep sleep = self.sleep_hours * 0.95 # Work if self.work_intensity == self.INTENSITY_LOW: work_factor = 1.5 elif self.work_intensity == self.INTENSITY_MEDIUM: work_factor = 1.8 else: work_factor = 2.2 work = self.work_hours * work_factor # Sport (entered in hours/week, so we must divide) if self.sport_intensity == self.INTENSITY_LOW: sport_factor = 4 elif self.sport_intensity == self.INTENSITY_MEDIUM: sport_factor = 6 else: sport_factor = 10 sport = (self.sport_hours / 7.0) * sport_factor # Free time if self.freetime_intensity == self.INTENSITY_LOW: freetime_factor = 1.3 elif self.freetime_intensity == self.INTENSITY_MEDIUM: freetime_factor = 1.9 else: freetime_factor = 2.4 freetime = self.freetime_hours * freetime_factor # Total total = (sleep + work + sport + freetime) / 24.0 return decimal.Decimal(str(total)).quantize(TWOPLACES) def user_bodyweight(self, weight): """ Create a new weight entry as needed """ if not WeightEntry.objects.filter(user=self.user).exists() or ( datetime.date.today() - WeightEntry.objects.filter(user=self.user).latest().date > datetime.timedelta(days=3) ): entry = WeightEntry() entry.weight = weight entry.user = self.user entry.date = datetime.date.today() entry.save() # Update the last entry else: entry = WeightEntry.objects.filter(user=self.user).latest() entry.weight = weight entry.save() return entry def get_owner_object(self): """ Returns the object that has owner information """ return self
16,285
Python
.py
472
26.724576
97
0.6173
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,758
license.py
wger-project_wger/wger/core/models/license.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 License(models.Model): """ License for an item (exercise, ingredient, etc.) """ full_name = models.CharField( max_length=60, verbose_name=_('Full name'), help_text=_( 'If a license has been localized, e.g. the Creative ' 'Commons licenses for the different countries, add ' 'them as separate entries here.' ), ) """Full name""" short_name = models.CharField( max_length=15, verbose_name=_('Short name, e.g. CC-BY-SA 3'), ) """Short name, e.g. CC-BY-SA 3""" url = models.URLField( verbose_name=_('Link'), help_text=_('Link to license text or other information'), blank=True, null=True, ) """URL to full license text or other information""" class Meta: """ Set Meta options """ ordering = [ 'full_name', ] # # Django methods # def __str__(self): """ Return a more human-readable representation """ return f'{self.full_name} ({self.short_name})' # # Own methods # def get_owner_object(self): """ License has no owner information """ return None
2,169
Python
.py
67
26.507463
79
0.633843
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,759
language.py
wger-project_wger/wger/core/models/language.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.urls import reverse from django.utils.translation import gettext_lazy as _ class Language(models.Model): """ Language of an item (exercise, workout, etc.) """ # e.g. 'de' short_name = models.CharField( max_length=2, verbose_name=_('Language short name'), help_text='ISO 639-1', unique=True, ) # e.g. 'Deutsch' full_name = models.CharField( max_length=30, verbose_name=_('Language full name'), ) # e.g. 'German' full_name_en = models.CharField( max_length=30, verbose_name=_('Language full name in English'), ) class Meta: """ Set Meta options """ ordering = [ 'full_name', ] # # Django methods # def __str__(self): """ Return a more human-readable representation """ return f'{self.full_name} ({self.short_name})' def get_absolute_url(self): """ Returns the canonical URL to view a language """ return reverse('core:language:view', kwargs={'pk': self.id}) # # Own methods # def get_owner_object(self): """ Muscle has no owner information """ return False @property def static_path(self): return f'images/icons/flags/{self.short_name}.svg'
2,219
Python
.py
71
25.633803
79
0.641386
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,760
weight_unit.py
wger-project_wger/wger/core/models/weight_unit.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 WeightUnit(models.Model): """ Weight unit, used in combination with an amount such as '10 kg', '5 plates' """ class Meta: """ Set Meta options """ ordering = [ 'name', ] name = models.CharField(max_length=100, verbose_name=_('Name')) def __str__(self): """ Return a more human-readable representation """ return self.name # # Own methods # def get_owner_object(self): """ Unit has no owner information """ return None @property def is_weight(self): """ Checks that the unit is a weight proper This is done basically to not litter the code with magic IDs """ return self.id in (1, 2)
1,698
Python
.py
50
28.68
79
0.664835
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,761
days_of_week.py
wger-project_wger/wger/core/models/days_of_week.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 DaysOfWeek(models.Model): """ Model for the days of the week This model is needed so that 'Day' can have multiple days of the week selected """ day_of_week = models.CharField(max_length=9, verbose_name=_('Day of the week')) class Meta: """ Order by day-ID, this is needed for some DBs """ ordering = [ 'pk', ] def __str__(self): """ Return a more human-readable representation """ return self.day_of_week
1,426
Python
.py
36
35.277778
83
0.699711
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,762
cache.py
wger-project_wger/wger/core/models/cache.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 class UserCache(models.Model): """ A table used to cache expensive queries or similar """ user = models.OneToOneField(User, editable=False, on_delete=models.CASCADE) """ The user """ last_activity = models.DateField(null=True) """ The user's last activity. Values for this entry are saved by signals as calculated by the get_user_last_activity helper function. """ def __str__(self): """ Return a more human-readable representation """ return f'Cache for user {self.user}'
1,452
Python
.py
37
35.675676
79
0.724432
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,763
__init__.py
wger-project_wger/wger/core/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 .cache import UserCache from .days_of_week import DaysOfWeek from .language import Language from .license import License from .profile import UserProfile from .rep_unit import RepetitionUnit from .weight_unit import WeightUnit
1,043
Python
.py
23
44.304348
79
0.786065
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,764
rep_unit.py
wger-project_wger/wger/core/models/rep_unit.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 RepetitionUnit(models.Model): """ Setting unit, used in combination with an amount such as '10 reps', '5 km' """ class Meta: """ Set Meta options """ ordering = [ 'name', ] name = models.CharField(max_length=100, verbose_name=_('Name')) def __str__(self): """ Return a more human-readable representation """ return self.name # # Own methods # def get_owner_object(self): """ Unit has no owner information """ return None @property def is_repetition(self): """ Checks that the repetition unit is a repetition proper This is done basically to not litter the code with magic IDs """ return self.id == 1
1,715
Python
.py
50
29.02
79
0.668882
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,765
wger_extras.py
wger-project_wger/wger/core/templatetags/wger_extras.py
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # Standard Library from collections.abc import Iterable # Django from django import template from django.templatetags.static import static from django.utils.safestring import mark_safe from django.utils.translation import ( gettext_lazy as _, pgettext, ) # wger from wger.manager.models import Day from wger.utils.constants import ( PAGINATION_MAX_TOTAL_PAGES, PAGINATION_PAGES_AROUND_CURRENT, ) from wger.utils.language import get_language_data register = template.Library() @register.filter(name='get_current_settings') def get_current_settings(exercise, set_id): """ Does a filter on the sets We need to do this here because it's not possible to pass arguments to function in the template, and we are only interested on the settings that belong to the current set """ return exercise.exercise_base.setting_set.filter(set_id=set_id) @register.inclusion_tag('tags/render_day.html') def render_day(day: Day, editable=True): """ Renders a day as it will be displayed in the workout overview """ return { 'day': day, 'workout': day.training, 'editable': editable, } @register.inclusion_tag('tags/pagination.html') def pagination(paginator, page): """ Renders the necessary links to paginating a long list """ # For very long lists (e.g. the English ingredient with more than 8000 items) # we muck around here to remove the pages not inmediately 'around' the current # one, otherwise we end up with a useless block with 300 pages. if paginator.num_pages > PAGINATION_MAX_TOTAL_PAGES: start_page = page.number - PAGINATION_PAGES_AROUND_CURRENT for i in range(page.number - PAGINATION_PAGES_AROUND_CURRENT, page.number + 1): if i > 0: start_page = i break end_page = page.number + PAGINATION_PAGES_AROUND_CURRENT for i in range(page.number, page.number + PAGINATION_PAGES_AROUND_CURRENT): if i > paginator.num_pages: end_page = i break page_range = range(start_page, end_page) else: page_range = paginator.page_range # Set the template variables return {'page': page, 'page_range': page_range} @register.inclusion_tag('tags/render_weight_log.html') def render_weight_log(log, div_uuid, user=None): """ Renders a weight log series """ return { 'log': log, 'div_uuid': div_uuid, 'user': user, } @register.inclusion_tag('tags/muscles.html') def render_muscles(muscles=None, muscles_sec=None): """ Renders the given muscles """ out = {'backgrounds': []} if not muscles and not muscles_sec: return out out_main = [] if muscles: out_main = muscles if isinstance(muscles, Iterable) else [muscles] out_secondary = [] if muscles_sec: out_secondary = muscles_sec if isinstance(muscles_sec, Iterable) else [muscles_sec] if out_main: front_back = 'front' if out_main[0].is_front else 'back' else: front_back = 'front' if out_secondary[0].is_front else 'back' out['backgrounds'] = ( [i.image_url_main for i in out_main] + [i.image_url_secondary for i in out_secondary] + [static(f'images/muscles/muscular_system_{front_back}.svg')] ) return out @register.inclusion_tag('tags/language_select.html', takes_context=True) def language_select(context, language): """ Renders a link to change the current language. """ return {**get_language_data(language), 'i18n_path': context['i18n_path'][language[0]]} @register.filter def get_item(dictionary, key): """ Allows to access a specific key in a dictionary in a template """ return dictionary.get(key) @register.filter def minus(a, b): """ Simple function that subtracts two values in a template """ return a - b @register.filter def is_positive(a): """ Simple function that checks whether one value is bigger than the other """ return a > 0 @register.simple_tag def fa_class(class_name='', icon_type='fas', fixed_width=True): """ Helper function to help add font awesome classes to elements :param class_name: the CSS class name, without the "fa-" prefix :param fixed_width: toggle for fixed icon width :param icon_type; icon type ( :return: the complete CSS classes """ css = '' if not class_name: return css css += f'{icon_type} fa-{class_name}' if fixed_width: css += ' fa-fw' return mark_safe(css) @register.simple_tag def trans_weight_unit(unit, user=None): """ Returns the correct (translated) weight unit :param unit: the weight unit. Allowed values are 'kg' and 'g' :param user: the user object, needed to access the profile. If this evaluates to False, metric is used :return: translated unit """ if not user or user.userprofile.use_metric: if unit == 'kg': return _('kg') if unit == 'g': return pgettext('weight unit, i.e. grams', 'g') else: if unit == 'kg': return _('lb') if unit == 'g': return pgettext('weight unit, i.e. ounces', 'oz') @register.filter def format_username(user): """ Formats the username according to the information available """ if user.get_full_name(): return user.get_full_name() elif user.email: return user.email else: return user.username
6,245
Python
.py
179
29.536313
91
0.674585
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,766
0006_auto_20151025_2237.py
wger-project_wger/wger/core/migrations/0006_auto_20151025_2237.py
# -*- coding: utf-8 -*- from django.db import migrations, models def create_usercache(apps, schema_editor): """ Creates a usercache table for all users """ User = apps.get_model('auth', 'User') Usercache = apps.get_model('core', 'Usercache') WorkoutLog = apps.get_model('manager', 'WorkoutLog') WorkoutSession = apps.get_model('manager', 'WorkoutSession') for user in User.objects.all(): # # This is the logic of get_user_last_activity at the time this migration # was created. # 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 # Create the cache entry Usercache.objects.create(user=user, last_activity=last_activity) def delete_usercache(apps, schema_editor): """ Deletes the usercache table for all users """ Usercache = apps.get_model('core', 'Usercache') for cache in Usercache.objects.all(): cache.delete() class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20151025_2236'), ('auth', '0006_require_contenttypes_0002'), ('manager', '0004_auto_20150609_1603'), ] operations = [migrations.RunPython(create_usercache, delete_usercache)]
1,789
Python
.py
46
31.152174
87
0.636784
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,767
0012_auto_20210210_1228.py
wger-project_wger/wger/core/migrations/0012_auto_20210210_1228.py
# Generated by Django 3.1.5 on 2021-02-10 11:28 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0011_auto_20201201_0653'), ] operations = [ migrations.AddField( model_name='userprofile', name='added_by', field=models.ForeignKey( editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='added_by', to=settings.AUTH_USER_MODEL, ), ), migrations.AddField( model_name='userprofile', name='can_add_user', field=models.BooleanField(default=False, editable=False), ), ]
908
Python
.py
27
24.037037
69
0.595211
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,768
0007_repetitionunit.py
wger-project_wger/wger/core/migrations/0007_repetitionunit.py
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0006_auto_20151025_2237'), ] operations = [ migrations.CreateModel( name='RepetitionUnit', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, primary_key=True, auto_created=True ), ), ('name', models.CharField(verbose_name='Name', max_length=100)), ], options={ 'ordering': ['name'], }, ), ]
695
Python
.py
23
18.26087
95
0.458084
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,769
0013_auto_20210726_1729.py
wger-project_wger/wger/core/migrations/0013_auto_20210726_1729.py
# Generated by Django 3.2.3 on 2021-07-26 15:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0012_auto_20210210_1228'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='timer_active', ), migrations.RemoveField( model_name='userprofile', name='timer_pause', ), ]
448
Python
.py
16
20.25
47
0.588785
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,770
0003_auto_20150217_1554.py
wger-project_wger/wger/core/migrations/0003_auto_20150217_1554.py
# -*- coding: utf-8 -*- from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [ ('core', '0002_auto_20141225_1512'), ] operations = [ migrations.AddField( model_name='userprofile', name='num_days_weight_reminder', field=models.IntegerField( verbose_name='Automatic reminders for weight entries', max_length=30, null=True, help_text='Number of days after the last weight entry (enter 0 to deactivate)', ), preserve_default=True, ), migrations.AlterField( model_name='userprofile', name='age', field=models.IntegerField( verbose_name='Age', null=True, validators=[ django.core.validators.MinValueValidator(10), django.core.validators.MaxValueValidator(100), ], ), preserve_default=True, ), migrations.AlterField( model_name='userprofile', name='height', field=models.IntegerField( verbose_name='Height (cm)', null=True, validators=[ django.core.validators.MinValueValidator(140), django.core.validators.MaxValueValidator(230), ], ), preserve_default=True, ), migrations.AlterField( model_name='userprofile', name='ro_access', field=models.BooleanField( verbose_name='Allow external access', default=False, help_text='Allow external users to access your workouts and logs in a read-only mode. You need to set this before you can share links e.g. to social media.', ), preserve_default=True, ), ]
2,016
Python
.py
56
23.357143
173
0.534254
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,771
0010_auto_20170403_0144.py
wger-project_wger/wger/core/migrations/0010_auto_20170403_0144.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-04-02 16:44 from django.db import migrations, models import wger.core.models class Migration(migrations.Migration): dependencies = [ ('core', '0009_auto_20160303_2340'), ] operations = [ migrations.AddField( model_name='userprofile', name='birthdate', field=models.DateField( null=True, validators=[wger.core.models.profile.birthdate_validator], verbose_name='Date of Birth', ), ), migrations.AlterField( model_name='license', name='full_name', field=models.CharField( help_text='If a license has been localized, e.g. the Creative Commons licenses for the different countries, add them as separate entries here.', max_length=60, verbose_name='Full name', ), ), ]
976
Python
.py
28
24.857143
160
0.572034
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,772
0011_auto_20201201_0653.py
wger-project_wger/wger/core/migrations/0011_auto_20201201_0653.py
# Generated by Django 3.1.3 on 2020-12-01 05:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('gym', '0008_auto_20190618_1617'), ('core', '0010_auto_20170403_0144'), ] operations = [ migrations.AlterField( model_name='userprofile', name='gym', field=models.ForeignKey( blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, to='gym.gym', ), ), ]
641
Python
.py
21
20.952381
61
0.553571
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,773
0016_alter_language_short_name.py
wger-project_wger/wger/core/migrations/0016_alter_language_short_name.py
# Generated by Django 4.2 on 2023-04-07 14:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0015_alter_language_short_name'), ] operations = [ migrations.AlterField( model_name='language', name='short_name', field=models.CharField( help_text='ISO 639-1', max_length=2, unique=True, verbose_name='Language short name' ), ), ]
494
Python
.py
15
24.733333
100
0.6
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,774
0014_merge_20210818_1735.py
wger-project_wger/wger/core/migrations/0014_merge_20210818_1735.py
# Generated by Django 3.2.3 on 2021-08-18 15:35 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0013_auto_20210726_1729'), ('core', '0013_userprofile_email_verified'), ] operations = []
269
Python
.py
8
28.625
52
0.673152
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,775
0013_userprofile_email_verified.py
wger-project_wger/wger/core/migrations/0013_userprofile_email_verified.py
# Generated by Django 3.2.3 on 2021-06-08 22:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0012_auto_20210210_1228'), ] operations = [ migrations.AddField( model_name='userprofile', name='email_verified', field=models.BooleanField(default=False), ), ]
396
Python
.py
13
23.307692
53
0.62533
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,776
0017_language_full_name_en.py
wger-project_wger/wger/core/migrations/0017_language_full_name_en.py
# Generated by Django 4.2.6 on 2024-01-17 15:41 from django.db import migrations, models def update_language_full_name(apps, schema_editor): mapper = { 'de': 'German', 'en': 'English', 'bg': 'Bulgarian', 'es': 'Spanish', 'ru': 'Russian', 'nl': 'Dutch', 'pt': 'Portuguese', 'el': 'Greek', 'cs': 'Czech', 'sv': 'Swedish', 'no': 'Norwegian', 'fr': 'French', 'it': 'Italian', 'pl': 'Polish', 'uk': 'Ukrainian', 'tr': 'Turkish', 'ar': 'Arabic', 'az': 'Azerbaijani', 'eo': 'Esperanto', 'fa': 'Persian', 'he': 'Hebrew', 'hr': 'Croatian', 'id': 'Indonesian', 'zh': 'Chinese', } Language = apps.get_model('core', 'Language') for language in Language.objects.all(): language.full_name_en = mapper.get(language.short_name, 'English') language.save() class Migration(migrations.Migration): dependencies = [ ('core', '0016_alter_language_short_name'), ] operations = [ migrations.AddField( model_name='language', name='full_name_en', field=models.CharField( default='english', max_length=30, verbose_name='Language full name in English', ), preserve_default=False, ), migrations.RunPython( update_language_full_name, reverse_code=migrations.RunPython.noop, ), ]
1,568
Python
.py
53
20.679245
74
0.513926
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,777
0002_auto_20141225_1512.py
wger-project_wger/wger/core/migrations/0002_auto_20141225_1512.py
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AddField( model_name='userprofile', name='ro_access', field=models.BooleanField( help_text='Allow anonymous users to access your workouts and logs in a read-only mode. You can then share the links to social media.', verbose_name='Allow read-only access', default=False, ), preserve_default=True, ), migrations.AlterField( model_name='userprofile', name='freetime_intensity', field=models.CharField( choices=[('1', 'Low'), ('2', 'Medium'), ('3', 'High')], null=True, max_length=1, help_text='Approximately', default='1', verbose_name='Physical intensity', ), preserve_default=True, ), migrations.AlterField( model_name='userprofile', name='gender', field=models.CharField( choices=[('1', 'Male'), ('2', 'Female')], null=True, default='1', max_length=1 ), preserve_default=True, ), migrations.AlterField( model_name='userprofile', name='sport_intensity', field=models.CharField( choices=[('1', 'Low'), ('2', 'Medium'), ('3', 'High')], null=True, max_length=1, help_text='Approximately', default='2', verbose_name='Physical intensity', ), preserve_default=True, ), migrations.AlterField( model_name='userprofile', name='weight_unit', field=models.CharField( choices=[('kg', 'Metric (kilogram)'), ('lb', 'Imperial (pound)')], verbose_name='Weight unit', max_length=2, default='kg', ), preserve_default=True, ), migrations.AlterField( model_name='userprofile', name='work_intensity', field=models.CharField( choices=[('1', 'Low'), ('2', 'Medium'), ('3', 'High')], null=True, max_length=1, help_text='Approximately', default='1', verbose_name='Physical intensity', ), preserve_default=True, ), ]
2,666
Python
.py
76
22.236842
151
0.481439
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,778
0005_auto_20151025_2236.py
wger-project_wger/wger/core/migrations/0005_auto_20151025_2236.py
# -*- coding: utf-8 -*- from django.db import migrations, models import django.core.validators from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0004_auto_20150217_1914'), ] operations = [ migrations.CreateModel( name='UserCache', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID' ), ), ('last_activity', models.DateField(null=True)), ( 'user', models.OneToOneField( editable=False, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE ), ), ], ), migrations.AlterField( model_name='userprofile', name='num_days_weight_reminder', field=models.IntegerField( default=0, verbose_name='Automatic reminders for weight entries', help_text='Number of days after the last weight entry (enter 0 to deactivate)', validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(30), ], ), ), ]
1,504
Python
.py
42
22.428571
95
0.510288
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,779
0001_initial.py
wger-project_wger/wger/core/migrations/0001_initial.py
# -*- coding: utf-8 -*- from django.db import models, migrations from django.conf import settings import django.core.validators class Migration(migrations.Migration): dependencies = [ ('gym', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='DaysOfWeek', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ('day_of_week', models.CharField(max_length=9, verbose_name='Day of the week')), ], options={ 'ordering': ['pk'], }, bases=(models.Model,), ), migrations.CreateModel( name='Language', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ('short_name', models.CharField(max_length=2, verbose_name='Language short name')), ('full_name', models.CharField(max_length=30, verbose_name='Language full name')), ], options={ 'ordering': ['full_name'], }, bases=(models.Model,), ), migrations.CreateModel( name='License', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ('full_name', models.CharField(max_length=60, verbose_name='Full name')), ( 'short_name', models.CharField(max_length=15, verbose_name='Short name, e.g. CC-BY-SA 3'), ), ( 'url', models.URLField( help_text='Link to license text or other information', null=True, verbose_name='Link', blank=True, ), ), ], options={ 'ordering': ['full_name'], }, bases=(models.Model,), ), migrations.CreateModel( name='UserProfile', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ('is_temporary', models.BooleanField(default=False, editable=False)), ( 'show_comments', models.BooleanField( default=True, help_text='Check to show exercise comments on the workout view', verbose_name='Show exercise comments', ), ), ( 'show_english_ingredients', models.BooleanField( default=True, help_text='Check to also show ingredients in English while creating\na nutritional plan. These ingredients are extracted from a list provided\nby the US Department of Agriculture. It is extremely complete, with around\n7000 entries, but can be somewhat overwhelming and make the search difficult.', verbose_name='Also use ingredients in English', ), ), ( 'workout_reminder_active', models.BooleanField( default=False, help_text='Check to activate automatic reminders for workouts. You need to provide a valid email for this to work.', verbose_name='Activate workout reminders', ), ), ( 'workout_reminder', models.IntegerField( default=14, help_text='The number of days you want to be reminded before a workout expires.', verbose_name='Remind before expiration', validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(30), ], ), ), ( 'workout_duration', models.IntegerField( default=12, help_text='Default duration in weeks of workouts not in a schedule. Used for email workout reminders.', verbose_name='Default duration of workouts', validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(30), ], ), ), ('last_workout_notification', models.DateField(null=True, editable=False)), ( 'timer_active', models.BooleanField( default=True, help_text='Check to activate timer pauses between exercises.', verbose_name='Use pauses in workout timer', ), ), ( 'timer_pause', models.IntegerField( default=90, help_text='Default duration in seconds of pauses used by the timer in the gym mode.', verbose_name='Default duration of workout pauses', validators=[ django.core.validators.MinValueValidator(10), django.core.validators.MaxValueValidator(400), ], ), ), ( 'age', models.IntegerField( max_length=2, null=True, verbose_name='Age', validators=[ django.core.validators.MinValueValidator(10), django.core.validators.MaxValueValidator(100), ], ), ), ( 'height', models.IntegerField( max_length=2, null=True, verbose_name='Height (cm)', validators=[ django.core.validators.MinValueValidator(140), django.core.validators.MaxValueValidator(230), ], ), ), ( 'gender', models.CharField( default=b'1', max_length=1, null=True, choices=[(b'1', 'Male'), (b'2', 'Female')], ), ), ( 'sleep_hours', models.IntegerField( default=7, help_text='The average hours of sleep per day', null=True, verbose_name='Hours of sleep', validators=[ django.core.validators.MinValueValidator(4), django.core.validators.MaxValueValidator(10), ], ), ), ( 'work_hours', models.IntegerField( default=8, help_text='Average hours per day', null=True, verbose_name='Work', validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(15), ], ), ), ( 'work_intensity', models.CharField( default=b'1', choices=[(b'1', 'Low'), (b'2', 'Medium'), (b'3', 'High')], max_length=1, help_text='Approximately', null=True, verbose_name='Physical intensity', ), ), ( 'sport_hours', models.IntegerField( default=3, help_text='Average hours per week', null=True, verbose_name='Sport', validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(30), ], ), ), ( 'sport_intensity', models.CharField( default=b'2', choices=[(b'1', 'Low'), (b'2', 'Medium'), (b'3', 'High')], max_length=1, help_text='Approximately', null=True, verbose_name='Physical intensity', ), ), ( 'freetime_hours', models.IntegerField( default=8, help_text='Average hours per day', null=True, verbose_name='Free time', validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(15), ], ), ), ( 'freetime_intensity', models.CharField( default=b'1', choices=[(b'1', 'Low'), (b'2', 'Medium'), (b'3', 'High')], max_length=1, help_text='Approximately', null=True, verbose_name='Physical intensity', ), ), ( 'calories', models.IntegerField( default=2500, help_text='Total caloric intake, including e.g. any surplus', null=True, verbose_name='Total daily calories', validators=[ django.core.validators.MinValueValidator(1500), django.core.validators.MaxValueValidator(5000), ], ), ), ( 'weight_unit', models.CharField( default=b'kg', max_length=2, verbose_name='Weight unit', choices=[(b'kg', 'Metric (kilogram)'), (b'lb', 'Imperial (pound)')], ), ), ( 'gym', models.ForeignKey( blank=True, editable=False, to='gym.Gym', null=True, on_delete=models.CASCADE, ), ), ( 'notification_language', models.ForeignKey( default=2, verbose_name='Notification language', to='core.Language', help_text='Language to use when sending you email notifications, e.g. email reminders for workouts. This does not affect the language used on the website.', on_delete=models.CASCADE, ), ), ( 'user', models.OneToOneField( editable=False, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE ), ), ], options={}, bases=(models.Model,), ), ]
13,101
Python
.py
322
20.046584
322
0.387554
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,780
0009_auto_20160303_2340.py
wger-project_wger/wger/core/migrations/0009_auto_20160303_2340.py
# -*- coding: utf-8 -*- from django.db import migrations, models def insert_data(apps, schema_editor): """ Inserts initial data for repetition and weight units Needed so that the migrations can go through without having to load any fixtures or perform any intermediate steps. """ WeightUnit = apps.get_model('core', 'WeightUnit') WeightUnit(name='kg', pk=1).save() WeightUnit(name='lb', pk=2).save() WeightUnit(name='Body Weight', pk=3).save() WeightUnit(name='Plates', pk=4).save() WeightUnit(name='Kilometers Per Hour', pk=5).save() WeightUnit(name='Miles Per Hour', pk=6).save() RepetitionUnit = apps.get_model('core', 'RepetitionUnit') RepetitionUnit(name='Repetitions', pk=1).save() RepetitionUnit(name='Until Failure', pk=2).save() RepetitionUnit(name='Seconds', pk=3).save() RepetitionUnit(name='Minutes', pk=4).save() RepetitionUnit(name='Miles', pk=5).save() RepetitionUnit(name='Kilometers', pk=6).save() class Migration(migrations.Migration): dependencies = [ ('core', '0008_weightunit'), ] operations = [ migrations.RunPython(insert_data, reverse_code=migrations.RunPython.noop), ]
1,210
Python
.py
29
36.724138
82
0.68798
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,781
0004_auto_20150217_1914.py
wger-project_wger/wger/core/migrations/0004_auto_20150217_1914.py
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20150217_1554'), ] operations = [ migrations.AlterField( model_name='userprofile', name='num_days_weight_reminder', field=models.IntegerField( default=0, verbose_name='Automatic reminders for weight entries', max_length=30, help_text='Number of days after the last weight entry (enter 0 to deactivate)', ), preserve_default=True, ), ]
644
Python
.py
19
24.052632
95
0.571659
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,782
0015_alter_language_short_name.py
wger-project_wger/wger/core/migrations/0015_alter_language_short_name.py
# Generated by Django 3.2.16 on 2022-11-10 14:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0014_merge_20210818_1735'), ] operations = [ migrations.AlterField( model_name='language', name='short_name', field=models.CharField(max_length=2, unique=True, verbose_name='Language short name'), ), ]
438
Python
.py
13
26.538462
98
0.634204
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,783
0008_weightunit.py
wger-project_wger/wger/core/migrations/0008_weightunit.py
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0007_repetitionunit'), ] operations = [ migrations.CreateModel( name='WeightUnit', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ('name', models.CharField(verbose_name='Name', max_length=100)), ], options={ 'ordering': ['name'], }, ), ]
687
Python
.py
23
17.913043
95
0.454545
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,784
license.py
wger-project_wger/wger/core/views/license.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.urls import reverse_lazy from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, ListView, UpdateView, ) # wger from wger.core.models import License from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) logger = logging.getLogger(__name__) class LicenseListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): """ Overview of all available licenses """ model = License permission_required = 'core.add_license' template_name = 'license/list.html' class LicenseAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView): """ View to add a new license """ model = License fields = ['full_name', 'short_name', 'url'] success_url = reverse_lazy('core:license:list') title = gettext_lazy('Add') permission_required = 'core.add_license' class LicenseUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView): """ View to update an existing license """ model = License fields = ['full_name', 'short_name', 'url'] success_url = reverse_lazy('core:license:list') permission_required = 'core.change_license' def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(LicenseUpdateView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object) return context class LicenseDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView): """ View to delete an existing license """ model = License success_url = reverse_lazy('core:license:list') permission_required = 'core.delete_license' def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(LicenseDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object) return context
2,921
Python
.py
84
30.535714
98
0.720625
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,785
react.py
wger-project_wger/wger/core/views/react.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.http import HttpResponseForbidden from django.views.generic import TemplateView class ReactView(TemplateView): """ ReactView is a TemplateView that renders a React page. """ template_name = 'react/react-page.html' div_id = 'react-page' login_required = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['div_id'] = self.div_id return context def dispatch(self, request, *args, **kwargs): """ Only logged-in users are allowed to access this page """ if self.login_required and not request.user.is_authenticated: return HttpResponseForbidden('You are not allowed to access this page') return super().dispatch(request, *args, **kwargs)
1,455
Python
.py
34
38.411765
83
0.729137
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,786
user.py
wger-project_wger/wger/core/views/user.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.conf import settings from django.contrib import messages from django.contrib.auth import ( authenticate, login as django_login, logout as django_logout, ) from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import ( LoginRequiredMixin, PermissionRequiredMixin, ) from django.contrib.auth.models import User from django.contrib.auth.views import ( LoginView, PasswordChangeView, PasswordResetConfirmView, PasswordResetView, ) from django.http import ( HttpResponseForbidden, HttpResponseNotFound, HttpResponseRedirect, ) from django.shortcuts import ( get_object_or_404, render, ) from django.template.context_processors import csrf from django.urls import ( reverse, reverse_lazy, ) from django.utils import translation from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( DetailView, ListView, RedirectView, UpdateView, ) # Third Party from crispy_forms.helper import FormHelper from crispy_forms.layout import ( ButtonHolder, Column, Layout, Row, Submit, ) from django_email_verification import send_email from rest_framework.authtoken.models import Token # wger from wger.config.models import GymConfig from wger.core.forms import ( PasswordConfirmationForm, RegistrationForm, RegistrationFormNoCaptcha, UserLoginForm, UserPersonalInformationForm, UserPreferencesForm, ) from wger.gym.models import ( AdminUserNote, Contract, GymUserConfig, ) from wger.manager.models import ( Workout, WorkoutLog, WorkoutSession, ) from wger.nutrition.models import NutritionPlan from wger.utils.api_token import create_token from wger.utils.generic_views import ( WgerFormMixin, WgerMultiplePermissionRequiredMixin, ) from wger.utils.language import load_language from wger.weight.models import WeightEntry logger = logging.getLogger(__name__) def login(request): """ Small wrapper around the django login view """ next_url = '?next=' + request.GET.get('next') if request.GET.get('next') else '' form = UserLoginForm form.helper.form_action = reverse('core:user:login') + next_url return LoginView.as_view(template_name='user/login.html', authentication_form=form) @login_required() def delete(request, user_pk=None): """ Delete a user account and all his data, requires password confirmation first If no user_pk is present, the user visiting the URL will be deleted, otherwise a gym administrator is deleting a different user """ if user_pk: user = get_object_or_404(User, pk=user_pk) # Forbidden if the user has not enough rights, doesn't belong to the # gym or is an admin as well. General admins can delete all users. if not request.user.has_perm('gym.manage_gyms') and ( not request.user.has_perm('gym.manage_gym') or request.user.userprofile.gym_id != user.userprofile.gym_id or user.has_perm('gym.manage_gym') or user.has_perm('gym.gym_trainer') or user.has_perm('gym.manage_gyms') ): return HttpResponseForbidden() else: user = request.user form = PasswordConfirmationForm(user=request.user) if request.method == 'POST': form = PasswordConfirmationForm(data=request.POST, user=request.user) if form.is_valid(): user.delete() messages.success( request, _('Account "{0}" was successfully deleted').format(user.username) ) if not user_pk: django_logout(request) return HttpResponseRedirect(reverse('software:features')) else: gym_pk = request.user.userprofile.gym_id return HttpResponseRedirect(reverse('gym:gym:user-list', kwargs={'pk': gym_pk})) form.helper.form_action = request.path context = {'form': form, 'user_delete': user} return render(request, 'user/delete_account.html', context) @login_required() def trainer_login(request, user_pk): """ Allows a trainer to 'log in' as the selected user """ user = get_object_or_404(User, pk=user_pk) orig_user_pk = request.user.pk # No changing if identity is not set if not request.user.has_perm('gym.gym_trainer') and not request.session.get('trainer.identity'): return HttpResponseForbidden() # Changing between trainers or managers is not allowed if request.user.has_perm('gym.gym_trainer') and ( user.has_perm('gym.gym_trainer') or user.has_perm('gym.manage_gym') or user.has_perm('gym.manage_gyms') ): return HttpResponseForbidden() # Changing is only allowed between the same gym if request.user.userprofile.gym != user.userprofile.gym: return HttpResponseNotFound( f'There are no users in gym "{request.user.userprofile.gym}" with user ID "{user_pk}".' ) # Check if we're switching back to our original account own = False if ( user.has_perm('gym.gym_trainer') or user.has_perm('gym.manage_gym') or user.has_perm('gym.manage_gyms') ): own = True # Note: when logging without authenticating, it is necessary to set the # authentication backend if own: del request.session['trainer.identity'] django_login(request, user, 'django.contrib.auth.backends.ModelBackend') if not own: request.session['trainer.identity'] = orig_user_pk if request.GET.get('next'): return HttpResponseRedirect(request.GET['next']) else: return HttpResponseRedirect(reverse('core:index')) else: return HttpResponseRedirect( reverse('gym:gym:user-list', kwargs={'pk': user.userprofile.gym_id}) ) def logout(request): """ Logout the user. For temporary users, delete them. """ user = request.user django_logout(request) if user.is_authenticated and user.userprofile.is_temporary: user.delete() return HttpResponseRedirect(reverse('core:user:login')) def registration(request): """ A form to allow for registration of new users """ # If global user registration is deactivated, redirect if not settings.WGER_SETTINGS['ALLOW_REGISTRATION']: return HttpResponseRedirect(reverse('software:features')) template_data = {} template_data.update(csrf(request)) # Don't show captcha if the global parameter is false FormClass = ( RegistrationForm if settings.WGER_SETTINGS['USE_RECAPTCHA'] else RegistrationFormNoCaptcha ) # Redirect regular users, in case they reached the registration page if request.user.is_authenticated and not request.user.userprofile.is_temporary: return HttpResponseRedirect(reverse('core:dashboard')) if request.method == 'POST': form = FormClass(data=request.POST) # If the data is valid, log in and redirect if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] email = form.cleaned_data['email'] user = User.objects.create_user(username, email, password) user.save() # Pre-set some values of the user's profile language = load_language(translation.get_language()) user.userprofile.notification_language = language # Set default gym, if needed gym_config = GymConfig.objects.get(pk=1) if gym_config.default_gym: user.userprofile.gym = gym_config.default_gym # Create gym user configuration object config = GymUserConfig() config.gym = gym_config.default_gym config.user = user config.save() user.userprofile.save() user = authenticate(request=request, username=username, password=password) # Log the user in django_login(request, user) # Email the user with the activation link send_email(user) # Redirect to the dashboard messages.success(request, _('You were successfully registered')) return HttpResponseRedirect(reverse('core:dashboard')) else: form = FormClass() template_data['form'] = form template_data['title'] = _('Register') return render(request, 'form.html', template_data) @login_required def preferences(request): """ An overview of all user preferences """ context = {} context.update(csrf(request)) redirect = False # Process the preferences form if request.method == 'POST': form = UserPreferencesForm(data=request.POST, instance=request.user.userprofile) form.user = request.user # Save the data if it validates if form.is_valid(): form.save() redirect = True else: data = { 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'email': request.user.email, } form = UserPreferencesForm(initial=data, instance=request.user.userprofile) # Process the email form if request.method == 'POST': user_email = request.user.email email_form = UserPersonalInformationForm(data=request.POST, instance=request.user) if email_form.is_valid() and redirect: # If the user changes the email, it is no longer verified if user_email != email_form.instance.email: logger.debug('resetting verified flag') request.user.userprofile.email_verified = False request.user.userprofile.save() # Save as normal email_form.save() redirect = True else: redirect = False context['form'] = form if redirect: messages.success(request, _('Settings successfully updated')) return HttpResponseRedirect(reverse('core:user:preferences')) else: return render(request, 'user/preferences.html', context) class UserDeactivateView( LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, RedirectView, ): """ Deactivates a user """ permanent = False model = User permission_required = ('gym.manage_gym', 'gym.manage_gyms', 'gym.gym_trainer') def dispatch(self, request, *args, **kwargs): """ Only managers and trainers for this gym can access the members """ edit_user = get_object_or_404(User, pk=self.kwargs['pk']) if not request.user.is_authenticated: return HttpResponseForbidden() if ( request.user.has_perm('gym.manage_gym') or request.user.has_perm('gym.gym_trainer') ) and edit_user.userprofile.gym_id != request.user.userprofile.gym_id: return HttpResponseForbidden() return super(UserDeactivateView, self).dispatch(request, *args, **kwargs) def get_redirect_url(self, pk): edit_user = get_object_or_404(User, pk=pk) edit_user.is_active = False edit_user.save() messages.success(self.request, _('The user was successfully deactivated')) return reverse('core:user:overview', kwargs=({'pk': pk})) class UserActivateView( LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, RedirectView, ): """ Activates a previously deactivated user """ permanent = False model = User permission_required = ('gym.manage_gym', 'gym.manage_gyms', 'gym.gym_trainer') def dispatch(self, request, *args, **kwargs): """ Only managers and trainers for this gym can access the members """ edit_user = get_object_or_404(User, pk=self.kwargs['pk']) if not request.user.is_authenticated: return HttpResponseForbidden() if ( request.user.has_perm('gym.manage_gym') or request.user.has_perm('gym.gym_trainer') ) and edit_user.userprofile.gym_id != request.user.userprofile.gym_id: return HttpResponseForbidden() return super(UserActivateView, self).dispatch(request, *args, **kwargs) def get_redirect_url(self, pk): edit_user = get_object_or_404(User, pk=pk) edit_user.is_active = True edit_user.save() messages.success(self.request, _('The user was successfully activated')) return reverse('core:user:overview', kwargs=({'pk': pk})) class UserEditView( WgerFormMixin, LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, UpdateView, ): """ View to update the personal information of an user by an admin """ model = User title = gettext_lazy('Edit user') permission_required = ('gym.manage_gym', 'gym.manage_gyms') form_class = UserPersonalInformationForm def dispatch(self, request, *args, **kwargs): """ Check permissions - Managers can edit members of their own gym - General managers can edit every member """ user = request.user if not user.is_authenticated: return HttpResponseForbidden() if ( user.has_perm('gym.manage_gym') and not user.has_perm('gym.manage_gyms') and user.userprofile.gym != self.get_object().userprofile.gym ): return HttpResponseForbidden() return super(UserEditView, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('core:user:overview', kwargs={'pk': self.kwargs['pk']}) def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(UserEditView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}'.format(self.object)) return context @login_required def api_key(request): """ Allows the user to generate an API key for the REST API """ context = {} context.update(csrf(request)) try: token = Token.objects.get(user=request.user) except Token.DoesNotExist: token = None if request.GET.get('new_key'): token = create_token(request.user, request.GET.get('new_key')) # Redirect to get rid of the GET parameter return HttpResponseRedirect(reverse('core:user:api-key')) context['token'] = token return render(request, 'user/api_key.html', context) class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, DetailView): """ User overview for gyms """ model = User permission_required = ('gym.manage_gym', 'gym.manage_gyms', 'gym.gym_trainer') template_name = 'user/overview.html' context_object_name = 'current_user' def dispatch(self, request, *args, **kwargs): """ Check permissions - Only managers for this gym can access the members - General managers can access the detail page of all users """ user = request.user if not user.is_authenticated: return HttpResponseForbidden() if ( (user.has_perm('gym.manage_gym') or user.has_perm('gym.gym_trainer')) and not user.has_perm('gym.manage_gyms') and user.userprofile.gym != self.get_object().userprofile.gym ): return HttpResponseForbidden() return super(UserDetailView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(UserDetailView, self).get_context_data(**kwargs) out = [] workouts = Workout.objects.filter(user=self.object).all() for workout in workouts: logs = WorkoutLog.objects.filter(workout=workout) out.append( { 'workout': workout, 'logs': logs.dates('date', 'day').count(), 'last_log': logs.last(), } ) context['workouts'] = out context['weight_entries'] = WeightEntry.objects.filter(user=self.object).order_by('-date')[ :5 ] context['nutrition_plans'] = NutritionPlan.objects.filter(user=self.object).order_by( '-creation_date' )[:5] context['session'] = WorkoutSession.objects.filter(user=self.object).order_by('-date')[:10] context['admin_notes'] = AdminUserNote.objects.filter(member=self.object)[:5] context['contracts'] = Contract.objects.filter(member=self.object)[:5] page_user = self.object # type: User request_user = self.request.user # type: User same_gym_id = request_user.userprofile.gym_id == page_user.userprofile.gym_id context['enable_login_button'] = request_user.has_perm('gym.gym_trainer') and same_gym_id context['gym_name'] = None # request_user.userprofile.gym.name return context class UserListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): """ Overview of all users in the instance """ model = User permission_required = ('gym.manage_gyms',) template_name = 'user/list.html' def get_queryset(self): """ Return a list with the users, not really a queryset. """ out = {'admins': [], 'members': []} for u in User.objects.select_related('usercache', 'userprofile__gym').all(): out['members'].append({'obj': u, 'last_log': None}) # u.usercache.last_activity return out def get_context_data(self, **kwargs): """ Pass other info to the template """ context = super(UserListView, self).get_context_data(**kwargs) context['show_gym'] = True context['user_table'] = { 'keys': [ _('ID'), _('Username'), _('Name'), _('Last activity'), _('Gym'), ], 'users': context['object_list']['members'], } return context class WgerPasswordChangeView(PasswordChangeView): template_name = 'form.html' success_url = reverse_lazy('core:user:preferences') title = gettext_lazy('Change password') def get_form(self, form_class=None): form = super(WgerPasswordChangeView, self).get_form(form_class) form.helper = FormHelper() form.helper.form_class = 'wger-form' form.helper.layout = Layout( 'old_password', Row( Column('new_password1', css_class='col-6'), Column('new_password2', css_class='col-6'), css_class='form-row', ), ButtonHolder(Submit('submit', _('Save'), css_class='btn-success btn-block')), ) return form class WgerPasswordResetView(PasswordResetView): template_name = 'form.html' email_template_name = 'registration/password_reset_email.html' success_url = reverse_lazy('core:user:password_reset_done') from_email = settings.WGER_SETTINGS['EMAIL_FROM'] def get_form(self, form_class=None): form = super(WgerPasswordResetView, self).get_form(form_class) form.helper = FormHelper() form.helper.form_class = 'wger-form' form.helper.add_input(Submit('submit', _('Save'), css_class='btn-success btn-block')) return form class WgerPasswordResetConfirmView(PasswordResetConfirmView): template_name = 'form.html' success_url = reverse_lazy('core:user:login') def get_form(self, form_class=None): form = super(WgerPasswordResetConfirmView, self).get_form(form_class) form.helper = FormHelper() form.helper.form_class = 'wger-form' form.helper.add_input(Submit('submit', _('Save'), css_class='btn-success btn-block')) return form @login_required def confirm_email(request): if not request.user.userprofile.email_verified: send_email(request.user) messages.success( request, _('A verification email was sent to %(email)s') % {'email': request.user.email} ) return HttpResponseRedirect(reverse('core:dashboard'))
21,138
Python
.py
543
31.416206
100
0.654164
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,787
languages.py
wger-project_wger/wger/core/views/languages.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.urls import reverse_lazy from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, DetailView, ListView, UpdateView, ) # wger from wger.core.models import Language from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) logger = logging.getLogger(__name__) class LanguageListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): """ Show an overview of all languages """ model = Language template_name = 'language/overview.html' context_object_name = 'language_list' permission_required = 'core.change_language' class LanguageDetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Language template_name = 'language/view.html' context_object_name = 'view_language' permission_required = 'core.change_language' class LanguageCreateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView): """ Generic view to add a new language """ model = Language fields = ['short_name', 'full_name', 'full_name_en'] title = gettext_lazy('Add') permission_required = 'core.add_language' class LanguageDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView): """ Generic view to delete an existing language """ model = Language success_url = reverse_lazy('core:language:overview') messages = gettext_lazy('Successfully deleted') permission_required = 'core.delete_language' def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(LanguageDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object.full_name) return context class LanguageEditView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView): """ Generic view to update an existing language """ model = Language fields = ['short_name', 'full_name', 'full_name_en'] permission_required = 'core.change_language' def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(LanguageEditView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object.full_name) return context
3,256
Python
.py
90
31.911111
99
0.729644
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,788
repetition_units.py
wger-project_wger/wger/core/views/repetition_units.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_lazy from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, ListView, UpdateView, ) # wger from wger.core.models import RepetitionUnit from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) logger = logging.getLogger(__name__) class ListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): """ Overview of all available setting units """ model = RepetitionUnit permission_required = 'core.add_repetitionunit' template_name = 'repetition_unit/list.html' class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView): """ View to add a new setting unit """ model = RepetitionUnit fields = ['name'] title = gettext_lazy('Add') success_url = reverse_lazy('core:repetition-unit:list') permission_required = 'core.add_repetitionunit' class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView): """ View to update an existing setting unit """ model = RepetitionUnit fields = ['name'] success_url = reverse_lazy('core:repetition-unit:list') permission_required = 'core.change_repetitionunit' 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 setting unit """ model = RepetitionUnit success_url = reverse_lazy('core:repetition-unit:list') permission_required = 'core.delete_repetitionunit' def dispatch(self, request, *args, **kwargs): """ Deleting the unit with ID 1 (repetitions) is not allowed This is the default and is hard coded in a couple of places """ if self.kwargs['pk'] == '1': 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
3,352
Python
.py
93
31.397849
91
0.716934
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,789
weight_units.py
wger-project_wger/wger/core/views/weight_units.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_lazy from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, ListView, UpdateView, ) # wger from wger.core.models import WeightUnit from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) logger = logging.getLogger(__name__) class ListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): """ Overview of all available weight units """ model = WeightUnit permission_required = 'core.add_weightunit' template_name = 'weight_unit/list.html' class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView): """ View to add a new weight unit """ model = WeightUnit fields = ['name'] title = gettext_lazy('Add') success_url = reverse_lazy('core:weight-unit:list') permission_required = 'core.add_weightunit' class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView): """ View to update an existing weight unit """ model = WeightUnit fields = ['name'] success_url = reverse_lazy('core:weight-unit:list') permission_required = 'core.change_weightunit' 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 weight unit """ model = WeightUnit success_url = reverse_lazy('core:weight-unit:list') permission_required = 'core.delete_weightunit' def dispatch(self, request, *args, **kwargs): """ Deleting the unit with ID 1 (repetitions) is not allowed This is the default and is hard coded in a couple of places """ if self.kwargs['pk'] == '1': 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
3,296
Python
.py
93
30.795699
91
0.71195
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,790
misc.py
wger-project_wger/wger/core/views/misc.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.conf import settings from django.contrib import messages from django.contrib.auth import login as django_login from django.contrib.auth.decorators import login_required from django.core import mail from django.http import HttpResponseRedirect from django.shortcuts import render from django.template.loader import render_to_string from django.urls import ( reverse, reverse_lazy, ) from django.utils.text import slugify from django.utils.translation import gettext as _ from django.views.generic.edit import FormView # Third Party from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit # wger from wger.core.demo import ( create_demo_entries, create_temporary_user, ) from wger.core.forms import ( FeedbackAnonymousForm, FeedbackRegisteredForm, ) from wger.core.models import DaysOfWeek from wger.manager.models import Schedule logger = logging.getLogger(__name__) # ************************ # Misc functions # ************************ def index(request): """ Index page """ if request.user.is_authenticated: return HttpResponseRedirect(reverse('core:dashboard')) else: return HttpResponseRedirect(reverse('software:features')) def demo_entries(request): """ Creates a set of sample entries for guest users """ if not settings.WGER_SETTINGS['ALLOW_GUEST_USERS']: return HttpResponseRedirect(reverse('software:features')) if ( not request.user.is_authenticated or request.user.userprofile.is_temporary ) and not request.session['has_demo_data']: # If we reach this from a page that has no user created by the # middleware, do that now if not request.user.is_authenticated: user = create_temporary_user(request) django_login(request, user) # OK, continue create_demo_entries(request.user) request.session['has_demo_data'] = True messages.success( request, _( 'We have created sample workout, workout schedules, weight ' 'logs, (body) weight and nutrition plan entries so you can ' 'better see what this site can do. Feel free to edit or ' 'delete them!' ), ) return HttpResponseRedirect(reverse('core:dashboard')) @login_required def dashboard(request): """ Show the index page, in our case, the last workout and nutritional plan and the current weight """ return render(request, 'index.html') class FeedbackClass(FormView): template_name = 'form.html' success_url = reverse_lazy('software:about-us') def get_initial(self): """ Fill in the contact, if available """ if self.request.user.is_authenticated: return {'contact': self.request.user.email} return {} def get_context_data(self, **kwargs): """ Set necessary template data to correctly render the form """ context = super(FeedbackClass, self).get_context_data(**kwargs) context['title'] = _('Feedback') return context def get_form_class(self): """ Load the correct feedback form depending on the user (either with reCaptcha field or not) """ if self.request.user.is_anonymous or self.request.user.userprofile.is_temporary: return FeedbackAnonymousForm else: return FeedbackRegisteredForm def get_form(self, form_class=None): """Return an instance of the form to be used in this view.""" form = super(FeedbackClass, self).get_form(form_class) form.helper = FormHelper() form.helper.form_id = slugify(self.request.path) form.helper.add_input(Submit('submit', _('Submit'), css_class='btn-success btn-block')) form.helper.form_class = 'wger-form' return form def form_valid(self, form): """ Send the feedback to the administrators """ messages.success(self.request, _('Your feedback was successfully sent. Thank you!')) context = {'user': self.request.user, 'form_data': form.cleaned_data} subject = 'New feedback' message = render_to_string('user/email_feedback.html', context) mail.mail_admins(subject, message) return super(FeedbackClass, self).form_valid(form)
5,126
Python
.py
136
31.801471
95
0.686405
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,791
serializers.py
wger-project_wger/wger/core/api/serializers.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 # Django from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.http import HttpRequest # Third Party from rest_framework import serializers from rest_framework.fields import empty from rest_framework.validators import UniqueValidator # wger from wger.core.models import ( DaysOfWeek, Language, License, RepetitionUnit, UserProfile, WeightUnit, ) logger = logging.getLogger(__name__) class UserprofileSerializer(serializers.ModelSerializer): """ Workout session serializer """ email = serializers.EmailField(source='user.email', read_only=True) username = serializers.EmailField(source='user.username', read_only=True) date_joined = serializers.EmailField(source='user.date_joined', read_only=True) class Meta: model = UserProfile fields = [ 'username', 'email', 'email_verified', 'is_trustworthy', 'date_joined', 'gym', 'is_temporary', 'show_comments', 'show_english_ingredients', 'workout_reminder_active', 'workout_reminder', 'workout_duration', 'last_workout_notification', 'notification_language', 'age', 'birthdate', 'height', 'gender', 'sleep_hours', 'work_hours', 'work_intensity', 'sport_hours', 'sport_intensity', 'freetime_hours', 'freetime_intensity', 'calories', 'weight_unit', 'ro_access', 'num_days_weight_reminder', ] class UserLoginSerializer(serializers.ModelSerializer): """Serializer to map to User model in relation to api user""" email = serializers.CharField(required=False) username = serializers.CharField(required=False) password = serializers.CharField(required=True, min_length=8) request: HttpRequest class Meta: model = User fields = ['username', 'password', 'email'] def __init__(self, request: HttpRequest = None, instance=None, data=empty, **kwargs): self.request = request super().__init__(instance, data, **kwargs) def validate(self, data): email = data.get('email', None) username = data.get('username', None) password = data.get('password', None) if email is None and username is None: raise serializers.ValidationError('Please provide an "email" or a "username"') user_username = authenticate(request=self.request, username=username, password=password) user_email = authenticate(request=self.request, username=email, password=password) user = user_username or user_email if user is None: logger.info(f"Tried logging via API with unknown user: '{username}'") raise serializers.ValidationError('Username or password unknown') return data class UserRegistrationSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=False, validators=[ UniqueValidator(queryset=User.objects.all()), ], ) username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all())], ) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) class Meta: model = User fields = ('username', 'email', 'password') def create(self, validated_data): user = User.objects.create(username=validated_data['username']) user.set_password(validated_data['password']) if validated_data.get('email'): user.email = validated_data['email'] user.save() return user class LanguageSerializer(serializers.ModelSerializer): """ Language serializer """ class Meta: model = Language fields = [ 'id', 'short_name', 'full_name', 'full_name_en', ] class DaysOfWeekSerializer(serializers.ModelSerializer): """ DaysOfWeek serializer """ class Meta: model = DaysOfWeek fields = ['day_of_week'] class LicenseSerializer(serializers.ModelSerializer): """ License serializer """ class Meta: model = License fields = [ 'id', 'full_name', 'short_name', 'url', ] class RepetitionUnitSerializer(serializers.ModelSerializer): """ Repetition unit serializer """ class Meta: model = RepetitionUnit fields = ['id', 'name'] class RoutineWeightUnitSerializer(serializers.ModelSerializer): """ Weight unit serializer """ class Meta: model = WeightUnit fields = ['id', 'name']
5,766
Python
.py
167
27.197605
100
0.650054
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,792
permissions.py
wger-project_wger/wger/core/api/permissions.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/>. # Third Party from rest_framework.permissions import BasePermission class AllowRegisterUser(BasePermission): """ Checks that users are allow to register via API. Apps can register user via the REST API, but only if they have been whitelisted first """ def has_permission(self, request, view): if request.user.is_anonymous: return False return request.user.userprofile.can_add_user
1,149
Python
.py
25
42.8
89
0.764758
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,793
views.py
wger-project_wger/wger/core/api/views.py
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. # Standard Library import logging # Django from django.conf import settings from django.contrib.auth.models import User from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page # Third Party from django_email_verification import send_email from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import ( OpenApiParameter, OpenApiResponse, extend_schema, inline_serializer, ) from rest_framework import ( status, viewsets, ) from rest_framework.decorators import action from rest_framework.fields import ( BooleanField, CharField, ) from rest_framework.permissions import ( AllowAny, IsAuthenticated, ) from rest_framework.response import Response # wger from wger import ( MIN_APP_VERSION, get_version, ) from wger.core.api.permissions import AllowRegisterUser from wger.core.api.serializers import ( DaysOfWeekSerializer, LanguageSerializer, LicenseSerializer, RepetitionUnitSerializer, RoutineWeightUnitSerializer, UserLoginSerializer, UserprofileSerializer, UserRegistrationSerializer, ) from wger.core.forms import UserLoginForm from wger.core.models import ( DaysOfWeek, Language, License, RepetitionUnit, UserProfile, WeightUnit, ) from wger.utils.api_token import create_token from wger.utils.permissions import WgerPermission logger = logging.getLogger(__name__) class UserProfileViewSet(viewsets.ModelViewSet): """ API endpoint for the user profile This endpoint works somewhat differently than the others since it always returns the data for the currently logged-in user's profile. To update the profile, use a POST request with the new data, not a PATCH. """ serializer_class = UserprofileSerializer permission_classes = ( IsAuthenticated, WgerPermission, ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return UserProfile.objects.none() return UserProfile.objects.filter(user=self.request.user) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(User, 'user')] def list(self, request, *args, **kwargs): """ Customized list view, that returns only the current user's data """ queryset = self.get_queryset() serializer = self.serializer_class(queryset.first(), many=False) return Response(serializer.data) def retrieve(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def create(self, request, *args, **kwargs): data = request.data serializer = self.serializer_class(request.user.userprofile, data=data) if serializer.is_valid(): serializer.save() # New email, update the user and reset the email verification flag if request.user.email != data['email']: request.user.email = data['email'] request.user.save() request.user.userprofile.email_verified = False request.user.userprofile.save() logger.debug('resetting verified flag') return Response(serializer.data) def update(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def partial_update(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) @action(detail=False, url_name='verify-email', url_path='verify-email') def verify_email(self, request): """ Return the username """ profile = request.user.userprofile if profile.email_verified: return Response({'status': 'verified', 'message': 'This email is already verified'}) send_email(request.user) return Response( {'status': 'sent', 'message': f'A verification email was sent to {request.user.email}'} ) class ApplicationVersionView(viewsets.ViewSet): """ Returns the application's version """ permission_classes = (AllowAny,) @staticmethod @extend_schema( parameters=[], responses={ 200: OpenApiTypes.STR, }, ) def get(request): return Response(get_version()) class PermissionView(viewsets.ViewSet): """ Checks whether the user has a django permission """ permission_classes = (AllowAny,) @staticmethod @extend_schema( parameters=[ OpenApiParameter( 'permission', OpenApiTypes.STR, OpenApiParameter.QUERY, description='The name of the django permission such as "exercises.change_muscle"', ), ], responses={ 201: inline_serializer( name='PermissionResponse', fields={ 'result': BooleanField(), }, ), 400: OpenApiResponse( description="Please pass a permission name in the 'permission' parameter" ), }, ) def get(request): permission = request.query_params.get('permission') if permission is None: return Response( "Please pass a permission name in the 'permission' parameter", status=status.HTTP_400_BAD_REQUEST, ) if request.user.is_anonymous: return Response({'result': False}) return Response({'result': request.user.has_perm(permission)}) class RequiredApplicationVersionView(viewsets.ViewSet): """ Returns the minimum required version of flutter app to access this server such as 1.4.2 or 3.0.0 """ permission_classes = (AllowAny,) @staticmethod @extend_schema( parameters=[], responses={ 200: OpenApiTypes.STR, }, ) def get(request): return Response(get_version(MIN_APP_VERSION, True)) class UserAPILoginView(viewsets.ViewSet): """ API login endpoint. Returns a token that can subsequently passed in the header. Note that it is recommended to use token authorization instead. """ permission_classes = (AllowAny,) queryset = User.objects.all() serializer_class = UserLoginSerializer throttle_scope = 'login' def get(self, request): return Response(data={'message': "You must send a 'username' and 'password' via POST"}) @extend_schema( parameters=[], responses={ status.HTTP_200_OK: inline_serializer( name='loginSerializer', fields={'token': CharField()}, ), }, ) def post(self, request): serializer = self.serializer_class(data=request.data, request=request) serializer.is_valid(raise_exception=True) # This is a bit hacky, but saving the email or username as the username # allows us to simply use the helpers.EmailAuthBackend backend which also # uses emails username = serializer.data.get('username', serializer.data.get('email', None)) data = {'username': username, 'password': serializer.data['password']} form = UserLoginForm(data=data, authenticate_on_clean=False) if not form.is_valid(): logger.info(f"Tried logging via API with unknown user : '{username}'") return Response( {'detail': 'Username or password unknown'}, status=status.HTTP_401_UNAUTHORIZED, ) form.authenticate(request) token = create_token(form.get_user()) return Response( data={'token': token.key}, status=status.HTTP_200_OK, headers={ 'Deprecation': 'Sat, 01 Oct 2022 23:59:59 GMT', }, ) class UserAPIRegistrationViewSet(viewsets.ViewSet): """ API endpoint """ permission_classes = (AllowRegisterUser,) serializer_class = UserRegistrationSerializer def get_queryset(self): """ Only allow access to appropriate objects """ return UserProfile.objects.filter(user=self.request.user) @extend_schema( parameters=[], responses={ status.HTTP_200_OK: inline_serializer( name='loginSerializer', fields={'token': CharField()}, ), }, ) def post(self, request): data = request.data serializer = self.serializer_class(data=data) serializer.is_valid(raise_exception=True) user = serializer.save() user.userprofile.added_by = request.user user.userprofile.save() token = create_token(user) # Email the user with the activation link send_email(user) return Response( {'message': 'api user successfully registered', 'token': token.key}, status=status.HTTP_201_CREATED, ) class LanguageViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for the languages used in the application """ queryset = Language.objects.all() serializer_class = LanguageSerializer ordering_fields = '__all__' filterset_fields = ('full_name', 'short_name') @method_decorator(cache_page(settings.WGER_SETTINGS['EXERCISE_CACHE_TTL'])) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) class DaysOfWeekViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for the days of the week (monday, tuesday, etc.). This has historical reasons, and it's better and easier to just define a simple enum """ queryset = DaysOfWeek.objects.all() serializer_class = DaysOfWeekSerializer ordering_fields = '__all__' filterset_fields = ('day_of_week',) class LicenseViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for license objects """ queryset = License.objects.all() serializer_class = LicenseSerializer ordering_fields = '__all__' filterset_fields = ( 'full_name', 'short_name', 'url', ) class RepetitionUnitViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for repetition units objects """ queryset = RepetitionUnit.objects.all() serializer_class = RepetitionUnitSerializer ordering_fields = '__all__' filterset_fields = ('name',) class RoutineWeightUnitViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for weight units objects """ queryset = WeightUnit.objects.all() serializer_class = RoutineWeightUnitSerializer ordering_fields = '__all__' filterset_fields = ('name',)
11,765
Python
.py
331
28.362538
99
0.658627
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,794
test_apikey.py
wger-project_wger/wger/core/tests/test_apikey.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.contrib.auth.models import User from django.urls import reverse # Third Party from rest_framework.authtoken.models import Token # wger from wger.core.tests.base_testcase import WgerTestCase logger = logging.getLogger(__name__) class ApiKeyTestCase(WgerTestCase): """ Tests the API key page """ def test_api_key_page(self): """ Tests the API key generation page """ self.user_login('test') user = User.objects.get(username='test') # User already has a key response = self.client.get(reverse('core:user:api-key')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Delete current API key and generate new one') self.assertTrue(Token.objects.get(user=user)) # User has no keys Token.objects.get(user=user).delete() response = self.client.get(reverse('core:user:api-key')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'You have no API key yet') self.assertRaises(Token.DoesNotExist, Token.objects.get, user=user) def test_api_key_page_generation(self): """ User generates a new key """ self.user_login('test') user = User.objects.get(username='test') key_before = Token.objects.get(user=user) response = self.client.get(reverse('core:user:api-key'), {'new_key': True}) self.assertEqual(response.status_code, 302) response = self.client.get(response['Location']) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Delete current API key and generate new one') key_after = Token.objects.get(user=user) self.assertTrue(key_after) # New key is different from the one before self.assertNotEqual(key_before.key, key_after.key)
2,573
Python
.py
60
37.133333
84
0.707131
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,795
test_user.py
wger-project_wger/wger/core/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 from unittest import TestCase # Django from django.contrib.auth.models import User from django.http import HttpRequest from django.urls import ( reverse, reverse_lazy, ) # wger from wger.core.demo import create_temporary_user from wger.core.tests.base_testcase import ( WgerAccessTestCase, WgerEditTestCase, WgerTestCase, ) class StatusUserTestCase(WgerTestCase): """ Test activating and deactivating users """ user_success = ( 'general_manager1', 'general_manager2', 'manager1', 'manager2', 'trainer1', 'trainer2', 'trainer3', ) user_fail = ( 'member1', 'member2', 'member3', 'member4', 'manager3', 'trainer4', ) def activate(self, fail=False): """ Helper function to test activating users """ user = User.objects.get(pk=2) user.is_active = False user.save() self.assertFalse(user.is_active) response = self.client.get(reverse('core:user:activate', kwargs={'pk': user.pk})) user = User.objects.get(pk=2) self.assertIn(response.status_code, (302, 403)) if fail: self.assertFalse(user.is_active) else: self.assertTrue(user.is_active) def test_activate_authorized(self): """ Tests activating a user as an administrator """ for username in self.user_success: self.user_login(username) self.activate() self.user_logout() def test_activate_unauthorized(self): """ Tests activating a user as another logged in user """ for username in self.user_fail: self.user_login(username) self.activate(fail=True) self.user_logout() def test_activate_logged_out(self): """ Tests activating a user a logged out user """ self.activate(fail=True) def deactivate(self, fail=False): """ Helper function to test deactivating users """ user = User.objects.get(pk=2) user.is_active = True user.save() self.assertTrue(user.is_active) response = self.client.get(reverse('core:user:deactivate', kwargs={'pk': user.pk})) user = User.objects.get(pk=2) self.assertIn(response.status_code, (302, 403)) if fail: self.assertTrue(user.is_active) else: self.assertFalse(user.is_active) def test_deactivate_authorized(self): """ Tests deactivating a user as an administrator """ for username in self.user_success: self.user_login(username) self.deactivate() self.user_logout() def test_deactivate_unauthorized(self): """ Tests deactivating a user as another logged in user """ for username in self.user_fail: self.user_login(username) self.deactivate(fail=True) self.user_logout() def test_deactivate_logged_out(self): """ Tests deactivating a user a logged out user """ self.deactivate(fail=True) class EditUserTestCase(WgerEditTestCase): """ Test editing a user """ object_class = User url = 'core:user:edit' pk = 2 data = { 'email': 'another.email@example.com', 'first_name': 'Name', 'last_name': 'Last name', } user_success = ( 'admin', 'general_manager1', 'general_manager2', 'manager1', 'manager2', ) user_fail = ( 'member1', 'member2', 'manager3', 'trainer2', 'trainer3', 'trainer4', ) class EditUserTestCase2(WgerEditTestCase): """ Test editing a user """ object_class = User url = 'core:user:edit' pk = 19 data = { 'email': 'another.email@example.com', 'first_name': 'Name', 'last_name': 'Last name', } user_success = ( 'admin', 'general_manager1', 'general_manager2', 'manager3', ) user_fail = ( 'member1', 'member2', 'trainer2', 'trainer3', 'trainer4', ) class UserListTestCase(WgerAccessTestCase): """ Test accessing the general user overview """ url = 'core:user:list' user_success = ( 'admin', 'general_manager1', 'general_manager2', ) user_fail = ( 'member1', 'member2', 'manager1', 'manager2', 'manager3', 'trainer2', 'trainer3', 'trainer4', ) class UserDetailPageTestCase(WgerAccessTestCase): """ Test accessing the user detail page """ url = reverse_lazy('core:user:overview', kwargs={'pk': 2}) user_success = ( 'trainer1', 'trainer2', 'manager1', 'general_manager1', 'general_manager2', ) user_fail = ( 'trainer4', 'trainer5', 'manager3', 'member1', 'member2', ) class UserDetailPageTestCase2(WgerAccessTestCase): """ Test accessing the user detail page """ url = reverse_lazy('core:user:overview', kwargs={'pk': 19}) user_success = ( 'trainer4', 'trainer5', 'manager3', 'general_manager1', 'general_manager2', ) user_fail = ( 'trainer1', 'trainer2', 'manager1', 'member1', 'member2', ) class UserTrustworthinessTestCase(WgerTestCase): request = HttpRequest() def test_temporary_user_no_permissions(self): """ Tests that temporary users do not pass the "is trustworthy" check and do not have any permissions. """ # Get a temporary user user = create_temporary_user(self.request) # User does not pass trustworthiness check self.assertFalse(user.userprofile.is_trustworthy) def test_is_trustworthy_new(self): """ Tests that new accounts are not considered trustworthy """ # Get a temporary user user = create_temporary_user(self.request) user.userprofile.is_temporary = False user.userprofile.email_verified = True user.date_joined = datetime.datetime.now() # User does not pass trustworthiness check self.assertFalse(user.userprofile.is_trustworthy) def test_is_trustworthy_old_no_email(self): """ Tests that users without verified email are not considered trustworthy """ # Get a temporary user user = create_temporary_user(self.request) user.userprofile.is_temporary = False user.userprofile.email_verified = False user.date_joined = datetime.datetime.now() - datetime.timedelta(days=30) # User does not pass trustworthiness check self.assertFalse(user.userprofile.is_trustworthy) def test_is_trustworthy_old_email(self): """ Tests that old accounts are not considered trustworthy """ # Get a temporary user user = create_temporary_user(self.request) user.userprofile.is_temporary = False user.userprofile.email_verified = True user.date_joined = datetime.datetime.now() - datetime.timedelta(days=30) # User does not pass trustworthiness check self.assertTrue(user.userprofile.is_trustworthy) def test_is_trustworthy_admin(self): """ Tests that superusers are always trustworthy """ # Get a temporary user user = create_temporary_user(self.request) user.is_superuser = True user.userprofile.is_temporary = False user.userprofile.email_verified = False user.date_joined = datetime.datetime.now() # User does not pass trustworthiness check self.assertTrue(user.userprofile.is_trustworthy)
8,717
Python
.py
289
22.678201
91
0.613392
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,796
test_delete_user.py
wger-project_wger/wger/core/tests/test_delete_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 logging # Django from django.contrib.auth.models import User from django.urls import reverse # wger from wger.core.tests.base_testcase import WgerTestCase logger = logging.getLogger(__name__) class DeleteUserTestCase(WgerTestCase): """ Tests deleting the user account and all his data """ def delete_user(self, fail=False): """ Helper function """ response = self.client.get(reverse('core:user:delete')) self.assertEqual(User.objects.filter(username='test').count(), 1) if fail: self.assertEqual(response.status_code, 302) else: self.assertEqual(response.status_code, 200) # Wrong user password if not fail: response = self.client.post( reverse('core:user:delete'), {'password': 'not the user password'}, ) self.assertEqual(response.status_code, 200) self.assertEqual(User.objects.filter(username='test').count(), 1) # Correct user password response = self.client.post(reverse('core:user:delete'), {'password': 'testtest'}) self.assertEqual(response.status_code, 302) if fail: self.assertEqual(User.objects.filter(username='test').count(), 1) else: self.assertEqual(User.objects.filter(username='test').count(), 0) def test_delete_user_logged_in(self): """ Tests deleting the own account as a logged in user """ self.user_login('test') self.delete_user(fail=False) def test_delete_user_anonymous(self): """ Tests deleting the own account as an anonymous user """ self.delete_user(fail=True) class DeleteUserByAdminTestCase(WgerTestCase): """ Tests deleting a user account by a gym administrator """ def delete_user(self, fail=False): """ Helper function """ response = self.client.get(reverse('core:user:delete', kwargs={'user_pk': 2})) self.assertEqual(User.objects.filter(username='test').count(), 1) if fail: self.assertIn( response.status_code, (302, 403), f'Unexpected status code for user {self.current_user}', ) else: self.assertEqual( response.status_code, 200, f'Unexpected status code for user {self.current_user}' ) # Wrong admin password if not fail: response = self.client.post( reverse('core:user:delete', kwargs={'user_pk': 2}), {'password': 'blargh'} ) self.assertEqual(response.status_code, 200) self.assertEqual(User.objects.filter(username='test').count(), 1) # Correct user password response = self.client.post( reverse('core:user:delete', kwargs={'user_pk': 2}), {'password': self.current_password} ) if fail: self.assertIn(response.status_code, (302, 403)) self.assertEqual(User.objects.filter(username='test').count(), 1) else: self.assertEqual(response.status_code, 302) self.assertEqual(User.objects.filter(username='test').count(), 0) def test_delete_user_manager(self): """ Tests deleting the user account as a gym manager """ self.user_login('manager1') self.delete_user(fail=False) def test_delete_user_manager2(self): """ Tests deleting the user account as a gym manager """ self.user_login('manager2') self.delete_user(fail=False) def test_delete_user_general_manager(self): """ Tests deleting the user account as a general manager """ self.user_login('general_manager1') self.delete_user(fail=False) def test_delete_user_general_manager2(self): """ Tests deleting the user account as a general manager """ self.user_login('general_manager2') self.delete_user(fail=False) def test_delete_user(self): """ Tests deleting the user account as a regular user """ self.user_login('test') self.delete_user(fail=True) def test_delete_user_trainer(self): """ Tests deleting the user account as a gym trainer """ self.user_login('trainer1') self.delete_user(fail=True) def test_delete_user_trainer2(self): """ Tests deleting the user account as a gym trainer """ self.user_login('trainer4') self.delete_user(fail=True) def test_delete_user_trainer_other(self): """ Tests deleting the user account as a gym trainer of another gym """ self.user_login('trainer4') self.delete_user(fail=True) def test_delete_user_manager_other(self): """ Tests deleting the user account as a gym manager of another gym """ self.user_login('manager3') self.delete_user(fail=True) def test_delete_user_member(self): """ Tests deleting the user account as a gym member """ self.user_login('member1') self.delete_user(fail=True) def test_delete_user_member2(self): """ Tests deleting the user account as a gym member """ self.user_login('member4') self.delete_user(fail=True) def test_delete_user_anonymous(self): """ Tests deleting the user account as an anonymous user """ self.delete_user(fail=True)
6,314
Python
.py
169
28.970414
99
0.623937
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,797
test_user_login.py
wger-project_wger/wger/core/tests/test_user_login.py
# Standard Library from unittest import mock # Third Party from rest_framework import status from rest_framework.exceptions import ErrorDetail # wger from wger.core.tests.api_base_test import ApiBaseTestCase from wger.core.tests.base_testcase import ( BaseTestCase, WgerTestCase, ) from wger.core.views.user import trainer_login def _build_mock_request(user): request = mock.Mock() request.session = dict() request.GET = dict() request.user = user return request def _build_mock_user(gym_name, is_trainer=False): user = mock.Mock() user.userprofile.gym = gym_name def request_has_perm(perm): if perm in ['gym.gym_trainer', 'gym.manage_gym', 'gym.manage_gyms']: return is_trainer return True # Don't care about other permissions for these tests user.has_perm.side_effect = request_has_perm return user @mock.patch('wger.core.views.user.django_login') class TrainerLoginTestCase(WgerTestCase): def test_trainer_is_allowed_to_login_to_non_trainer_in_same_gym(self, _): request_user = _build_mock_user('same-gym', is_trainer=True) request = _build_mock_request(request_user) user_from_db_lookup = _build_mock_user('same-gym', is_trainer=False) with mock.patch('wger.core.views.user.get_object_or_404', return_value=user_from_db_lookup): resp = trainer_login(request, 'primary-key-not-needed-because-get-object-is-mocked') self.assertEqual(302, resp.status_code) def test_trainer_is_denied_from_login_to_trainer_in_same_gym(self, _): request_user = _build_mock_user('same-gym', is_trainer=True) request = _build_mock_request(request_user) user_from_db_lookup = _build_mock_user('same-gym', is_trainer=True) with mock.patch('wger.core.views.user.get_object_or_404', return_value=user_from_db_lookup): resp = trainer_login(request, 'primary-key-not-needed-because-of-mock') self.assertEqual(403, resp.status_code) def test_trainer_is_denied_from_login_to_trainer_at_different_gym(self, _): request_user = _build_mock_user('trainer-gym', is_trainer=True) request = _build_mock_request(request_user) user_from_db_lookup = _build_mock_user('other-trainer-gym', is_trainer=True) with mock.patch('wger.core.views.user.get_object_or_404', return_value=user_from_db_lookup): resp = trainer_login(request, 'primary-key-not-needed-because-of-mock') self.assertEqual(403, resp.status_code) def test_trainer_gets_404_when_trying_to_login_to_non_trainer_in_different_gym(self, _): request_user = _build_mock_user('trainer-gym', is_trainer=True) request = _build_mock_request(request_user) user_from_db_lookup = _build_mock_user('user-gym', is_trainer=False) with mock.patch('wger.core.views.user.get_object_or_404', return_value=user_from_db_lookup): resp = trainer_login(request, 'primary-key-not-needed-because-of-mock') self.assertEqual(404, resp.status_code) class UserApiLoginApiTestCase(BaseTestCase, ApiBaseTestCase): url = '/api/v2/login/' def test_access_logged_out(self): """ Logged-out users are also allowed to use the search """ response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_login_username_success(self): response = self.client.post( self.url, {'username': 'admin', 'password': 'adminadmin'}, ) result = response.data self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(result, {'token': 'apikey-admin'}) def test_login_username_fail(self): response = self.client.post(self.url, {'username': 'admin', 'password': 'adminadmin123'}) result = response.data self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual( result['non_field_errors'], [ErrorDetail(string='Username or password unknown', code='invalid')], ) def test_login_email_success(self): response = self.client.post( self.url, {'email': 'admin@example.com', 'password': 'adminadmin'}, ) result = response.data self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(result, {'token': 'apikey-admin'}) def test_login_email_fail(self): response = self.client.post( self.url, {'email': 'admin@example.com', 'password': 'adminadmin123'} ) result = response.data self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual( result['non_field_errors'], [ErrorDetail(string='Username or password unknown', code='invalid')], ) def test_no_parameters(self): response = self.client.post(self.url, {'foo': 'bar', 'password': 'adminadmin123'}) result = response.data self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual( result['non_field_errors'], [ErrorDetail(string='Please provide an "email" or a "username"', code='invalid')], )
5,307
Python
.py
107
41.663551
100
0.669377
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,798
base_testcase.py
wger-project_wger/wger/core/tests/base_testcase.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 decimal import logging import os import pathlib import shutil import tempfile # Django from django.conf import settings from django.core.cache import cache from django.test import TestCase from django.urls import ( NoReverseMatch, reverse, ) from django.utils.translation import activate # wger from wger.utils.constants import TWOPLACES STATUS_CODES_FAIL = (302, 403, 404) def get_reverse(url, kwargs=None): """ Helper function to get the reverse URL """ if kwargs is None: kwargs = {} try: url = reverse(url, kwargs=kwargs) except NoReverseMatch: # URL needs special care and doesn't need to be reversed here, # everything was already done in the individual test case url = url return str(url) def get_user_list(users): """ Helper function that returns a list with users to test """ if isinstance(users, tuple): return users else: return [users] def delete_testcase_add_methods(cls): """ Helper function that dynamically adds test methods. This is a bit of a hack, but it's the easiest way of making sure that all the setup and teardown work is performed for each test user (and, most importantly for us, that the database is reseted every time). This must be called if the testcase has more than one success user """ for user in get_user_list(cls.user_fail): def test_unauthorized(self): self.user_login(user) self.delete_object(fail=False) setattr(cls, f'test_unauthorized_{user}', test_unauthorized) for user in get_user_list(cls.user_success): def test_authorized(self): self.user_login(user) self.delete_object(fail=False) setattr(cls, f'test_authorized_{user}', test_authorized) class BaseTestCase: """ Base test case. Generic base testcase that is used for both the regular tests and the REST API tests """ media_root = None fixtures = ( 'days_of_week', 'gym_config', 'groups', 'setting_repetition_units', 'setting_weight_units', 'test-languages', 'test-licenses', 'test-gyms', 'test-gymsconfig', 'test-user-data', 'test-gym-adminconfig.json', 'test-gym-userconfig.json', 'test-admin-user-notes', 'test-gym-user-documents', 'test-contracts', 'test-apikeys', 'test-weight-data', 'test-equipment', 'test-categories', 'test-muscles', 'test-exercises', 'test-exercise-images', 'test-weight-units', 'test-ingredients', 'test-nutrition-data', 'test-nutrition-diary', 'test-workout-data', 'test-workout-session', 'test-schedules', 'test-gallery-images', 'test-measurement-categories', 'test-measurements', ) current_user = 'anonymous' current_password = '' def setUp(self): """ Overwrite some of Django's settings here """ # Don't check reCaptcha's entries os.environ['RECAPTCHA_TESTING'] = 'True' # Explicitly set the locale to en, otherwise the CI might make problems activate('en') # Set logging level logging.disable(logging.INFO) # Disable django-axes # https://django-axes.readthedocs.io/en/latest/3_usage.html#authenticating-users settings.AXES_ENABLED = False settings.WGER_SETTINGS['DOWNLOAD_INGREDIENTS_FROM'] = False settings.WGER_SETTINGS['USE_CELERY'] = False def tearDown(self): """ Reset settings """ del os.environ['RECAPTCHA_TESTING'] cache.clear() # Clear MEDIA_ROOT folder if self.media_root: shutil.rmtree(self.media_root) def init_media_root(self): """ Init the media root and copy the used images to it This is error-prone and ugly, but it's probably ok for the time being """ self.media_root = tempfile.mkdtemp() settings.MEDIA_ROOT = self.media_root os.makedirs(self.media_root + '/exercise-images/1/') os.makedirs(self.media_root + '/exercise-images/2/') shutil.copy( 'wger/exercises/tests/protestschwein.jpg', self.media_root + '/exercise-images/1/protestschwein.jpg', ) shutil.copy( 'wger/exercises/tests/wildschwein.jpg', self.media_root + '/exercise-images/1/wildschwein.jpg', ) shutil.copy( 'wger/exercises/tests/wildschwein.jpg', self.media_root + '/exercise-images/2/wildschwein.jpg', ) class WgerTestCase(BaseTestCase, TestCase): """ Testcase to use with the regular website """ user_success = 'admin' """ A list of users to test for success. For convenience, a string can be used as well if there is only one user. """ user_fail = 'test' """ A list of users to test for failure. For convenience, a string can be used as well if there is only one user. """ def user_login(self, user='admin'): """ Login the user, by default as 'admin' """ password = f'{user}{user}' self.client.login(username=user, password=password) self.current_user = user self.current_password = password def user_logout(self): """ Visit the logout page """ self.client.logout() self.current_user = 'anonymous' def compare_fields(self, field, value): current_field_class = field.__class__.__name__ # Standard types, simply compare if current_field_class in ('unicode', 'str', 'int', 'float', 'time', 'date', 'datetime'): self.assertEqual(field, value) # boolean, convert elif current_field_class == 'bool': self.assertEqual(field, bool(value)) # decimal, convert elif current_field_class == 'Decimal': # TODO: use FOURPLACES when routine branch is merged self.assertEqual(field.quantize(TWOPLACES), decimal.Decimal(value).quantize(TWOPLACES)) # Related manager and SortedManyToMany, iterate elif current_field_class in ('ManyRelatedManager', 'SortedRelatedManager'): for j in field.all(): self.assertIn(j.id, value) # Uploaded image or file, compare the filename elif current_field_class in ('ImageFieldFile', 'FieldFile'): # We can only compare the extensions, since the names can be changed # Ideally we would check that the byte length is the same self.assertEqual(pathlib.Path(field.name).suffix, pathlib.Path(value.name).suffix) # Other objects (from foreign keys), check the ID else: self.assertEqual(field.id, value) def post_test_hook(self): """ Hook to add some more specific tests after the basic add or delete operations are finished """ pass class WgerDeleteTestCase(WgerTestCase): """ Tests deleting an object an authorized user, a different one and a logged out one. This assumes the delete action is only triggered with a POST request and GET will only show a confirmation dialog. """ pk = None url = '' object_class = '' def delete_object(self, fail=False): """ Helper function to test deleting an object """ # Only perform the checks on derived classes if self.__class__.__name__ == 'WgerDeleteTestCase': return # Fetch the delete page count_before = self.object_class.objects.count() response = self.client.get(get_reverse(self.url, kwargs={'pk': self.pk})) count_after = self.object_class.objects.count() self.assertEqual(count_before, count_after) if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) else: self.assertEqual(response.status_code, 200) # Try deleting the object response = self.client.post(get_reverse(self.url, kwargs={'pk': self.pk})) count_after = self.object_class.objects.count() if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) self.assertEqual(count_before, count_after) else: self.assertEqual(response.status_code, 302) self.assertEqual(count_before - 1, count_after) self.assertRaises( self.object_class.DoesNotExist, self.object_class.objects.get, pk=self.pk, ) # TODO: the redirection page might not have a language prefix (e.g. /user/login # instead of /en/user/login) so there is an additional redirect # # The page we are redirected to doesn't trigger an error # response = self.client.get(response['Location']) # self.assertEqual(response.status_code, 200) self.post_test_hook() def test_delete_object_anonymous(self): """ Tests deleting the object as an anonymous user """ self.delete_object(fail=True) def test_delete_object_authorized(self): """ Tests deleting the object as the authorized user """ if not isinstance(self.user_success, tuple): self.user_login(self.user_success) self.delete_object(fail=False) def test_delete_object_other(self): """ Tests deleting the object as the unauthorized, logged-in users """ if self.user_fail and not isinstance(self.user_success, tuple): for user in get_user_list(self.user_fail): self.user_login(user) self.delete_object(fail=True) class WgerEditTestCase(WgerTestCase): """ Tests editing an object as an authorized user, a different one and a logged out one. """ object_class = '' url = '' pk = None data = {} data_ignore = () fileupload = None """ If the form requires a file upload, specify the field name and the file path here in a list or tuple: ['fielname', 'path'] """ def edit_object(self, fail=False): """ Helper function to test editing an object """ # Only perform the checks on derived classes if self.__class__.__name__ == 'WgerEditTestCase': return # Fetch the edit page response = self.client.get(get_reverse(self.url, kwargs={'pk': self.pk})) entry_before = self.object_class.objects.get(pk=self.pk) if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) self.assertTemplateUsed('login.html') else: self.assertEqual(response.status_code, 200) # Try to edit the object # Special care if there are any file uploads if self.fileupload: field_name = self.fileupload[0] filepath = self.fileupload[1] with open(filepath, 'rb') as testfile: self.data[field_name] = testfile url = get_reverse(self.url, kwargs={'pk': self.pk}) response = self.client.post(url, self.data) else: response = self.client.post(get_reverse(self.url, kwargs={'pk': self.pk}), self.data) entry_after = self.object_class.objects.get(pk=self.pk) # Check the results if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) self.assertTemplateUsed('login.html') self.assertEqual(entry_before, entry_after) else: self.assertEqual(response.status_code, 302) # Check that the data is correct for i in [j for j in self.data if j not in self.data_ignore]: current_field = getattr(entry_after, i) self.compare_fields(current_field, self.data[i]) # TODO: the redirection page might not have a language prefix (e.g. /user/login # instead of /en/user/login) so there is an additional redirect # # The page we are redirected to doesn't trigger an error # response = self.client.get(response['Location']) # self.assertEqual(response.status_code, 200) self.post_test_hook() def test_edit_object_anonymous(self): """ Tests editing the object as an anonymous user """ self.edit_object(fail=True) def test_edit_object_authorized(self): """ Tests editing the object as the authorized users """ for user in get_user_list(self.user_success): self.user_login(user) self.edit_object(fail=False) def test_edit_object_other(self): """ Tests editing the object as the unauthorized, logged in users """ if self.user_fail: for user in get_user_list(self.user_fail): self.user_login(user) self.edit_object(fail=True) class WgerAddTestCase(WgerTestCase): """ Tests adding an object as an authorized user, a different one and a logged out one. """ object_class = '' url = '' pk_before = None pk_after = None anonymous_fail = True data = {} data_ignore = () fileupload = None """ If the form requires a file upload, specify the field name and the file path here in a list or tuple: ['fielname', 'path'] """ def add_object(self, fail=False): """ Helper function to test adding an object """ # Only perform the checks on derived classes if self.__class__.__name__ == 'WgerAddTestCase': return # Fetch the add page response = self.client.get(get_reverse(self.url)) if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) else: self.assertEqual(response.status_code, 200) # Enter the data count_before = self.object_class.objects.count() self.pk_before = self.object_class.objects.all().order_by('id').last().pk # Special care if there are any file uploads if self.fileupload: field_name = self.fileupload[0] filepath = self.fileupload[1] with open(filepath, 'rb') as testfile: self.data[field_name] = testfile response = self.client.post(get_reverse(self.url), self.data) else: response = self.client.post(get_reverse(self.url), self.data) count_after = self.object_class.objects.count() self.pk_after = self.object_class.objects.all().order_by('id').last().pk if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) self.assertEqual(self.pk_before, self.pk_after) self.assertEqual(count_before, count_after) else: self.assertEqual(response.status_code, 302) self.assertGreater(self.pk_after, self.pk_before) entry = self.object_class.objects.get(pk=self.pk_after) # Check that the data is correct for i in [j for j in self.data if j not in self.data_ignore]: current_field = getattr(entry, i) self.compare_fields(current_field, self.data[i]) self.assertEqual(count_before + 1, count_after) # TODO: the redirection page might not have a language prefix (e.g. /user/login # instead of /en/user/login) so there is an additional redirect # # The page we are redirected to doesn't trigger an error # response = self.client.get(response['Location']) # self.assertEqual(response.status_code, 200) self.post_test_hook() def test_add_object_anonymous(self): """ Tests adding the object as an anonymous user """ if self.user_fail: self.add_object(fail=self.anonymous_fail) def test_add_object_authorized(self): """ Tests adding the object as the authorized users """ for user in get_user_list(self.user_success): self.user_login(user) self.add_object(fail=False) def test_add_object_other(self): """ Tests adding the object as the unauthorized, logged in users """ if self.user_fail: for user in get_user_list(self.user_fail): self.user_login(self.user_fail) self.add_object(fail=True) class WgerAccessTestCase(WgerTestCase): """ Tests accessing a URL per GET as an authorized user, an unauthorized one and a logged out one. """ url = '' anonymous_fail = True def access(self, fail=True): # Only perform the checks on derived classes if self.__class__.__name__ == 'WgerAccessTestCase': return response = self.client.get(get_reverse(self.url)) if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) # TODO: the redirection page might not have a language prefix (e.g. /user/login # instead of /en/user/login) so there is an additional redirect # if response.status_code == 302: # # The page we are redirected to doesn't trigger an error # response = self.client.get(response['Location']) # self.assertEqual(response.status_code, 200) else: self.assertEqual(response.status_code, 200) def test_access_anonymous(self): """ Tests accessing the URL as an anonymous user """ self.user_logout() self.access(fail=self.anonymous_fail) def test_access_authorized(self): """ Tests accessing the URL as the authorized users """ for user in get_user_list(self.user_success): self.user_login(user) self.access(fail=False) def test_access_other(self): """ Tests accessing the URL as the unauthorized, logged in users """ if self.user_fail: for user in get_user_list(self.user_fail): self.user_login(user) self.access(fail=True) self.user_logout()
19,176
Python
.py
491
30.244399
99
0.62022
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,799
test_sitemap.py
wger-project_wger/wger/core/tests/test_sitemap.py
# This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # Django from django.urls import reverse # wger from wger.core.tests.base_testcase import WgerTestCase class SitemapTestCase(WgerTestCase): """ Tests the generated sitemap """ def test_sitemap_index(self): response = self.client.get(reverse('sitemap')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['sitemaps']), 1) def test_sitemap_exercises(self): response = self.client.get( reverse('django.contrib.sitemaps.views.sitemap', kwargs={'section': 'exercises'}) ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['urlset']), 11) # def test_sitemap_ingredients(self): # response = self.client.get( # reverse('django.contrib.sitemaps.views.sitemap', kwargs={'section': 'nutrition'}) # ) # self.assertEqual(response.status_code, 200) # self.assertEqual(len(response.context['urlset']), 14)
1,636
Python
.py
37
40
95
0.721734
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)