Search code examples
pythondjangocookiesbrowserdjango-cookies

How to set and get cookies in Django?


I have a web site which shows different content based on a location the visitor chooses. e.g: User enters in 55812 as the zip. I know what city and area lat/long. that is and give them their content pertinent to that area. My question is how can I store this in a cookie so that when they return they are not required to always enter their zip code?

I see it as follows:

  1. Set persistent cookie based on their area.
  2. When they return read cookie, grab zipcode.
  3. Return content based on the zip code in their cookie.

I can't seem to find any solid information on setting a cookie. Any help is greatly appreciated.


Solution

  • UPDATE : check Peter's answer below for a builtin solution :

    This is a helper to set a persistent cookie:

    import datetime
    
    def set_cookie(response, key, value, days_expire=7):
        if days_expire is None:
            max_age = 365 * 24 * 60 * 60  # one year
        else:
            max_age = days_expire * 24 * 60 * 60
        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,
        )
    

    Use the following code before sending a response.

    def view(request):
        response = HttpResponse("hello")
        set_cookie(response, 'name', 'jujule')
        return response
    

    UPDATE : check Peter's answer below for a builtin solution :