tags:

views:

900

answers:

2

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.

+5  A: 

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).

Ben
Good point! One note, you can reduce the HTTP weight by hosting static content on a separate domain (not subdomain), so that the cookies are not sent on those requests. http://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site/305381#305381
John Paulett
+1  A: 

Heres 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)
    return response

use this before sending a response :

def view(request):
    resp = HttpResponse("hello")
    resp.set_cookie(resp, 'name", 'jujule')
    return resp
jujule
any problem if settings.SESSION_COOKIE_DOMAIN is not set?
panchicore
anyway django itselfs sets a default SESSION_COOKIE_DOMAIN.think about this setting if you need to share cookie across multiple subdomains.
jujule