I have a very simple model and view py file for cats (trying to test out/learn basic features of django. However the cat's happiness status never really updated.
class Cats(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE)
name = models.CharField(max_length = 200)
description = models.TextField()
happiness = 6
def pet(self):
self.happiness = self.happiness+1
self.save()
from django.shortcuts import render, get_object_or_404
from .models import Cats
def cat_detail(request, pk):
cat = get_object_or_404(Cats, pk=pk)
return render(request, 'cats/cat_detail.html', {'cat': cat})
def cat_interact(request, pk, action):
cat = get_object_or_404(Cats, pk=pk)
pet = False
if(action == 1):
cat.pet()
pet = True
return render(request, 'cats/cat_interact.html', {'cat': cat, 'pet': pet})
action will always be 1 (that's the only current action possible). Inside the html file of both "detail" and "interact" I print out the happiness status of the cat. When I go to the interact page, the cat's happiness status is printed as 7 (since default/start happiness is 6). I expect this value (7) to be saved to the database and when I go to the detail page again it also prints 7. However, even after running the function cat.play() on the detail page it still prints 6, which is the default. Is the 7 never saved to the data base? is self.save() not working in this case? How should I change my code?
Your
happiness
is not connected to your database, you should wright it like thisthen this part
will save
happiness
to DB