PacktPublishing / Django-4-by-example

Django 4 by example (4th Edition) published by Packt
https://djangobyexample.com/
MIT License
818 stars 461 forks source link

Please avoid user_model.contribute_to_class() and instead update code to a CustomUser model #64

Open cb109 opened 3 months ago

cb109 commented 3 months ago

Hi,

while your codebase uses references to settings.AUTH_USER_MODEL, it doesn't actually define and use a custom User model. This is a problem in combination with this user_model.contribute_to_class() call, which extends the User model dynamically, and with your repo checked out as is, targets Django's builtin User model.

As a result, running python manage.py makemigrations will create a new migration for Django itself e.g. at <my-venv>/lib/python3.7/site-packages/django/contrib/auth/migrations/0013_user_following.py.

While this does migrate for the moment, it will be incompatible with future Django versions should they add more migrations themselves, and inherently seems to be a bad idea. The contribute_to_class() isn't exactly recommended to use, and could be replaced by a more explicit field definition, and shielded from future Django updates by placing it on a custom User model within the project's own apps.

It can also lead you astray as a beginner when fiddling with migration files (e.g. deleting the migrations folder by accident). This problem popped up on the Official Django Discord, and I was able to find a few occurrences of that same issue over the last few years online. Since it looks like it's Django's own migration it was pretty confusing, so I just wanted to let you know.

Cheers