1

I have to set cookies to save cart details in my project but its not working, when i test cookies using function

request.session.set_test_cookie()

Then it set cookies but response.set_cookie function is not setting cookies. I have tried this code.

def index(request):
    if request.method == 'GET':
        response = HttpResponse('hello')
        days_expire = 7
        max_age = days_expire * 24 * 60 * 60 
        response.set_cookie('my_cookie', 'Product Cart', max_age=max_age)
        return render(request, 'home/index.py')

and for getting cookis , this code is being used

def sport(request):
    if request.method == 'GET':
        if 'my_cookie' in request.COOKIES:
            value = request.COOKIES['my_cookie']
            return HttpResponse(value)
        else:
            return HttpResponse('Cookie not set')

It always prints cookie not set string, What can be the reason behind it.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Pankaj
  • 229
  • 5
  • 17

2 Answers2

4

You are creating two different HttpResponse instances: one manually and the other one is created by the render() call and returned from the view. You should save the result the of the render() call and set the cookie there:

response = render(request, 'home/index.py')
response.set_cookie('my_cookie', 'Product Cart', max_age=max_age)
return response

You should also consider:

  • Using an extenstion different from .py for your templates. They might get confused with Python code files.
  • Using sessions for your shipping card.
Klaus D.
  • 13,874
  • 5
  • 41
  • 48
  • Thankyouuu so much, it solved my issue, thanks a lot :) – Pankaj Nov 18 '16 at 09:16
  • One more thing how can i use "dictionary" in place of my_cookie variable like my_cookie.item_count and my_cookie.price – Pankaj Nov 18 '16 at 09:17
  • Cookies are text only, they can not store dictionaries directly, but a session can do that. IF you need more information, open a new question with the new topic. – Klaus D. Nov 18 '16 at 09:19
0

You must return the object as shown below otherwise cookies are not set to a browser and you can see my answer explaining how to set and get cookies in Django:

from django.shortcuts import render

def my_view(request):
    response = render(request, 'index.html', {})
    response.set_cookie('first_name', 'John')
    response.cookies['last_name'] = 'Smith'
    return response # Must return the object

In addition, Django sessions can set the session id cookies to a browser without returning the object as shown below:

from django.shortcuts import render

def my_view(request):
    response = render(request, 'index.html', {})
    request.session['first_name'] = 'John'
    request.session['last_name'] = 'Smith'
    return response # Don't need to return the object
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129