0

I am trying to extend the user model in django by using a Client model (this might not be the ideal way, but that boat has sailed). When I try to access a user record in a template I get the error:

No Client matches the given query

models.py

class Client(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

views.py

def update_client_details(request):
    if request.user.is_authenticated:
        user = request.user
        # print('pk', user.pk)
        client = get_object_or_404(Client, pk=user.pk)

If I print the user.pk I see what I expect.

Why doesn't it return an object?

Psionman
  • 3,084
  • 1
  • 32
  • 65

3 Answers3

1

Because you are using user.pk in get_object_or_404(Client, pk=user.pk) as it will try to find pk in Client model but In client model there where no any data available as per given primary key in get_object_or_404(Client, pk=user.pk) because this pk is user's pk.

So, if you want to get object as per user the you have to write as below...

client = get_object_or_404(Client, user=user)

Or you can use as simple way...

client_obj = Client.objects.get(user=request.user)
MK Patel
  • 1,354
  • 1
  • 7
  • 18
0

Because, you queried on Client model with User model id. you can use this query

client = get_object_or_404(Client, pk=user.pk)

instead of

client = get_object_or_404(Client, user=user)

If you want to check whether any client exist related with request.user you can use following queries:

client = Client.objects.filter(user=request.user).first() 
# this query returns None if there is no client related with your user.
if client:
    #your update processes
else:
    # your client not exist commands

you can use also hasattr method. There is a sample here

kamilyrb
  • 2,502
  • 3
  • 10
  • 25
0

Using this answer I realised that I needed to add:

profile, created = Profile.objects.get_or_create(user=request.user)

to views.py

So views.py now looks like:

def update_client_details(request):
    if request.user.is_authenticated:
        user = request.user
        profile, created = Profile.objects.get_or_create(user=request.user)

and I have access to user and profile data

The profile for a user is created if it doesn't exist

Psionman
  • 3,084
  • 1
  • 32
  • 65