我正在使用django custom usermodel with restframework,在成功注册后,我无法为普通用户登录。我可以通过初始超级用户登录,但如果我创建新的超级用户,他们将成功注册,但在登录时出错,与尝试使用普通用户时一样。你知道吗
错误
Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.
对于一些配置文件,我也在管理面板中观察到以下错误。你知道吗
invalid password format or unknown hashing algorithm
型号.py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
class UserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
if not email:
raise ValueError('Users must have an email address')
now = timezone.now()
email = self.normalize_email(email)
user = self.model(
email=email,
is_staff=is_staff,
is_active=True,
is_superuser=is_superuser,
last_login=now,
date_time_onboarded=now,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
user = self._create_user(email, password, True, True, **extra_fields)
return user
class AppOnboarding(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
product_name = models.CharField(max_length=254, null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_time_onboarded = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
序列化程序.py
from rest_framework import serializers
from .models import AppOnboarding
class AppOnboardingSerializer(serializers.ModelSerializer):
class Meta:
model = AppOnboarding
fields = ['email', 'product_name', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
app_onboard = AppOnboarding(
email=self.validated_data['email'],
product_name=self.validated_data['product_name']
)
password = self.validated_data['password']
app_onboard.set_password(password)
app_onboard.save()
def save(self):
app_onboard = AppOnboarding(
email=self.validated_data['email'],
product_name=self.validated_data['product_name']
)
password = self.validated_data['password']
app_onboard.set_password(password)
app_onboard.save()
网址.py
from django.urls import path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('app', views.AppOnboardingView)
urlpatterns = router.urls
视图.py
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status, viewsets
from .serializers import AppOnboardingSerializer
from .models import AppOnboarding
class AppOnboardingView(viewsets.ModelViewSet):
queryset = AppOnboarding.objects.all()
serializer_class = AppOnboardingSerializer
*设置.py
"""
Django settings for nrn project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
# , EMAIL_HOST_USER , EMAIL_HOST_PASSWORD
from .email_info import EMAIL_HOST, EMAIL_PORT
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mz)6t6hfo*44sz*g)u&2o5!9p9azk!lwuju=*0lp_-c5)m-hj4'
# 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',
'rest_framework',
'send',
'apponboarding'
]
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 = 'nrn.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'nrn.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
EMAIL_HOST = EMAIL_HOST
EMAIL_PORT = EMAIL_PORT
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
AUTH_USER_MODEL = 'apponboarding.AppOnboarding'
# REST_FRAMEWORK = {
# 'DEFAULT_AUTHENTICATION_CLASSES': [
# 'rest_framework.authentication.SessionAuthentication',
# ],
# }
# AUTHENTICATION_BACKENDS = (
# 'django.contrib.auth.backends.RemoteUserBackend',
# 'django.contrib.auth.backends.ModelBackend',
# )
如果定义了自定义用户,则在设置中必须提及自定义身份验证用户模型。你知道吗
对于权限,可以将以下代码添加到AppOnboarding
相关问题 更多 >
编程相关推荐