安装django-users2
- 首先下载django-users2
将解压的users拖入工程目录下 - 然后运行
pip install django-users2
在settings.py 中添加
INSTALLED_APPS = [
...
'users',
...
]
AUTH_USER_MODEL = 'users.User'
- 引入成功后创建数据表
python manage.py makemigrations
python manage.py migrate
tip:
- 如果添加urls.py中报
NameError at / name 'include' is not defined
可将from django.conf.urls import include
引入到urls.py - 如果安装了mysql-python后更新mysql数据库报错,有可能数据库字符集设置错误
指定字符集:
CREATE DATABASE ledemon DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
- 如果django后台添加汉子报错
'ascii' codec can't encode characters in position 0-1:
需要在相应入口文件添加
import sys
reload(sys)
sys.setdefaultencoding('utf8')
如果用python manager.py启动,则在 manager.py头部添加
如果用uwsgi启动,需要在uwsgi.py头部添加
- Django 2 中使用mysql报错
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
需要在Django的init文件中添加
import pymysql
pymysql.install_as_MySQLdb()
- 如果想拉取所有静态文件
python manage.py collectstatic
如果报错django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
需要在setting.py中添加
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
django自带User进行验证
- 用户登录验证
from django.contrib.auth import authenticate
user = authenticate(username=username, password=password) # 验证用户名和密码,返回用户对象
- 用户密码对比
from django.contrib.auth.hashers import make_password, check_password
#创建django密码, 第二个参数为None是每次产生的密码都不用,第三个参数为算法, 后面两个参数可以忽略
dj_ps = make_password(password.decode('utf-8'), None, 'pbkdf2_sha256')
# check_password 返回值为一个Bool类型,验证密码的正确与否
ps_bool = check_password(ps, dj_ps)