简体   繁体   English

如何在 django 中验证来自 mysql 的用户?

[英]How to authenticate User from mysql in django?

I want to implement login app.我想实现登录应用程序。 all the users information are in table named 'admin_users'.所有用户信息都在名为“admin_users”的表中。 I am using mysql server by xampp.我正在使用 xampp 的 mysql 服务器。

when i am authenticating using user = authenticate(username=username,password=password) On printing user I am getting None .当我使用user = authenticate(username=username,password=password)在打印用户上进行身份验证时,我得到None

I am beginner in django and I could not find out whats wrong.我是 django 的初学者,我找不到问题所在。 If I am doing AdminUsers.objects.all() I can print all the table information.如果我正在执行AdminUsers.objects.all()我可以打印所有表信息。

models.py模型.py

class AdminUsers(models.Model):
    username=models.CharField(max_length=50)
    firstname=models.CharField(max_length=50)
    department=models.CharField(max_length=50)
    mail=models.CharField(max_length=50)
    id=models.IntegerField(primary_key=True)
    password=models.CharField(max_length=200)
    class Meta:
        db_table="admin_users"

view.py查看.py

def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username,password=password)
        print(user)
    return render(request,'AdminUsers/login.html')

my index.html contains simple forms with username and password.我的 index.html 包含带有用户名和密码的简单 forms。

settings.py设置.py

"""
Django settings for python_test project.

Generated by 'django-admin startproject' using Django 3.2.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-j*uh&s1$j-'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'python_test.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates'),
        os.path.join(BASE_DIR,'app_kanri/templates/app_kanri/')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'python_test.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


STATIC_URL = '/static/'


DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


You need to insert this in your settings: AUTH_USER_MODEL = 'AppName.AdminUsers' (replace AppName with the name of the app containing AdminUsers).您需要在设置中插入: AUTH_USER_MODEL = 'AppName.AdminUsers' (将 AppName 替换为包含 AdminUsers 的应用名称)。

Your custom User model should inherit from AbstractUser to be compatible with the authentication system (right now it will not work):您的自定义用户 model 应该从 AbstractUser 继承以与身份验证系统兼容(现在它不起作用):

class AdminUsers(AbstractUser):
    department=models.CharField(max_length=50)
    
    class Meta:
        db_table='admin_users'

Now AdminUsers will inherit fields of AbstractUser (username, email, password, is_staff, ...), read this for details .现在 AdminUsers 会继承 AbstractUser 的字段(用户名,email,密码,is_staff,...),详细阅读这个。 If you have already done migrations, you need to delete migrations of the default User model.如果您已经完成迁移,则需要删除默认用户 model 的迁移。

Note also that you should name the model 'AdminUser' and not 'AdminUsers'.另请注意,您应该将 model 命名为“AdminUser”而不是“AdminUsers”。

Not sure what your goal is with the AdminUsers model. The default django user model has flags like is_staff and is_superuser that you can use to seperate users and their permissions with regards to what they can access on the app.不确定 AdminUsers model 的目标是什么。默认的 django 用户 model 具有诸如 is_staff 和 is_superuser 之类的标志,您可以使用这些标志来区分用户及其在应用程序上可以访问的权限。 Check out the docs on the user model here此处查看用户 model 的文档

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

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