Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created November 29, 2013 00:59
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmispelon/7700152 to your computer and use it in GitHub Desktop.
Save bmispelon/7700152 to your computer and use it in GitHub Desktop.
A Django CBV mixin to make setting cookies easier.
class CookieMixin(object):
"""
A CBV mixin that adds an `add_cookie` method on the view, allowing the user
to set cookies on the response without having direct access to the response
object itself.
Example usage::
class SomeFormView(CookieMixin, FormView):
...
def form_valid(self, form):
self.add_cookie('form_was_sent', True, max_age=3600)
return super(SomeFormView, self).form_valid(form)
"""
def __init__(self, *args, **kwargs):
super(CookieMixin, self).__init__(*args, **kwargs)
self._cookies = []
def get_cookies(self):
"""
Return an iterable of (args, kwargs) to be passed to set_cookie.
"""
return self._cookies
def add_cookie(self, *args, **kwargs):
"""
Al given arguments will be passed to response.set_cookie later on.
"""
self.cookies.append((args, kwargs))
def dispatch(self, request, *args, **kwargs):
"""
Get the response object from the parent class and sets the cookies on
it accordingly.
"""
response = super(CookieMixin, self).dispatch(request, *args, **kwargs)
for cookie_args, cookie_kwargs in self.get_cookies():
response.set_cookie(*cookie_args, **cookie_kwargs)
return response
@sunnyar
Copy link

sunnyar commented Oct 22, 2014

A minor change in 'add_cookie' method (Line # 31)
Should be -
self._cookies.append((args, kwargs))

@blackrosezy
Copy link

awesome 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment