Django: Setting Cookie and returning a rendered template – an example

While trying to figure out how to set cookies with Django (something I’ve been lucky enough to not have to do) I was of course searching “How to set a cookie with Django” this was the first result I found. Now that’s a great link and all, and it points to the relevant Django Docs.

However, there was a particular example missing. Returning a rendered template, with a cookie. Fortunately, it didn’t take long to figure it out, but I felt the fact that an exact example of this was missing as a little annoying. So for anyone else wondering “How do I return a rendered template AND set a cookie” here’s an example.

from django.shortcuts import render

def my_view(request):
    response = render(request, 'index.html')
    response.set_cookie('my_cookie', 'Here is my cookie!')
    return response

With any luck this will help at least one other person out there!

Of course, please read up the set_cookie and set_signed_cookie docs for more info on what you can do here.