How to set a login cookie in django?

2020-03-08 06:13发布

问题:

How do I set_cookie with the username of the member that is logged in to my site?

Thanks

回答1:

you can implement this by using the session middleware, make sure to enable it in your project. I recommend you to use django.contrib.auth to manage sessions though. It manages sessions in the database which is a lot safer than just saving the username in a cookie



回答2:

Here is an example of how to do it using middleware

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


回答3:

The django.contrib.auth app. is the best way to add a login feature to your site. This app. uses the django.contrib.sessions app and middleware.

The session middleware will look after setting a cookie in the user's browser for you. Then, in your code, it means that you will need to decorate your views to force users to login:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...

Inside your view, you will then have access to

  • request.session, which is a dict where you can store data across the session
  • request.user, which is user object

I advise you to read the docs. Documentation is one of the best parts of Django