Closed ni8mr closed 7 years ago
What's the value of single_post
?
def post(request, post_url):
single_post = get_object_or_404(Post,
title=post_url.replace('_', ' '))
print( single_post)
single_post.views += 1 # increment the number of views
single_post.save() # and saving it
t = loader.get_template('blog/post.html')
c = Context({'single_post': single_post, })
return HttpResponse(t.render(c))
@mjhea0 The values of single_post are the objects we get from querying database using get_object_or_404(). So they are the blog posts. But we didn't define any view attribute under Post class (i.e. post table) in the models.py. Here is the model -
class Post(models.Model):
created_at = models.DateTimeField(auto_now_add = True)
title = models.CharField(max_length=100)
tag = models.CharField(max_length=20, blank=True, null=True)
image = models.ImageField(upload_to = "images", blank=True, null=True)
content = models.TextField()
I have eliminated the error by defining a views attribute for Post class in the model. My final model (for now) is -
class Post(models.Model):
created_at = models.DateTimeField(auto_now_add = True)
title = models.CharField(max_length=100)
tag = models.CharField(max_length=20, blank=True, null=True)
image = models.ImageField(upload_to = "images", blank=True, null=True)
content = models.TextField()
views = models.IntegerField(default=0)
I have checked the code from the repository after this. The views attribute is there. It seems you have forgot to mention about defining it in the book.
:+1:
Updated in v 2.0 of the courses. Coming week of 12/19/2016. https://github.com/realpython/about/blob/master/changelog.csv
At chapter 27, while we are adding view counts to bloggy app, we have the following code-
Here we are incrementing single_post.views before declaring it. So while i am running the code, i am having an AttributeError, which is tracing back to this line -