这是我的代码片段:
class LoginView(View):
facility = 'unique-named-facility'
audience = {'broadcast':True}
form_class = LoginForm
#This is a constructor
def __init__(self,*args,**kwargs):
#Initialize inherited parent calss by calling its constructor
super(LoginView,self).__init__(*args,**kwargs)
#Create an instance of redis publisher at the time od instaniation of Login View
self.redis_publisher = RedisPublisher(facility=self.facility, **self.audience)
def get(self, request):
#Create a message ovject for websocket
message = RedisMessage('A message has been passed to all clients listening to this unique-named-facility')
#Publish the socket
self.redis_publisher.publish_message(message)
#Initialize the login form
form = self.form_class()
#Render the login form
if request.COOKIES.get('user') != None:
login(request,request.COOKIES.get('user'))
return HttpResponseRedirect('/app/dashboard/')
return render(request,'login/index.html',{'form' : form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
#Fetch username and password
user_name = form.cleaned_data["user_name"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data["remember"]
#Authenticate the User
user = authenticate(username=user_name, password=password)
if user is not None:
#After authentication login the user
login(request,user)
# Redirect to the new page if authenticated succesfully
response = HttpResponseRedirect('/app/dashboard/')
if remember_me:
response.set_cookie('user',user)
return response
else:
# Empty previous form Content
form = self.form_class()
# If user is still not autheticated re render the view with warning message
return render(request,'login/index.html',{'form' : form , "warning": "Please enter valid credentials"})
我想在这里实现的是一个类似Twitter的功能,记住我(让我登录)通过django 1.10
答案 0 :(得分:1)
此处发生错误:https://github.com/django/django/blob/stable/1.10.x/django/contrib/auth/init.py#L101
user.pk
中的是user
不是用户对象而是str对象。并且潜在的问题显然是你在代码中的某个地方重新定义str
作为变量或/并且因此,你将字符串对象传递给login()
而不是用户对象
检查它的位置并修复它