我为我的登录系统创建了一个自定义身份验证后端。当然,当我在 python shell 中尝试时,自定义后端可以工作。但是,当我在服务器中运行它时出现错误。错误显示“此模型中不存在以下字段或者是 m2m 字段:last_login”。我是否需要在客户模型中包含 last_login 字段,或者是否有其他解决方案可以解决该问题?
这是我的示例代码:
In my models.py
class Customer(models.Model):
yes_or_no = ((True, 'Yes'),(False, 'No'))
male_or_female = ((True,'Male'),(False,'Female'))
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100,blank = False, null = False)
password = models.CharField(max_length=100)
gender = models.BooleanField(default = True, choices = male_or_female)
birthday = models.DateField(default =None,blank = False, null = False)
created = models.DateTimeField(default=datetime.now, blank=True)
_is_active = models.BooleanField(default = False,db_column="is_active")
@property
def is_active(self):
return self._is_active
# how to call setter method, how to pass value ?
@is_active.setter
def is_active(self,value):
self._is_active = value
def __str__(self):
return self.name
在后端.py
from .models import Customer
from django.conf import settings
class CustomerAuthBackend(object):
def authenticate(self, name=None, password=None):
try:
user = Customer.objects.get(name=name)
if password == getattr(user,'password'):
# Authentication success by returning the user
user.is_active = True
return user
else:
# Authentication fails if None is returned
return None
except Customer.DoesNotExist:
return None
def get_user(self, user_id):
try:
return Customer.objects.get(pk=user_id)
except Customer.DoesNotExist:
return None
在views.py
@login_required(login_url='/dataInfo/login/')
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(name=username,password=password)
if user is not None:
if user.is_active:
login(request,user)
#redirect to user profile
print "suffcessful login!"
return HttpResponseRedirect('/dataInfo/userprofile')
else:
# return a disable account
return HttpResponse("User acount or password is incorrect")
else:
# Return an 'invalid login' error message.
print "Invalid login details: {0}, {1}".format(username, password)
# redirect to login page
return HttpResponseRedirect('/dataInfo/login')
else:
login_form = LoginForm()
return render_to_response('dataInfo/login.html', {'form': login_form}, context_instance=RequestContext(request))
在设置.py
AUTHENTICATION_BACKENDS = ('dataInfo.backends.CustomerAuthBackend', 'django.contrib.auth.backends.ModelBackend',)
最佳答案
发生这种情况是因为您使用的是 django 的 login()
登录用户的功能。
Django 的login
函数发出一个名为 user_logged_in
的信号与 user
您作为参数提供的实例。 See login()
source .
而这个信号在 django 的 contrib.auth.models
中被监听.它尝试更新名为 last_login
的字段假设您提供的用户实例是 django 默认 AbstractUser
的子类模型。
为了解决此问题,您可以执行以下操作之一:
login()
django 附带的函数并创建一个自定义函数。 user_logged_in
来自 update_last_login
的信号接收者。 Read how . last_login
的字段根据您的型号 关于django - 关于 Django 自定义身份验证和登录的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38156681/