Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing default auth_user table name

Tags:

python

django

i'm happy with django built in user/auth , i just want to add some fields to it and change table name (mostly the last one , i can use another table for custom fields )

so i searched around and apparently we can use subclass as suggested on Rename Django's auth_user table?

So i have to start a new app and use it's model to as a subclass for AbstractUser or there is another way? (After all i just want to use it's model and other parts of app are useless )

anyway i created a new project / started app called customuser and in its model i have this code

customuser/models.py

from django.db import models

from django.contrib.auth.models import AbstractUser
class customuser(AbstractUser):

    class Meta:
        swappable = 'AUTH_USER_MODEL'  
        db_table = 'customuser'

i ran makemigrations AND migrate ... it's done successfully

enter image description here

but atill the tables with default name was created in database as you can see below ... am i missing something ?

enter image description here

like image 283
hretic Avatar asked Feb 07 '23 23:02

hretic


2 Answers

To use a custom user model, you need to set the AUTH_USER_MODEL setting in your settings module.

Note that you don't need to set swappable = 'AUTH_USER_MODEL'. This is an undocumented and private attribute, and is probably better left untouched.

like image 153
knbk Avatar answered Feb 16 '23 06:02

knbk


Quite frankly if you're still in the position to do it, i'd just start a new app. It says in the docs that this decision is best made before starting your project because its a pain in the ... its hard.

If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time.

The solution otherwise is to dumpdata from the database, and manually tweak it so any reference to the user class in your dump file is replaced with your new user class. then you need to create some migrations to change the schema.

So it is doable. its just much simpler to start from a fresh project.

like image 26
Sayse Avatar answered Feb 16 '23 08:02

Sayse