# This view is for displaying a list of all the add kids in cards
class KidsListView(LoginRequiredMixin, ListView):
template_name = 'SmartSpend/kids.html'
model = Kid
def get_queryset(self):
print(f"This is the value {Kid.objects.filter(parent=self.request.user)}")
return Kid.objects.filter(parent=self.request.user)
class KidWalletView(TemplateView):
template_name = 'SmartSpend/kid_wallet.html'
model = KidWallet
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
kid_id = self.kwargs['kid_id']
try:
context['kid_wallet'] = KidWallet.objects.get(account_owner__id=kid_id)
except KidWallet.DoesNotExist:
context['error_message'] = "No wallet found for this kid."
return context```
#A bug with accessing specific kids cards ids in the database
1 messages · Page 1 of 1 (latest)
{% extends "SmartSpend/layout.html" %}
{% load static %}
{% block head %}
{{ block.super }}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<link rel="stylesheet" href="{% static 'SmartSpend/styles.css' %}">
{% endblock %}
{% block body %}
<div class="col-xl-1 col-lg-4 col-md-6 m-t-30">
<div class="LIEYp">
<div class="xsm8L">
<div class="iQUEC">
<div><a href="{% url 'kid_profile' kid_wallet.account_owner.id %}" style="padding: 10px; align-items: center; justify-content: center; color: black; text-decoration: none;">Profile</a></div>
</div>
</div>
</div>
</div>
<div class="container my-5">
<div class="row">
<div class="col-md-6 mx-auto text-center">
<div><a href="{% url 'kid_wallet' kid_wallet.account_owner.id %}"></a> </div>
<img src="#" alt="Event Image" class="img-fluid rounded mb-4">
<h5>Hello, World!</h5>
{% if kid_wallet %}
<div><strong>Account owner:</strong> {{ kid_wallet.account_owner.first_name}} {{ kid_wallet.account_owner.last_name}}</div>
<div><strong>Wallet Number:</strong> {{ kid_wallet.wallet_number}}</div>
<div><strong>Balance:</strong> {{ kid_wallet.balance }}</div>
{% else %}
<div>{{ error_message }}</div>
{% endif %}
</div>
</div>
</div>
{% endblock %}```
Run this for me:
$ python manage.py shell
>>> from SmartSpend.models import KidWallet
>>> KidWallet.objects.get(account_owner__id=11)
```and show me the full output you get?
Ok!
Sorry for not providing more details about the bug, but I think your get the idea by reading the logic and the error message.
The parent is able to add kids and display them cards, but whenever I click on any of the kids particluer card to view their wallet, I get this error. Let me run shell.
It seems like a kid on id 11 doesn't exist?
>>> from SmartSpend.models import KidWallet
>>> KidWallet.objects.get(account_owner__id=11)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\SmartSpend Project\.venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "C:\SmartSpend Project\.venv\Lib\site-packages\djmoney\models\managers.py", line 207, in wrapper
queryset = func(*args, **kwargs)
File "C:\SmartSpend Project\.venv\Lib\site-packages\django\db\models\query.py", line 633, in get
raise self.model.DoesNotExist(
"%s matching query does not exist." % self.model._meta.object_name
)
SmartSpend.models.KidWallet.DoesNotExist: KidWallet matching query does not exist.```
Let me try query all the kids and check their ids?
>>> KidWallet.objects.all()
<QuerySet [<KidWallet: Parent Wallet ForeignKey: Owner: Full name: Phone number: +477474444 Home address: None Birthday: None OTP: None Wallet number: 150930923344 Balance: SEK0.00 Created at: 2025-10-26 10:28:44.734550+00:00 Account Owner: Parent: Full name: Phone number: +477474444 Home address: None Birthday: None OTP: None First Name: Connor Last Name: McDavid Birthday: 1997-01-13 Gender: Male Photo Link: Relationship: Parent Wallet Number: 983056583208 Balance: SEK0.00 Created at: 2025-10-31 13:42:42.774348+00:00>]>
>>>```
What
A KidWallet with an account_owner whose ID is 11 doesn’t exist, yes. So when your template tries to put a link to the “Profile”, the ID is empty, and it can’t generate the URL, so you get the error. You need to handle “no kid wallet found with that ID” more gracefully
It seems like the only kid which is Connor McDavid is being add for that parent and that's why this is the only kid that I'm able to view their wallet and profile, but not Ed Mylett, Sidney Crosby and the other one.
Aha
But my friend, why only Connor McDavid is the only one being linked to that parent and not the other 3 kids?
So this error check should be add in the KidWalletView right?
Yes. I would just raise a 404
Aha, because I'm already handling this part in the view context['error_message'] = "No wallet found for this kid." but yeah there should be an httpResponse with rendering the doesn't exist type of error 404
This should solve the issue then
class KidWalletView(TemplateView):
template_name = 'SmartSpend/kid_wallet.html'
model = KidWallet
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
kid_id = self.kwargs['kid_id']
try:
context['kid_wallet'] = KidWallet.objects.get(account_owner__id=kid_id)
except KidWallet.DoesNotExist:
"""context['error_message'] = "No wallet found for this kid."""
return HttpResponse("No wallet found for this kid.", status=404)
return context```
Didn't work actually
File "C:\SmartSpend Project\.venv\Lib\site-packages\django\template\context.py", line 291, in make_context
raise TypeError(
"context must be a dict rather than %s." % context.__class__.__name__
)
TypeError: context must be a dict rather than HttpResponse.```
Nope, you can’t return an HttpResponse from there. Try raising an Http404
Ok
I was Googling and searching how to use that Http404
Bingo
from django.http import HttpResponse, HttpResponseRedirect, Http404
class KidWalletView(TemplateView):
template_name = 'SmartSpend/kid_wallet.html'
model = KidWallet
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
kid_id = self.kwargs['kid_id']
try:
context['kid_wallet'] = KidWallet.objects.get(account_owner__id=kid_id)
except KidWallet.DoesNotExist:
raise Http404("No wallet found for this kid.")
return context```
Ok! Now getting this page instead of a bug error.
Page not found (404)
No wallet found for this kid.
Request Method: GET
Request URL: http://127.0.0.1:8000/post/kid_wallet/11/
Raised by: SmartSpend.views.KidWalletView```
It seem like kid id 11, 12, and 1 don't exist except for 8 which it does exist and it's the kid above Conor.
Ok! I just found out that the other kids are being add by the same logged-in parent, but they're not being linked or at least their wallets to the parent.
I mean I am storing the logged-in parent by saving whenever adding new kid
class AddKidsWizard(SessionWizardView):
location = os.path.join(settings.MEDIA_ROOT, 'kids')
file_storage = FileSystemStorage(location)
form_list = [("first_name", KidFirstForm),
("last_name", KidLastNameForm),
("birth_date", KidBirthDateForm),
("gender", GenderForm),
("relationship", RelationshipForm),
("photo_link", KidPhotoLinkForm)]
template_name = "SmartSpend/add_kids.html"
def done(self, form_list, form_dict, **kwargs):
user = self.request.user
first_name = form_dict['first_name'].cleaned_data['first_name']
last_name = form_dict['last_name'].cleaned_data['last_name']
birth_date = form_dict['birth_date'].cleaned_data['birth_date']
gender = form_dict['gender'].cleaned_data['gender']
relationship = form_dict['relationship'].cleaned_data['relationship']
photo_link = form_dict['photo_link'].cleaned_data['photo_link']
profile = Kid(parent=user, first_name=first_name, last_name=last_name, birth_date=birth_date, gender=gender, relationship=relationship, photo_link=photo_link)
profile.save()
generate_account(self.request, profile)
return HttpResponseRedirect(reverse("dashboard"))```
Ok! Querying those two models shows me that there multiple kids being add and stored in the Kid model, but the KidWallet model has only one kid which means other kids are being stored in the KidWallet model.
>>> Kid.objects.all()
<QuerySet [<Kid: Parent: Full name: Phone number: +477474444 Home address: None Birthday: None OTP: None First Name: Sidney Last Name: Crosby Birthday: 1987-01-20 Gender: Male Photo Link: Relationship: Parent>, <Kid: Parent: Full name: Phone number: +477474444 Home address: None Birthday: None OTP: None First Name: Connor Last Name: McDavid Birthday: 1997-01-13 Gender: Male Photo Link: Relationship: Parent>, <Kid: Parent: Full name: Phone number: +477474444 Home address: None Birthday: None OTP: None First Name: Tomas Last Name: Hertil Birthday: 1993-11-12 Gender: Male Photo Link: Relationship: Parent>, <Kid: Parent: Full name: Phone number: +477474444 Home address: None Birthday: None OTP: None First Name: Ed Last Name: Mylett Birthday: 1971-04-27 Gender: Male Photo Link: Relationship: Parent>]>
>>>```
Ben whenever I'm adding a new kid, I am saving the logged-in user in the parent Foreign Key field for each kid, I'm not sure why only one kid is being add but the rest get to be ignored?
KidWalletmodel is storing only one kid but not the rest
Oh! Here is what I found out.
In this
generate_accountfunction, I'm using a try-except block to check if a KidWallet already exists for the account owner. If it does, I don’t create a newKidWallet. This might be why only Connor McDavid has aKidWallet.
# This view is responsible for generating a SmartSpend random account whenever a parent adds a kid account/wallet to their account
def generate_account(request, kid):
user = request.user
try:
account_owner = user.account_owner.get()
kid_wallet = KidWallet.objects.get(parent_wallet=account_owner)
kid = Kid.objects.get(pk=kid.pk) # When I use pk=kid.pk, I'm filtering for the Kid object with the same primary key as the kid parameter. This ensures I'm working with the correct Kid object.
except KidWallet.DoesNotExist:
random_number = "".join(random.choice(string.digits) for i in range(12))
kid_wallet = KidWallet.objects.create(parent_wallet=account_owner, account_owner=kid, wallet_number=random_number, balance=0.0, balance_currency="SEK")
kid_wallet.save()
print(f"This is the kid_wallet owner: {kid_wallet.account_owner} wallet number: {kid_wallet.wallet_number} balance: {kid_wallet.balance} currency: {kid_wallet.balance_currency}")
return HttpResponseRedirect(reverse("dashboard"))```
So maybe removing the try-except block would solve the issue