There is some basics I do not understand here regarding custom user models

I wanted to delete a user. After a bit of struggeling I ended up like this: 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. In the line

email = request.user.email.

Why is it not

email = request.the_user.email

There is some basics I do not understand here regarding custom user models. Is this because the user is refering to the AbstractBaseUser?

Please excuse me for asking this.

request is an instance of an HttpRequest object. It represents the current received request. The AuthenticationMiddleware authenticates the user that made the request (based on cookies or however you have configured it) and adds the request.user attribute to it, so your code can get who the current user is that made the request.

What you call the_user is the User model class. That's an arbitrary name you gave to a variable in your code.

FYI, the request.user object is already a full fledged User instance, which already has a delete method. You don't need to find the same user again via the the_user model class, you can just do:

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

The .user attribute is set by the AutenticationMiddleware [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.

Вернуться на верх