I am following these two references (one and two) to have a custom user model in order to authenticate via email and also to add an extra field to it.
class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True, max_length=254, ) mobile_number = models.IntegerField(unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() ... ... class Meta: db_table = 'auth_user' ... ...
As you can see, I have added the db_table='auth_user'
into the Meta fields of the class. Also, I have included AUTH_USER_MODEL = 'accounts.User'
and User model app (i.e., accounts)into the INSTALLED_APPS
in settings.py. Further more, I deleted the migrations folder from the app.
Then tried migrating:
$ python manage.py makemigrations accounts Migrations for 'accounts': accounts/migrations/0001_initial.py: - Create model User $ python manage.py migrate accounts
Which gives me an error:
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'.
How can I migrate from the existing django user model into a custom user model?
In short, you can use the get_user_model() method to get the model directly, or if you need to create a ForeignKey or other database relationship to the user model, use settings. AUTH_USER_MODEL (which is simply a string corresponding to the appname. ModelName path to the user model).
It's highly recommended to set up a custom User model when starting a new Django project. Without it, you will need to create another model (like UserProfile ) and link it to the Django User model with a OneToOneField if you want to add new fields to the User model.
Run python manage.py makemigrations to create a migration file. This is an auto-generated migration file using the above command. Now we will add function for transferring data from users table to bank_accounts table.
You have to clear admin, auth, contenttypes, and sessions from the migration history and also drop the tables. First, remove the migration folders of your apps and then type the following:
python manage.py migrate admin zero python manage.py migrate auth zero python manage.py migrate contenttypes zero python manage.py migrate sessions zero
Afterwards, you can run makemigrations accounts
and migrate accounts
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With