简体   繁体   中英

How can i use the “user” table on mysql instead of the “auth_user” table which is the default from the django site?

How can i use the "user" table on mysql instead of the "auth_user" table which is the default from the django site?

def login_user(request):
if request.method == 'POST':
    form = AuthenticationForm(request=request, data=request.POST)
    if form.is_valid():
        user_id = form.cleaned_data.get('user_id')
        password = form.cleaned_data.get('password')
        user = authenticate(user_id=user_id, password=password)

        if user is not None:
            login(request, user)
            messages.info(request, f"You are now logged in as {user_id}")
            return redirect('/')
        else:
            messages.error(request, "Invalid username or password.")
    else:
        messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request=request,
              template_name="login.html",
              context={"form": form})

code from views.py

code from models.py (User)

class User(models.Model):
login_id = models.AutoField(primary_key=True)
user_id = models.CharField(max_length=50, blank=True, null=True)
employee_id = models.IntegerField()
password = models.CharField(max_length=45)
user_type = models.CharField(max_length=45)

class Meta:
    managed = False
    db_table = 'user'

code from models.py (auth_user)

class AuthUser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.IntegerField()
username = models.CharField(unique=True, max_length=150)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=150)
email = models.CharField(max_length=254)
is_staff = models.IntegerField()
is_active = models.IntegerField()
date_joined = models.DateTimeField()

class Meta:
    managed = False
    db_table = 'auth_user'

Simply override the default 'db_table' name for the user model in your models.py:

from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM