Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Move logic from management command to migration.

Roland Geider71f2f4cd576c
diff --git a/wger/exercises/management/commands/migrate_descriptions_to_markdown.py b/wger/exercises/management/commands/migrate_descriptions_to_markdown.py
deleted file mode 100644
index 70d4cbcd7..000000000
--- a/wger/exercises/management/commands/migrate_descriptions_to_markdown.py
+++ /dev/null
@@ -1,99 +0,0 @@
-# This file is part of wger Workout Manager.
-#
-# wger Workout Manager is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# wger Workout Manager is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-
-# Standard Library
-import time
-
-# Django
-from django.core.management.base import BaseCommand
-from django.db.models import Q
-
-# Third Party
-from markdownify import markdownify
-
-# wger
-from wger.exercises.models import Translation
-
-
-class Command(BaseCommand):
- """
- Migrates existing HTML descriptions to Markdown.
- Populates the 'description_source' field using 'markdownify'
- on the existing 'description'.
- """
-
- help = 'Converts HTML descriptions to Markdown source for the new editing system.'
-
- def add_arguments(self, parser):
- parser.add_argument(
- '--dry-run',
- action='store_true',
- dest='dry_run',
- help='Simulate the migration without saving changes.',
- )
- parser.add_argument(
- '--batch-size',
- type=int,
- default=100,
- help='Number of records to process per batch.',
- )
-
- def handle(self, **options):
- dry_run = options['dry_run']
-
- # Filter: Has description, but NO source (to avoid re-migrating).
- translations_to_migrate = Translation.objects.filter(
- Q(description_source__isnull=True) | Q(description_source=''), description__isnull=False
- ).exclude(description='')
-
- total = translations_to_migrate.count()
- self.stdout.write(f'Found {total} translations to migrate.')
-
- count = 0
- errors = 0
-
- for trans in translations_to_migrate:
- try:
- # ATX to ensure # headings instead of underlined headings.
- md_source = markdownify(trans.description, heading_style='ATX')
-
- if dry_run:
- self.stdout.write(
- f'[Dry Run] ID {trans.id}: '
- f'converted length {len(trans.description)} -> {len(md_source)}'
- )
- else:
- trans.description_source = md_source
-
- # save() triggers:
- # description = render_markdown(description_source)
- # To ensure a clean HTML cache.
- trans.save()
-
- count += 1
-
- if count % 100 == 0:
- self.stdout.write(f'Processed {count}/{total}...')
-
- except Exception as e:
- errors += 1
- self.stdout.write(self.style.ERROR(f'Error converting ID {trans.id}: {e}'))
-
- success_msg = f'Successfully migrated {count} descriptions.'
- if dry_run:
- success_msg += ' (Dry Run)'
-
- self.stdout.write(self.style.SUCCESS(success_msg))
- if errors > 0:
- self.stdout.write(self.style.WARNING(f'Finished with {errors} errors.'))
diff --git a/wger/exercises/migrations/0035_add_markdown_description_field.py b/wger/exercises/migrations/0035_add_markdown_description_field.py
new file mode 100644
index 000000000..a72a74313
--- /dev/null
+++ b/wger/exercises/migrations/0035_add_markdown_description_field.py
@@ -0,0 +1,39 @@
+# Generated by Django 5.2.9 on 2025-12-10 00:17
+
+from django.db.backends.base.schema import BaseDatabaseSchemaEditor
+from django.db.migrations.state import StateApps
+from markdownify import markdownify
+
+from django.db import migrations, models
+
+def migrate_description_to_markdown(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor):
+ Translation = apps.get_model('exercises', 'Translation')
+
+ translations_to_migrate = Translation.objects.exclude(description='')
+ for trans in translations_to_migrate:
+ # ATX to ensure # headings instead of underlined headings.
+ trans.description_source = markdownify(trans.description, heading_style='ATX')
+
+ # save() triggers "description = render_markdown(description_source)". This
+ # ensures a clean HTML cache
+ trans.save()
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ('exercises', '0034_add_exercise_image_dimensions'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='historicaltranslation',
+ name='description_source',
+ field=models.TextField(blank=True, null=True, verbose_name='Description (Source)'),
+ ),
+ migrations.AddField(
+ model_name='translation',
+ name='description_source',
+ field=models.TextField(blank=True, null=True, verbose_name='Description (Source)'),
+ ),
+ migrations.RunPython(migrate_description_to_markdown),
+ ]
diff --git a/wger/exercises/migrations/0035_rename_exercises_e_name_ac11f4_gin_exercises_t_name_6264c9_gin_and_more.py b/wger/exercises/migrations/0035_rename_exercises_e_name_ac11f4_gin_exercises_t_name_6264c9_gin_and_more.py
deleted file mode 100644
index 0c60fc014..000000000
--- a/wger/exercises/migrations/0035_rename_exercises_e_name_ac11f4_gin_exercises_t_name_6264c9_gin_and_more.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# Generated by Django 5.2.9 on 2025-12-10 00:17
-
-import django.db.models.deletion
-import wger.exercises.models.image
-import wger.utils.images
-from django.db import migrations, models
-
-
-class Migration(migrations.Migration):
- dependencies = [
- ('exercises', '0034_add_exercise_image_dimensions'),
- ]
-
- operations = [
- migrations.AddField(
- model_name='historicaltranslation',
- name='description_source',
- field=models.TextField(blank=True, null=True, verbose_name='Description (Source)'),
- ),
- migrations.AddField(
- model_name='translation',
- name='description_source',
- field=models.TextField(blank=True, null=True, verbose_name='Description (Source)'),
- ),
- ]
diff --git a/wger/exercises/tests/test_command_migrate_descriptions.py b/wger/exercises/tests/test_command_migrate_descriptions.py
deleted file mode 100644
index dd93af960..000000000
--- a/wger/exercises/tests/test_command_migrate_descriptions.py
+++ /dev/null
@@ -1,79 +0,0 @@
-# This file is part of wger Workout Manager.
-#
-# wger Workout Manager is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# wger Workout Manager is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-
-# 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 import Translation
-
-
-class TestMigrateDescriptionsCommand(WgerTestCase):
- """
- Tests the migrate descriptions command
- """
-
- def setUp(self):
- super().setUp()
- self.translation = Translation.objects.get(pk=1)
-
- self.raw_html = (
- '<p>This is <b>bold</b> and <i>italic</i>.</p><ul><li>Item 1</li><li>Item 2</li></ul>'
- )
-
- # Set to Legacy State (no markdown).
- Translation.objects.filter(pk=1).update(description=self.raw_html, description_source=None)
- self.translation.refresh_from_db()
-
- def test_migration_command(self):
- """
- Test that the command converts HTML to Markdown correctly for various tags.
- """
-
- out = StringIO()
- call_command('migrate_descriptions_to_markdown', stdout=out)
-
- self.translation.refresh_from_db()
-
- src = self.translation.description_source
- self.assertIsNotNone(src)
- self.assertTrue('**bold**' in src or '__bold__' in src) # Markdownify config dependant
- self.assertTrue('*italic*' in src or '_italic_' in src)
- self.assertIn('* Item 1', src)
- self.assertIn('* Item 2', src)
-
- desc = self.translation.description
- self.assertIn('<strong>bold</strong>', desc)
- self.assertIn('<em>italic</em>', desc)
- self.assertIn('<ul>', desc)
- self.assertIn('<li>Item 1</li>', desc)
- self.assertIn('<p>', desc)
-
- def test_dry_run(self):
- """
- Test that dry-run does not alter the database.
- """
-
- out = StringIO()
- call_command('migrate_descriptions_to_markdown', '--dry-run', stdout=out)
-
- self.translation.refresh_from_db()
-
- self.assertIsNone(self.translation.description_source)
- self.assertIn('[Dry Run]', out.getvalue())
- self.assertEqual(self.translation.description, self.raw_html)