Fallback for Django view that relies on session variable - django

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

Related

How to get username from user id in template

This is probably a simple answer but I cant figure it out. I have a comment system on my blog. I need to get the username from the user id.
I get the id from which is a fk to the users table
{{child_comment.parent_userdata_id}}
Usually when I need to do this I just user .username but it doesn't seem to work in this case
The only way you can get object data from the database is to fetch it on the server-side.
Unfortunately, you can't do that on the live HTML template.
Django template is just for evaluating the pre-existing context data for better use.
So, filtering the username from user id in views (backend) and passing it via the context into the template is the only (and probably the best) option.
Assuming user login is required to comment, you can create a variable of user = request.user in your view function, now user variable has the instance of user and pass it as context in template. It would look like this
views.py
def view_function(request):
user = request.user
# do something
context = {
'user' : user,
}
return render(request, 'template.html', context)
template.html
<p>{{user.username}}</p>
reference

how can i store this created cookie key in a variable in django

request.session.set_test_cookie() <---- this will create a session with cookie id
but how can I store this cookie key in a variable in Django.
I've tried this, but it gives error.
id = request.session.set_test_cookie()
Django provides an easy way to test whether the user’s browser accepts cookies. Just call the set_test_cookie() method of request.session in a view, and call test_cookie_worked() in a subsequent view – not in the same view call reference.
so set_test_cookie() method is only for testing a is browser support cookie or not. if you want to check is browser support call session.test_cookie_worked() method
Create cookie in django as follow:
def view(request):
response = HttpResponse('response data')
response.set_cookie('cookie_name', 'cookie_value')
Retrieve cookie data:
def view(request):
if 'cookie_name' in request.COOKIES:
value = request.COOKIES['cookie_name']

How to use cookies and sessions django

I a have a certain amounts of products. I want to make function that save a certain products in cookies not database. But i dont know how to create a list of product in cookies. Products mast be saved in such way from that i can show them by some function. What method i must use to create a list of products in cookies.
def add_instance_note(request,instance_id):
instance = Instance.objects.get(pk=instance_id)
request.session['list'].append(instance_id)
return render_to_response('show_instance.html', locals(),
context_instance=RequestContext(request))
def show_instance_note(request):
instances=[]
for instance_id in request.session['list']:
instances.append(Instance.objects.get(pk=instance_id))
return render_to_response('show_instance_note.html', locals(),
context_instance=RequestContext(request))
To use sessions with Django you must first enable and configure a session service, with a certain backend (in your case cookies). This is covered in depth here:
https://docs.djangoproject.com/en/1.6/topics/http/sessions/#using-cookie-based-sessions
For basic cookie support, this is available on the request/respond objects:
https://docs.djangoproject.com/en/dev/ref/request-response/
You can set a cookie with set_cookie:
def GetHandler(request):
response = HttpResponse('Testing cookies')
response.set_cookie('key', 'value')
To get cookies, you retrieve them from request.COOKIES. You can use standard dict operations like has_key and get to retrieve them (by the key you set previously).

How do I make cookie sessions?

I'm trying to make a cookie session and can't find anything thats resembles clear documentation. The django docs on this are very weak!
Alls I found was this guys video on cookies: http://www.youtube.com/watch?v=U_dDY7TvJ4E
Can someone show me how to make a cookie when a visitor goes to my site?
I want be able to save that cookie in my database, so that when they make another request I can associate changes with them server side.
Thanks!
Here is the link for where in the Django Docs on how to make cookies:
https://docs.djangoproject.com/en/dev/topics/http/sessions/
A short example of how to do so would be like so. You can use the built in Session table as a dictionary like so:
def myView(request):
request.session['foo'] = 'bar'
# other view code
render(request, 'mypage.html')
UPDATE:
This is how you would redirect a User based on if they have a Cookie or not
def myViewTwo(request):
id = request.session['UUID1']
# verify the UUID1 exists
if id == 'UUID1:
return render(request, 'cookie.html')
# if not, send them to a normal view
return render(request, 'no_cookie.html')

How to pass dictionary of values when redirecting user to a url in django

Below is the code from views.py where I am using render_to_response to direct the user to done.html along with a dictionary of variables. But, I actually want to direct the user to a url /home_main/#signin_completeand pass the dictionary of variables that are callable. Can someone please suggest if there is a way of doing this ?
def done(request):
"""Login complete view, displays user data"""
scope = ' '.join(GooglePlusAuth.DEFAULT_SCOPE)
return render_to_response('done.html', {
'user': request.user,
'plus_id': getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None),
'plus_scope': scope
}, RequestContext(request))
EDIT
My requirement is to render a second page (signin_complete) from a multipage html (home_main.html). Currently, I am achieving this by redirecting the user with HttpResponseRedirect as shown below. But, I would also like to pass a callable dictionary that I can use in the second page of the multipage html.
Here is a link that gives more information of a multipage html under multipage template structure.
def done(request):
"""Login complete view, displays user data"""
scope = ' '.join(GooglePlusAuth.DEFAULT_SCOPE)
return HttpResponseRedirect('/home_main/#signin_complete')
Below is the dictionary that I would like to pass to the second page (sign_complete) in the multi page html.
{
'user': request.user,
'plus_id': getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None),
'plus_scope': scope
}
The session is the place to store data between requests.
# in done():
request.session['dict_to_save'] = my_dict_to_save
return redirect('/new/url/to/redirect/to')
# in the new view:
values_from_session = request.session.pop('dict_to_save', None)
It would be much better if you would redirect request inside done() method, like the docs advises you to do.
This solves your issue as well, since you can define your own url to redirect to, there's related SO question of how to add hash tags when redirecting.