How to rename an existing Django application

How to rename an existing Django application

May 28, 2020

As business requirements change, so must software. So, sometimes the names of your Django apps will come to no longer make sense. This short tutorial will go through how to rename an existing app without any pain or data loss.

Step 1

Rename the app folder. For this example,"old_app" is our old name and "new_app" is our new name".

mv ./old_app ./new_app

Step 2

Update all imports referencing the old folder to reference the new.

For example:

# Before 
from myproject.old_app import models
# After
from myproject.new_app import models

Step 3

Update old app name references within the Django migrations.

Example changes you'll likely have to make:

# Before
dependencies = [
    ('old_app', '0023_auto_20200403_1050'),
]
# After
dependencies = [
    ('new_app', '0023_auto_20200403_1050'),
]

# Before
field = models.ForeignKey(
    default=None, on_delete=django.db.models.deletion.CASCADE,
    to='old_app.Experiment'
)
# After
field = models.ForeignKey(
    default=None, on_delete=django.db.models.deletion.CASCADE,
    to='new_app.Experiment'
)

Step 4

Make a commit at this point.

Then, however you run your application migrations in a deployed environment, run django_rename_app before you run your migrations in that process.

i.e Before "python manage.py migrate --noinput", as the example below shows.

# Before
python manage.py collectstatic --noinput
python manage.py migrate --noinput
gunicorn my_project.wsgi:application

# After
python manage.py collectstatic --noinput
python manage.py rename_app old_app new_app
python manage.py migrate --noinput
gunicorn my_project.wsgi:application

This will update the app name in the following internal Django database tables:

  • django_content_type
  • django_migrations

And rename the prefix of all of your tables to start with your new app name, rather than the old one.

Step 5

Deploy your project!

You may safely deploy multiple times as the django_rename_app command will only have any effect the first time it is executed.

After deployment give your database and application a manual check over and then remove django_rename_app from your project.

That's all folks. If you have any other tips or tricks to share, we'd love to hear them in the comments!

Latest Articles

How to validate Django ImageField dimensions
How to use ipdb debugger with docker-compose
How to rename an existing Django application, the right way