Search code examples
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

  • 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")