S
S
Sergey Eremin2014-10-07 00:03:20
Django
Sergey Eremin, 2014-10-07 00:03:20

Why don't cookies work under Pythom/Django?

Help a beginner. Something I don’t even understand why it doesn’t work:
View:

from django.http import HttpResponse
from django.shortcuts import render_to_response

def main_init ( request ) :

    if "NumVisit" in request.COOKIES:
        # стоят куки, и это не первый визит
        NumViz = request.COOKIES["NumVisit"]
        NumViz = int( NumViz ) + 1
    else:
        # куки не стоят
        NumViz = 0

    dimention_to_template = { 'NV': NumViz }      # словарь, для передачи шаблону
    return render_to_response( "index.html" , dimention_to_template ).set_cookie ("NumVizit", str( NumViz )  )

Well, the simplest template "index.htnl":
<p>{{ NV }}</p>
Doesn't work. At the same time, Django cookie token hangs up properly. But my cookie, judging by the Request information, does not hang up ...

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Eremin, 2014-10-10
@Sergei_Erjemin

It actually works like this:

from django.shortcuts import render

def main_init ( request ) :
    NumViz = 0
    if "NumVisit" in request.COOKIES:
        # стоят кукии, и это не первый визит
        NumViz = request.COOKIES["NumVisit"]
        NumViz = int( NumViz ) + 1

    dimention_to_template = { 'NV': NumViz }      # словарь, для передачи шаблону
   
    return render( request, "index.html", dimention_to_template ).set_cookie( "NumVisit", NumViz )

Those. through render_to_response cookies are not hung up, but through just render - easily

S
Singularity, 2014-10-07
@Singularity

Nalo get an object response and set him:

def view(request):
  response = HttpResponse( 'blah' )
  response.set_cookie( 'cookie_name', 'cookie_value' )
  return response

O
overmes, 2014-10-07
@overmes

the code is just awful
and doesn't work because set_cookie returns None

A
alternativshik, 2014-10-07
@alternativshik

Read PEP08 already! set_cookie is called on response as above...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question