I have a view that looks like this:
def CineByCiudad(request):
city = request.session["ciudad"]
cines = Cine.objects.filter(ciudad=city)
context = {'cines': cines}
return render_to_response('cine-ciudad.html', context, context_instance=RequestContext(request))
Now, I am using the session variable "ciudad" to filter my query. On the homepage of my site I let the user set their "ciudad" and once its set I redirect them to another page and they can start viewing the content based on their city("ciudad").
My homepage checks if the session has items:
def index(request):
#Checks to see if the session has items, in particular if a city has been set
if not request.session.items():
return render_to_response('index.html', context_instance=RequestContext(request))
else:
return redirect(Cartelera)
Now lets suppose for some reason the user deletes his cookies and on the site he visits a url different than the homepage(something like www.site.com/cartelera) he would then get an error because the session variable "ciudad" is not set.
Is there a way to create a default value for this session variable in case that it has not been set? Or what is a good practice to deal with this issue?
Use the dict.get method on the session to retrieve a default if the value isn't set, like this:
city = request.session.get('ciudad', 'default value')