0

I could set a dictionary or list to a session and get it properly as shown below:

# "views.py"

from django.http import HttpResponse

def my_view(request):
    request.session['teacher'] = {'name': 'John', 'age': 36}
    print(request.session['teacher']) # {'name':'John','age':36}
    print(request.session['teacher']['name']) # John
    print(request.session['teacher']['age']) # 36

    request.session['student'] = ['David', 21]
    print(request.session['student']) # ['David', 21]
    print(request.session['student'][0]) # David
    print(request.session['student'][1]) # 21
    return HttpResponse("Test")

But, I couldn't set a dictionary or list to a cookie and get it properly as shown below:

# "views.py"

from django.http import HttpResponse

def my_view(request):
    response = HttpResponse('Test')
    response.set_cookie('teacher', {'name': 'John', 'age': 36})
    response.cookies['student'] = ['David', 21]
    return response
# "views.py"

from django.http import HttpResponse

def my_view(request):
    print(request.COOKIES['teacher']) # {'name': 'John', 'age': 36}
    print(request.COOKIES['teacher']['name']) # Error
    print(request.COOKIES['teacher']['age']) # Error

    print(request.COOKIES['student']) # ['David', 21]
    print(request.COOKIES['student'][0]) # [
    print(request.COOKIES['student'][1]) # '
    HttpResponse("Test")

enter image description here

So, how can I set a dictionary or list to a cookie and get it properly in Django?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
  • https://stackoverflow.com/questions/20907420/javascript-problems-parsing-document-cookie-json-object – Jisson Jul 04 '23 at 06:52
  • https://stackoverflow.com/questions/17355358/how-to-specify-delimiter-for-multi-value-cookie-in-django – Jisson Jul 04 '23 at 06:53

0 Answers0