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 views.py
file is exists in expenses_app
directory . And on the other hand , models.py
file is exists in userpreferences
directory . And expenses_app
, userpreferences
both are in same directory .
some code of views.py :
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
@login_required(login_url='/authentication/login')
def index(request):
categories=Category.objects.all()
expenses=Expense.objects.filter(owner=request.user)
paginator=Paginator(expenses,2)
page_number=request.GET.get('page')
page_obj=Paginator.get_page(paginator,page_number)
currency = UserPreference.objects.get(user=request.user).currency
context={
'expenses':expenses,
'page_obj':page_obj,
'currency':currency
}
return render(request,'expenses/index.html',context)
some code of userpreferences/models.py :
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)
currency=models.CharField(max_length=255,blank=True,null=True)
def __str__(self):
return str(User)+'s'+'preferences'
How can I solve this issue ?