Danio
Danio

Reputation: 1114

How can I create session- or cookie-based user identity in Django?

In my Django web app every user must register before entering. I want to let newcomers skip this process for convenience at first and play with the app before they decide to create an account. Users' actions results are persisted in relational DB, so even if I don't want to save their identity, I must have some kind of "user" object to consistently persist their data from the beginning.

So I thought that whenever a new user comes to the website and he is not authenticated, I will create a fake user in DB for and identify him by the session/cookie.

When user decides to create an account, the "fake" user would be modified to match his registration data.

How and when to create this kind of user? Is this is a good approach?

Upvotes: 0

Views: 692

Answers (1)

SydHenry
SydHenry

Reputation: 83

I am not sure if this is the best option, but you could use the AbstractBaseUser and add a session_id to the user. You would have to make the other fields not required, like username and password. Then you could do something like this:

from django.contrib.auth import login
from .models import MyUser

def home_view(request):
    if not request.user.is_authenticated():  # user not logged in
       user, is_new = MyUser.objects.get_or_create(session_id=request.session.session_key)  # Make or get the user
       login(request, user)  # Log them in
    ###

That should bind the session_id to a user, and if that user is visiting the site a second time, it would keep their previous info and not make a new user for them. You might get a lot of orphaned users this way, for example, when someone has logged out, when they revisit the site they will create a new user and then login as there real account. You might be able to have disable cascade on delete for the session_id so that the user is not deleted when they log out. You could also just set the session_id to None and that should fix that issue.

Upvotes: 1

Related Questions