pythondjangodjango-custom-user

There Are Some Basics I Need To Understand Regarding Python Custom User Models


I wanted to delete a user. After a bit of struggling I ended up with:

views.py

the_user = get_user_model()

@login_required
def del_user(request):
    email = request.user.email
    the_user.objects.filter(email=email).delete()
    messages.warning(request, "bruker slettet.")
    return redirect("index")

But I really do not understand the following line:

email = request.user.email.

And why not?

email = request.the_user.email

Is this because the user is referring to the AbstractBaseUser?


Solution

  • The .user attribute is set by the AuthenticationMiddleware [Django-doc]. It thus checks the session variables for a key named _auth_user_id, and if that contains the primary key of a user, it can fetch the corresponding user object (based on the user model you pick).

    It thus has nothing to do with the name of the model (the_user is by the way not a good name, since classes are written in PascalCase), the name is always .user, or .auser if you want to fetch it in an asynchronous manner.

    The .user object is also fetched lazily: as long as you do not need to access an attribute of request.user, or make a method call, or something else, it is not fetched.