0
我爲我的登錄系統創建自定義身份驗證後端。當然,當我在python shell中嘗試時,自定義後端工作正常。但是,當我在服務器中運行它時出現錯誤。錯誤顯示「以下字段在此模型中不存在或者是m2m字段:last_login」。我是否需要在客戶模型中包含last_login字段,或者是否有其他解決方案來解決問題? 這裏是我的示例代碼:有關Django自定義身份驗證和登錄的錯誤?
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
在backends.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))
在setting.py
AUTHENTICATION_BACKENDS = ('dataInfo.backends.CustomerAuthBackend', 'django.contrib.auth.backends.ModelBackend',)
我在Customer模型中添加了一個last_login字段,但同樣的錯誤依然存在。我是否需要修改其他地方? – pipi
你確定你已經添加它作爲日期時間字段?你有沒有遷移你的數據庫? – v1k45
是的,我做過。我意識到字段名稱必須與「last_login」完全一樣,但我將其命名爲私有變量(_last_login),這可能是造成問題的原因。 – pipi