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



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.


Leave a comment