realpython / book2-exercises

Book 2 -- Exercises for the book
168 stars 203 forks source link

Incrementing before declaring #62

Closed ni8mr closed 7 years ago

ni8mr commented 8 years ago

At chapter 27, while we are adding view counts to bloggy app, we have the following code-

def post(request, post_url):
    single_post = get_object_or_404(Post,
    title=post_url.replace('_', ' '))
    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)) 

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 -

single_post.views += 1     # incrementing the number of views
mjhea0 commented 8 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))
ni8mr commented 8 years ago

@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()
ni8mr commented 8 years ago

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.

mjhea0 commented 8 years ago

:+1:

mjhea0 commented 7 years ago

Updated in v 2.0 of the courses. Coming week of 12/19/2016. https://github.com/realpython/about/blob/master/changelog.csv