2016-12-06 5 views
0

Вот отрывок из моего кода:Как сохранить аутентифицированный пользователь в cookie в django?

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"}) 

Также скриншот браузера возвращает ошибку относительно рк: enter image description here

Я пытаюсь реализовать здесь является твиттер как функциональность помните меня (Оставаться в системе) через Джанго 1,10

+0

Вместо публикации скриншотов текста * отправьте текст * – Sayse

ответ

1

Ошибка происходит здесь: https://github.com/django/django/blob/stable/1.10.x/django/contrib/auth/init.py#L101

в user.pk is user не объект пользователя, а объект str. и основная проблема, по-видимому, что вы пересматриваете str где-то в коде, как переменная или/и в результате, вы передаете объект строки в login() вместо объекта пользователя

чека, где она есть, и исправить это