Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set or get a cookie value in django

Tags:

cookies

django

This is my code:

from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django import http from django.http import HttpResponse   def main(request, template_name='index.html'):     HttpResponse.set_cookie('logged_in_status', 'zjm1126')     context ={               'a':a,               'cookie':HttpResponse.get_cookie('logged_in_status'),     }      return render_to_response(template_name, context)     #return http.HttpResponsePermanentRedirect(template_name) 

It raises this exception:

unbound method set_cookie() must be called with HttpResponse instance as first argument (got str instance instead) 

What can I do?

like image 589
zjm1126 Avatar asked Feb 25 '11 04:02

zjm1126


People also ask

What is request cookies in Django?

Django's request object has an attribute COOKIES, like COOKIES array in PHP. COOKIES is a special attribute of request, and its value is the name of the cookie from which you want to read data. Since there can be multiple cookies, you can change this value many times according to the type of cookie you want to store.

Where are Django cookies?

Build Python Django Real Project: Django Web Development Always keep in mind, that cookies are saved on the client side and depending on your client browser security level, setting cookies can at times work and at times might not.

Does Django use cookies by default?

Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users).


1 Answers

You can't just start calling methods on the HttpResponse class, you have to instantiate it e.g. response = HttpResponse("Hello World"), call the cookie method, and then return it from your view.

response = render_to_response(template_name, context)  response.set_cookie('logged_in_status', 'never_use_this_ever')  return response # remember my other answer:  # it's a terrrible idea to set logged in status on a cookie. 

To get the cookie:

request.COOKIES.get('logged_in_status')  # remember, this is a terrible idea. 
like image 127
Yuji 'Tomita' Tomita Avatar answered Oct 13 '22 23:10

Yuji 'Tomita' Tomita