How do I deal with a null query in Django?

Viewed 103

So let me start with the registration process in my web page. The user would register first, and then right after registration, he/she is redirected to a page where the user has to input his/her personal info, such as self-introduction, full name, etc. When the user completes filling his/her personal info in, then the user will be redirected to home page.

So what I wanted to do is this: When the user tries to access home page, check if he/she is logged in. If yes, check if he/she has filled in the personal info. If no, redirect the user to register page. If the user has filled in (=matching query exists), redirect him/her to the home page. If not, redirect him/her to the personal info page, to fill the fields in.

And here's my code in views.py

def userHome(request):
    if request.user.is_authenticated:
        current_user = request.user

        if PersonalInfo.objects.get(authuser_id=current_user.id).exists():

            context = {
                'thisUser' : thisUser,
                'newSeed' : newSeed
            }
            return render(request, '/userhome.html', context)

        else: 
            return redirect('/inputpersonalinfo')

    else:
        return redirect('/register')

models.py

from django.db import models
from django.contrib.auth.models import User

class PersonalInfo(models.Model):
    objects = models.Manager()

    authuser = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'personalinfo', null=True, default=None)
    name = models.CharField(max_length=50)
    ...

I keep getting an error saying PersonalInfo matching query deos not exist. I do understand why this occurs, but can't think of the solution. Please help.

2 Answers

You have to use filter instead of get when you check if PersonalInfo exists:

PersonalInfo.objects.filter(authuser_id=current_user.id).exists()

get throws an error if there's no object matching the query. filter will return an empty queryset.

See the example in the documentation, and a question about get vs. filter

Even if the answer already provided works, I would avoid simply using exists() simply because I'm often likely to use the result of the query and exists() doesn't return the object. In your case I would rather do something like that:

try:
    info = PersonalInfo.objects.get(authuser_id=current_user.id)
    context = {
        'thisUser' : thisUser,
        'newSeed' : newSeed,
        'someinfo' : info.whatever
    }
    return render(request, '/userhome.html', context)
except PersonalInfo.DoesNotExist:
    return redirect('/inputpersonalinfo')
Related