UserPreference matching query does not exist.

When execute this line of code currency = UserPreference.objects.get(user=request.user).currency then it shows me an error . The error is :

userpreferences.models.UserPreference.DoesNotExist: UserPreference matching query does not exist.

for better understanding about the error, please see this image

And also file is exists in expenses_app directory . And on the other hand , file is exists in userpreferences directory . And expenses_app , userpreferences both are in same directory .

some code of :

from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from .models import Expense,Category
from django.contrib import messages
from django.core.paginator import Paginator
import json
from django.http import JsonResponse

from userpreferences.models import UserPreference

def index(request):


    currency = UserPreference.objects.get(user=request.user).currency    

    return render(request,'expenses/index.html',context)

some code of userpreferences/ :

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

# Create your models here.

class UserPreference(models.Model):

    user=models.OneToOneField(to=User, on_delete=models.CASCADE)
    def __str__(self):

        return str(User)+'s'+'preferences'

How can I solve this issue ?

1 Like


Django throws a DoesNotExist exception when it can’t find a match for your .get() query, in this case UserPreference.objects.get(user=request.user).currency.

Most likely the UserPreference table doesn’t have rows that match request.user

The solution I found was to add an expense directly and the reload and it worked as it was missing currency as it didn’t have an default currency eventhough this was a simple patch it is not a permanent solution so the permanent solution would be to change


this in an if else block to give it a default currency

if UserPreference.objects.filter(user = request.user).exists():
        currency = UserPreference.objects.get(user = request.user).currency
        currency = 'INR - Indian Rupee'

Hope This Helps.

1 Like


Great to hear you solved your issue. One thing that I think is nice to know, and it sure has helped me along the way, is using the DoesNotExist exception to your advantage which can simplify this code and reduce the the number of queries to one.

    currency = UserPreference.objects.get(user = request.user).currency
except UserPreference.DoesNotExist:
    currency = 'INR - Indian Rupee'

In short, the try except clause tries to get(user=request.user) an object matching your query. If there is no matching result it will raise the DoesNotExist exception and the except will catch it, executing the line of code after the except clause.

1 Like