Skip to content

Instantly share code, notes, and snippets.

@fabienheureux
Last active August 18, 2021 10:36
Show Gist options
  • Save fabienheureux/cd6308ec18bc037ddb70c2aebf725736 to your computer and use it in GitHub Desktop.
Save fabienheureux/cd6308ec18bc037ddb70c2aebf725736 to your computer and use it in GitHub Desktop.
Update Wagtail's image model on an existing project
# Generated by Django 2.2.24 on 2021-08-17 11:33
from django.db import migrations
from django.forms.models import model_to_dict
from wagtail.images.models import Image as PreviousImage
from image.models import CustomImage as Image
def migrate_images(apps, schema_editor):
for image in PreviousImage.objects.all():
new_image_data = {}
for field in PreviousImage._meta.fields:
new_image_data[field.name] = getattr(image, field.name)
new_image = Image(**new_image_data)
new_image.id = image.id
new_image.save()
def remove_images(apps, schema_editor):
for image in Image.objects.all():
image.delete()
class Migration(migrations.Migration):
dependencies = [
("image", "0001_initial"),
]
operations = [
migrations.RunPython(migrate_images, reverse_code=remove_images),
]
@fabienheureux
Copy link
Author

If ever you need to add a custom wagtail image model, you might have some issues migrating your previously added images to your brand new model.

Here is a little gist to help you do such a thing.

Add a new image model

Start by adding your image model, once it is done, create an empty migration python manage.py makemigrations --empty yourappname (https://docs.djangoproject.com/fr/3.2/topics/migrations/)

Write the migration

Adapt the content of your empty migration to match what is written in this gist.

Deploy your changes

If you have an app running on production, you should start by deploying these changes without changing the default Wagtail's image model.

Switch Wagtail's image model

Once your changes are live, your migrations properly ran, you can safely switch the image model in the wagtail settings/base.py file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment