mimo
mimo

Reputation: 2629

How to create an "empty" session in Django?

How can I create a session in Django, but without setting any specific variable?

I just need to send the session cookie to the client.

Upvotes: 3

Views: 811

Answers (2)

Henhuy
Henhuy

Reputation: 1164

In my app, I simply did:

request.session.save()

to create an (real) empty session...

Upvotes: 0

zepp133
zepp133

Reputation: 1610

As it stands, Django won't create a session ID/key unless you modify the request.session dictionary in some way. The following little "hack" is already enough to create a session:

request.session[None] = None

The most generic place to put this snippet would be a class-based view's dispatch() method. You can create a mixin to make things reusable:

class EmptySessionMixin:
    def dispatch(self, request, *args, **kwargs):
        request.session[None] = None
        return super().dispatch(request, *args, **kwargs)

class MyView(EmptySessionMixin, View):
    pass

Upvotes: 1

Related Questions