Search code examples
djangosession-cookiesdjango-sessions

Django cookie setting


I am using Django - ldap authentication in my project . Once if the user is authenticated , i need to set a cookie and return as a response to the server .

def post(self,request):
        userData = json.loads(request.body)
        username = userData.get('username') 
        password = userData.get('password')

        oLdap = LDAPBackend()


        if username == "admin" and password == "admin":
            User_Grps = "AdminLogin"
        else:
            try:
                User = oLdap.authenticate(username=username,password=password) 
                if User is not None:
                    User_Grps = User.ldap_user.group_dns
                else:
                    User_Grps = "Check your username and password"

            except ldap.LDAPError:
                   User_Grps = "Error"

        return HttpResponse(User_Grps)

How to add a cookie to the response and send it with a the User_Grps to the client


Solution

  • response = HttpResponse(User_Grps)
    response.set_cookie(key, value)
    return response
    

    That's it.