我得到以下错误AttributeError:经理不在;在我的django项目中,当我尝试点击注册按钮时,'auth. user'已经被替换为'accounts.user',当我做了发送电子邮件和密码到后台的注册按钮。我有一个acoounts应用程序,其中文件中有以下代码:
backend.py:
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
class EmailBackend(ModelBackend):
def authenticate(self, request, email=None, password=None, **kwargs):
User = get_user_model()
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None
models.py:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.contrib.auth import get_user_model
from django.db import models
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
objects = CustomUserManager()
def __str__(self):
return self.email
views.py:
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login as auth_login
from django.contrib.auth import authenticate
from .models import User
from django.contrib import messages
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Registration successful. You can now log in.')
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'register.html', {'form': form})
def login_view(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, username=email, password=password)
if user is not None:
auth_login(request, user)
return redirect('homepage')
else:
messages.error(request, 'Invalid email or password')
return render(request, 'login.html')
如果你需要任何其他的代码,我会发送,但这些是主要的文件,我猜。谢谢你
1条答案
按热度按时间8ftvxx2r1#
您在www.example.com中调用的用户创建表单views.py是
但是,这是将使用普通用户模型的默认表单。您需要在您的www.example.com中覆盖它forms.py,类似于
然后为您的views.py register()方法导入它。