Django 1.9.5 Cookies. how can I set and display them?

76 views
Skip to first unread message

shaukat ali

unread,
May 5, 2016, 6:48:42 AM5/5/16
to Django users
Hey Guys

I have a website which do some calculations in different ways. It will use COOKIES. So how can I set and display the COOKIES? So can you guys guide me.

My code id:

response = HttpResponse('true')
DEFAULT_DATE_FORMAT = 'MM/dd/yyyy'
# Here I am setting my cookies
response.set_cookie('DEFAULT_DATE_FORMAT', DEFAULT_DATE_FORMAT)

# Here I am displaying my cookies
mycookies = request.COOKIES['DEFAULT_DATE_FORMAT']
print(mycookies)

I does not display any error message but it just stop my code execution.
NOTE: My browser's cookies are enabled.

Kristofer Pettijohn

unread,
May 6, 2016, 12:28:54 AM5/6/16
to django...@googlegroups.com
I recommend looking at the Django documentation.  You set cookies via request.session.set().  And you typically do not modify the response value returned from HttpResponse() unless you are doing more advanced things.

For example (straight from the docs):

def post_comment(request, new_comment):
    if request.session.get('has_commented', False):
        return HttpResponse("You've already commented.")
    c = comments.Comment(comment=new_comment)
    c.save()
    request.session['has_commented'] = True
    return HttpResponse('Thanks for your comment!')

or:

def login(request):
    m = Member.objects.get(username=request.POST['username'])
    if m.password == request.POST['password']:
        request.session['member_id'] = m.id
        return HttpResponse("You're logged in.")
    else:
       return HttpResponse("Your username and password didn't match.")

or if you want to delete a cookie:

def logout(request):
    try:
        del request.session['member_id']
    except KeyError:
        pass
    return HttpResponse("You're logged out.")



From: "shaukat ali" <shauka...@gmail.com>
To: "Django users" <django...@googlegroups.com>
Sent: Thursday, May 5, 2016 3:30:50 AM
Subject: Django 1.9.5 Cookies. how can I set and display them?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/cff8d681-5be5-4754-939e-2294f3cf71b3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages