Search code examples
pythondjangocookiesdjango-generic-views

Setting test cookie in generic view in Django


I want to set a test cookie in my CreateView and be able to get a test result in form_valid function (after sending a form).

Where should I put the code responsible for setting the cookie?

self.request.session.set_test_cookie()

I tried to override get_form_kwargs and put it there, but it didn't work.

My code:

class MyView(CreateView):
    def form_valid(self, form):
        if not self.request.session.test_cookie_worked():
            pass
        else:
            pass

Solution

  • See the docs for test_cookie_worked:

    https://docs.djangoproject.com/en/1.6/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.test_cookie_worked

    "Due to the way cookies work, you’ll have to call set_test_cookie() on a previous, separate page request."

    Therefore I would suggest to set_test_cookie in the get method of the view:

    class MyView(CreateView):
        def get(self, request, *args, **kwargs):
            self.request.session.set_test_cookie()
            super(MyView, self).get(request, *args, **kwargs)
    
        def form_valid(self, form):
            if not self.request.session.test_cookie_worked():
                pass
            else:
                pass