How to set cookie in Django and then render template?

后端 未结 4 1878
慢半拍i
慢半拍i 2020-12-25 14:07

I want to set a cookie inside a view and then have that view render a template. As I understand it, this is the way to set a cookie:

def index(request):
            


        
相关标签:
4条回答
  • 2020-12-25 14:19

    The accepted answer sets the cookie before the template is rendered. This works.

    response = HttpResponse()
    response.set_cookie("cookie_name", "cookie_value")
    response.write(template.render(context))
    
    0 讨论(0)
  • 2020-12-25 14:21

    This is how to do it:

    from django.shortcuts import render
    
    def home(request, template):
        response = render(request, template)  # django.http.HttpResponse
        response.set_cookie(key='id', value=1)
        return response
    
    0 讨论(0)
  • 2020-12-25 14:29

    If you just need the cookie value to be set when rendering your template, you could try something like this :

    def view(request, template):
        # Manually set the value you'll use for rendering
        # (request.COOKIES is just a dictionnary)
        request.COOKIES['key'] = 'val'
        # Render the template with the manually set value
        response = render(request, template)
        # Actually set the cookie.
        response.set_cookie('key', 'val')
    
        return response
    
    0 讨论(0)
  • 2020-12-25 14:38
    def index(request, template):
        response = HttpResponse('blah')
        response.set_cookie('id', 1)
        id = request.COOKIES.get('id')
        return render_to_response(template,{'cookie_id':id})
    
    0 讨论(0)
提交回复
热议问题