我正在使用phpMyAdmin作为数据库。 我正在创建自己的用户表并在其中存储用户信息,而不扩展Django用户模型。现在,我在登录部分遇到了问题。我无法从带对象的用户表中获取数据,并且身份验证功能也无法正常工作。 这是我的代码:
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .form import SignUp,UserLogin
from .models import users
from django.contrib.auth import authenticate,get_user_model,login,logout
from django.contrib.auth.models import User
def Userlogin(request):
form=UserLogin()
if request.method == 'POST':
user_login = UserLogin(request.POST or None)
if user_login.is_valid():
username = request.POST.get('email', '')
password = request.POST.get('password', '')
getInfo=users.objects.get(email='example@mail.com')
user=authenticate(email=username,password=password)
if user is not None and user.is_active:
login(request,user)
return redirect('/')
args={'form':form}
return render(request,'html/login.html',args)
from django import forms
from .models import users
class UserLogin(forms.Form):
email = forms.CharField(widget=forms.EmailInput(attrs=
{ 'value':'',
'class':'form-control'}))
password = forms.CharField(widget=forms.TextInput(attrs=
{ 'type': '',
'value':"mukul",
'class':'form-control'}))
from django.db import models
class users(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=100, blank=False)
email=models.EmailField(max_length=100, blank=False, unique=True)
password=models.CharField(max_length=500, blank=False)
created_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now_add=True)
def __str__(self):
return self.email
我需要什么:-
authenticate()
。它不起作用,我不知道想要是错误的。我应该在form.py中创建新的authenticate()
。如果我调用users.objects.get(email='example@mail.com')
,它也不能在view.py中工作,但是如果在python shell中运行,则效果很好。
getInfo = users.objects.get(email='example@mail.com')
显示错误:
类用户没有对象成员
如果我创建自己的用户模型
objects.get()
,objects.all()
,
objects.create_user()
等?请帮助我,我正在从事一个项目,并且对此错误感到困惑。谢谢
答案 0 :(得分:0)
首先回答您的问题: 如果我创建自己的用户模型: 是否要创建自己的登录身份验证功能?是 我是否要创建objects.get(),objects.all(),objects.create_user()等?不,
您需要修复错误:
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import SignUp,UserLogin #Wrong Import
from .models import users
from django.contrib.auth import authenticate,get_user_model,login,logout
from django.contrib.auth.models import User
def Userlogin(request):
form=UserLogin()
if request.method == 'POST':
user_login = UserLogin(request.POST or None) #Indentation
if user_login.is_valid():
username = request.POST.get('email', '')
password = request.POST.get('password', '')
getInfo=users.objects.get(email='example@mail.com')
user=authenticate(email=username,password=password)
if user is not None and user.is_active:
login(request,user)
return redirect('/')
args={'form':form} #Fix Indentation
return render(request,'html/login.html',args) #Fix Indentation
Models.py
class users(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=100, blank=False)
email=models.EmailField(max_length=100, blank=False, unique=True)
password=models.CharField(max_length=500, blank=False)
created_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now_add=True)
def __str__(self):
return self.email
此外,您需要做的是“运行迁移”。 python manage.py makemigrations应用程序名称 python manage.py migration
这将在数据库中自动创建模型,因此Django的ORM可用于.objects.get
更改Models.py(扩展默认用户,因为它已经包含电子邮件和密码字段)
from django.db import models
from django.contrib.auth.models import User as AuthUser, UserManager
# Extend the base User model
class User(AuthUser):
class Meta:
db_table = 'user'
active = models.CharField(max_length=1)
last_modified = models.DateTimeField("last modified")
objects = UserManager()
覆盖用户的Django模型后端
class CustomAuth(ModelBackend):
def authenticate(**credentials):
return super(CustomAuth, self).authenticate(**credentials)
def authenticate(self, username=None, password=None):
# Check the username/password and return a User.
if username != None and password != None:
# Get the user
try:
user = User.objects.get(email=username)
if user.check_password(password):
logger.info('User is authenticated, logging user in')
return user
except User.DoesNotExist:
pass
return None
def get_user(self, user_id):
try:
return User.objects.get(id=user_id)
except User.DoesNotExist:
return None
现在您可以将其用作:
user = authenticate(username='test@gmail.com', password='testUser')
以供进一步参考:https://www.micahcarrick.com/django-email-authentication.html