Python

Cookies in Django

How to save data to a browser cookie from a Django app.

set_cookie

Save dato a a cookie

def set_cookie(response, key, value):
    max_age = settings.SESSION_COOKIE_AGE
    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
    response.set_cookie(key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None)

get_cookie

Read data from a cookie

def get_cookie(request, name):
    if name in request.COOKIES:
        return request.COOKIES[name]
    else:
        return None

views.py

Set the cookie before send the response.

def index(request):
    template = loader.get_template('home.html')
    context = {
        'page': 'home',
    }
    response = HttpResponse(template.render(context, request))
    set_cookie(response, 'page', page)
    return response

Read the cookie:

def index(request):
    template = loader.get_template('home.html')
    context = {
        'page': get_cookie(request, 'page'),
    }
    response = HttpResponse(template.render(context, request))
    return response