How to set cookie in Django and then render template?

后端 未结 4 1901
慢半拍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: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
    

提交回复
热议问题