How do I set a cookie for django login?
you can implement this using session middleware , be sure to include it in your project. I recommend you use django.contrib.auth for session management. It manages sessions in the database, which is much safer than just storing the username in a cookie
source to share
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
source to share
django.contrib.auth app . this is the best way to add login functionality to your website. This app. uses django.contrib.sessions app and middleware.
The session middleware will keep track of the cookie setting in the user's browser for you. Then in your code, that means you'll need to decorate your views to get users to log in:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
Within your view, you will have access to
-
request.session
which isdict
where you can store data in the session -
request.user
which user object
I advise you to read the docs. Documentation is one of the best parts of Django
source to share