title: Setting cookies within Django Middleware
body: <p>I would like to use Custom Django Middleware (Django 1.9) to check whether or not an anonymous user has accepted a site's terms &amp; conditions - I'll show the user a dialog if they've not yet clicked 'Agree'.</p>
  
  <p>I have no need to store this in the database and would prefer to simply use a Cookie. I have the following in <code>settings.py</code>:</p>
  
  <pre><code>MIDDLEWARE_CLASSES = [
      'django.middleware.security.SecurityMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      ...
      'myapp.middleware.app_custom_middleware.TermsMiddleware',]
  
  SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
  </code></pre>
  
  <p>I'm then trying something very rudimentary in TermsMiddleware - here I'm deliberately trying to modify the request <em>and</em> the response just to try to get it to work:</p>
  
  <pre><code>class TermsMiddleware(object):
  
      def process_request(self, request):
          request.session['myCookieKey'] = 'myCookieValue'
          request.session.save()
          return
  
      def process_response(self, request, response):
          request.session['myCookieKey'] = 'myCookieValue'
          request.session.save()
          return response
  </code></pre>
  
  <p>If I inspect the response in the browser, I see that <code>myCookieKey</code> isn't being set, so I think I've misunderstood how this should be written.</p>
  
  <p>Can I manipulate the session within middleware like this, having it take effect in the cookie sent in the response Django was going to send anyway? The documentation makes it sound like I should be able to:</p>
  
  <blockquote>
    <p>It should return either None or an HttpResponse object. If it returns
    None, Django will continue processing this request, executing any
    other process_request() middleware, then, process_view() middleware,
    and finally, the appropriate view. If it returns an HttpResponse
    object, Django won’t bother calling any other request, view or
    exception middleware, or the appropriate view; it’ll apply response
    middleware to that HttpResponse, and return the result.</p>
  </blockquote>
  
  <p>I've also seen the note in the documentation to use <code>SessionStore()</code> when outside of a view function. In theory I don't think I should need to do that here because I've got access to <code>request</code> (and <code>response</code>). I tried it anyway, and I still couldn't get it to work.</p>
  
  <p>Help much appreciated!</p>