Mathieu Dhondt
Mathieu Dhondt

Reputation: 8934

Session data lost after a HttpResponseRedirect

I have this redirect view that sets session variables. But it's as if the session is flushed before the view that is being redirected to is called, as the whole session is empty there.

(Btw, this is the real code, I've cut stuff to find the cause but still can't find it).

class ActivateUserView(RedirectView):
    def get(self, request, *args, **kwargs):
        # activates user and redirects to listing
        listing = Listing.objects.get(id=2)
        request.session['test'] = 'icle'
        print("Session set to: ", request.session.get('test', "Nothing!"))
        return HttpResponseRedirect(reverse('listing-detail', kwargs={'pk': listing_pk, 'slug': listing.slug}))

The view the above is redirected to:

class ListingDetailView(TemplateView):
    template_name = "frontend/detail.html"

    @method_decorator(ensure_csrf_cookie)
    def get(self, request, *args, **kwargs):
        print("Session data: ", request.session.get('test', "Nothing!"))
        return super(ListingDetailView, self).get(request, *args, **kwargs)

In the console, I get:

Session set to:  icle 
Session data:  Nothing!

I've checked with django-debug-toolbar, raising Exceptions here and there, and somewhere between the redirect call and the view, all session data is deleted.

Upvotes: 4

Views: 3816

Answers (1)

Mathieu Dhondt
Mathieu Dhondt

Reputation: 8934

Setting SESSION_COOKIE_SECURE to False (in my dev settings) solved the issue. I was using a local, non-https dev environment.

Upvotes: 2

Related Questions