Django Cookies, how can I set them?

Django Cookies, how can I set them?

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:

Set persistent cookie based on their area.
When they return read cookie, grab zipcode.
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. 

Solutions/Answers:

Answer 1:

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 :

Answer 2:

Using Django’s session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don’t need a helper function).

Setting a cookie:

def view(request):
  response = HttpResponse('blah')
  response.set_cookie('cookie_name', 'cookie_value')

Retrieving a cookie:

def view(request):
  value = request.COOKIES.get('cookie_name')
  if value is None:
    # Cookie is not set

  # OR

  try:
    value = request.COOKIES['cookie_name']
  except KeyError:
    # Cookie is not set

Answer 3:

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django’s sessions feature. This will let you get and set variables tied internally to the user’s session cookie. Cool thing about this is that if you want to store a lot of data tied to a user’s session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django’s end of storing the session data to keep in mind).

References