Django Cookies, how can I set them?

Jeffrey picture Jeffrey · Oct 26, 2009 · Viewed 119.3k times · Source

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.

Answer

Peter picture Peter · Apr 7, 2011

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