Search code examples
djangodjango-authentication

Django multiple users login and logout


Two users of the same type login. When one of the users changes the tab, now the user is the one who logged in last ({{ user.username }} changes).

The more major issue for me is that once one of them logout, the other logs out automatically. Basically, there is no two users, there is only one at a time, the user who logged last.
Also, all the views are @login_required.

@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('login'))


def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            login(request, user)
            return HttpResponseRedirect(reverse('success_page'))
        else:
            return render(request, 'login.html')
    else:
        return render(request, 'login.html')

In settings.py:

SESSION_COOKIE_AGE = 24*60*60
LOGIN_URL = '/login/'

My basic user form:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignUpForm(UserCreationForm):
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2', )

My question is how I can have multiple users logged in at a same time in a Django application.


Solution

  • Django uses sessions to manage users. Basically, when a user logs into the Django webiste, the Django backend puts a cookie in the users browser which identifies the browser as the user that just logged in. Django (and basically every other framework/implementation) will only allow one of these user cookies per session.

    So if you were to somehow log in again without logging out, it would simply override the current user cookie and effectively log out the previous user.