Bharani Priya
Bharani Priya

Reputation: 11

unable to output cookie value in django

My view.py

def search(request):
    res = HttpResponse('Setting Response');
    res.set_cookie("name","abcd")
    return render_to_response("search.html", {"res":res})

My search.html

<html>
<body>
<h1>{{res.COOKIES.name}}</h1>
</body>
</html>

Even {{request.COOKIES.name}} is also not working. I am unable to get value "abcd" it is giving " " (empty string)

Please help me in this regard

Upvotes: 1

Views: 2417

Answers (3)

Serhii Holinei
Serhii Holinei

Reputation: 5864

try this:

from django.shortcuts import render
...
return render(request, "search.html", {"res":res})

so the request instance will be available on the template

UPDATE:

If your goal is to set a cookie and then retrieve it on a template you can do next:

from django.shortcuts import render

def search(request):
    response = render(request, "search.html")
    # render function returns a HttpResponse object
    response.set_cookie("name","abcd")
    return response

Then on a template:

{{ request.COOKIES.name }}

Solution came from here

Upvotes: 4

Rohan
Rohan

Reputation: 53326

You should try to get cookie in the view and pass in the template or pass request variable to the template.

Another way is to enable request context processor so that request variable is available by default in the template.

Upvotes: 0

Jure C.
Jure C.

Reputation: 3080

request variable is not automatically available to your views.

return render_to_response("search.html", {"request":request})

Upvotes: 1

Related Questions