feat: add avatar migration

This commit is contained in:
Reto Aebersold 2024-01-10 09:28:46 +01:00
parent 28445cf1a5
commit 20885a53db
3 changed files with 51 additions and 6 deletions

View File

@ -1,8 +1,8 @@
# Generated by Django 3.2.20 on 2024-01-08 08:43
import django.db.models.deletion
from django.db import migrations, models
from vbv_lernwelt.core.model_utils import migrate_avatars
class Migration(migrations.Migration):
dependencies = [
@ -11,10 +11,6 @@ class Migration(migrations.Migration):
]
operations = [
migrations.RemoveField(
model_name="user",
name="avatar_url",
),
migrations.AddField(
model_name="user",
name="avatar",
@ -26,4 +22,9 @@ class Migration(migrations.Migration):
to="media_files.userimage",
),
),
migrations.RunPython(migrate_avatars),
migrations.RemoveField(
model_name="user",
name="avatar_url",
),
]

View File

@ -1,3 +1,5 @@
from django.conf import settings
from django.core.files import File
from wagtail.models import Page
@ -144,3 +146,39 @@ def remove_organisations(apps=None, schema_editor=None):
Organisation.objects.filter(
organisation_id=org_id,
).delete()
def migrate_avatars(apps=None, schema_editor=None):
# pylint: disable=import-outside-toplevel
if apps is None:
from vbv_lernwelt.core.models import User
from vbv_lernwelt.media_files.models import UserImage
else:
User = apps.get_model("core", "User")
UserImage = apps.get_model("media_files", "UserImage")
# Models created by Django migration don't contain methods of the original models.
# We need to add them manually.
from wagtail.images.models import AbstractImage
UserImage.get_upload_to = AbstractImage.get_upload_to
avatar_dir = settings.APPS_DIR / "static" / "avatars"
for user in User.objects.all().exclude(
avatar_url="/static/avatars/myvbv-default-avatar.png"
):
if not user.avatar_url:
continue
avatar_file = user.avatar_url.split("/")[-1]
try:
with open(avatar_dir / avatar_file, "rb") as f:
image = UserImage.objects.create(
file=File(f),
)
user.avatar = image
user.save()
except FileNotFoundError:
pass

View File

@ -1,4 +1,6 @@
import os
from pathlib import Path
from unittest import skipIf
from django.core.files import File
from django.test import RequestFactory, TestCase
@ -10,6 +12,10 @@ from vbv_lernwelt.media_files.models import UserImage
TEST_IMAGE = Path(__file__).parent / "test_images" / "user1_profile.jpg"
@skipIf(
os.environ.get("ENABLE_S3_STORAGE_UNIT_TESTS") is None,
"Only enable tests by setting ENABLE_S3_STORAGE_UNIT_TESTS=1",
)
class UserImageViewTest(TestCase):
def setUp(self):
self.factory = RequestFactory()