如何在django中设置登录cookie?

use*_*500 0 django cookies login member

如何使用登录到我的站点的成员的用户名set_cookie?

谢谢

sid*_*rcy 8

以下是使用中间件进行操作的示例

class UserCookieMiddleWare(object):
    """
    Middleware to set user cookie
    If user is authenticated and there is no cookie, set the cookie,
    If the user is not authenticated and the cookie remains, delete it
    """

    def process_response(self, request, response):
        #if user and no cookie, set cookie
        if request.user.is_authenticated() and not request.COOKIES.get('user'):
            response.set_cookie("user", 'Hello Cookie')
        elif not request.user.is_authenticated() and request.COOKIES.get('user'):
            #else if if no user and cookie remove user cookie, logout
            response.delete_cookie("user")
        return response
Run Code Online (Sandbox Code Playgroud)