简体   繁体   English

我如何使用 mysql 上的“用户”表,而不是 django 站点默认的“auth_user”表?

[英]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?我如何使用 mysql 上的“用户”表,而不是 django 站点默认的“auth_user”表?

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来自views.py的代码

code from models.py (User)来自models.py(用户)的代码

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)来自 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:只需在您的 models.py 中覆盖用户 model 的默认“db_table”名称:

from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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