Thursday, May 5, 2016

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

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" <shaukatali110@gmail.com>
To: "Django users" <django-users@googlegroups.com>
Sent: Thursday, May 5, 2016 3:30:50 AM
Subject: Django 1.9.5 Cookies. how can I set and display them?

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.

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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.

No comments:

Post a Comment