这是我第一次用Django做项目。作为第一步,我正在创建注册和登录用户的方法。
注册效果很好。但是,注册用户后,我尝试登录但没有成功。
我的models.py文件是:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, username, email, password=None, **extra_fields):
user = self.model(username=username, email=email, **extra_fields)
# set_password will handle the password before saving it in the database
# It hash the password before saving it
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(username, email, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=20, unique=True)
email = models.EmailField(unique=True)
password = models.CharField(max_length=256)
fname = models.CharField(max_length=100)
lname = models.CharField(max_length=100)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.username
class Meta:
managed = True
db_table = "users"
而views.py中的登录方法如下:
def signin(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
# Authenticate the user
user = authenticate(request, username=username, password=password)
# If it is not None - user exists and right credentials
if user:
login(request, user)
fname = user.first_name
return render(request, "authentication/index.html", {'fname': fname})
else:
messages.error(request, "Bad credentials")
return redirect("home")
return render(request, "authentication/signin.html")
另外,这是我的“注册”功能:
def signup(request):
if request.method == "POST":
username = request.POST.get("username")
fname = request.POST.get("fname")
lname = request.POST.get("lname")
email = request.POST.get("email")
password = request.POST.get("password")
password2 = request.POST.get("password2")
myuser = User.objects.create_user(username = username, fname
= fname, lname = lname, email=email, password=password)
myuser.first_name = fname
myuser.last_name = lname
myuser.is_active = False
myuser.save()
# redirect to login
return redirect("signin")
return render(request, "authentication/signup.html")
由于我在数据库中使用自定义用户表,因此我还将分享我的settings.py
from pathlib import Path
from Memovies.info import *
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
EMAIL_USE_TLS = EMAIL_USE_TLS
EMAIL_HOST = EMAIL_HOST
EMAIL_HOST_USER = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD
EMAIL_PORT = EMAIL_PORT
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.messages",
"django.contrib.staticfiles",
"authentication",
"catalog",
]
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 = "Memovies.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["templates"],
"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 = "Memovies.wsgi.application"
AUTH_USER_MODEL = 'authentication.User'
#Authentication backends
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
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/4.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
[已解决]我的代码很好,我只是没有考虑到用户未激活:P。