1

I wanted to pass variables with the User information, that is linked to a Clients model through a OneToOneField to the django.contrib.auth.models, onto the base.html file.

So, I created a context_processors.py with the following code

from django.contrib.auth.models import User

    def userData(request):  
        user = request.user
        u = User.objects.get(username=user)
        us = u.clients.first_name
        uv = u.clients.avatar
        return {
            'u': u,
            'us': us,
            'uv': uv
        }

Everything was working fine, until I logged out.

When I try to login again, I get the accounts/login url and get a

DoesNotExist at /accounts/login/
User matching query does not exist.
overclock
  • 585
  • 3
  • 20
  • 1
    Does this answer your question? [How do I get the object if it exists, or None if it does not exist?](https://stackoverflow.com/questions/3090302/how-do-i-get-the-object-if-it-exists-or-none-if-it-does-not-exist) – justinas Feb 18 '20 at 11:38
  • Based on your code, it looks like a `User` can have *multiple* `Client`s? – Willem Van Onsem Feb 18 '20 at 11:39
  • @WillemVanOnsem I am using a OneToOneField on my `models.py`. So, I believe it can't. By again, I am new to Django/Python. – overclock Feb 18 '20 at 11:40
  • @JoãodeSousa: yes then it is indeed impossible. But then it might be better to rename the model to `Client` (models normally are given *singular names*, or the related name to `client`). Since now it "hints" that it returns multiple ones (since `clients` is plural). – Willem Van Onsem Feb 18 '20 at 11:42

1 Answers1

3

Well your request.user is already a User, so it makes not much sense to fetch it again.

You can simply check if the user is logged in:

def userData(request):
    if request.user.is_authenticated:
        return {
            'u': request.user,
            'us': request.user.clients.first_name,
            'uv': request.user.clients.avatar,
        }
    return {}

Note: the name clients is plular, so that suggests a collection of Clients. Normally model names are singular (so Client instead of Clients), and the related name of a OneToOneField should, if you specify it yourself, be singular as well.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555