Somdip Dey
Somdip Dey

Reputation: 3386

How to add page count in the class of views.py without error [Django]

I have created a simple blog app using Django/Python.

I have the following views.py code:

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post

# Create your views here.
#def home(request):
#        return render(request, 'home.html', {})

class HomeView(ListView):
    model = Post
    template_name = 'home.html'
    ordering = ['-published_date']
    paginate_by = 9

class ArticleView(DetailView):
    model = Post
    model.post_view = model.post_view + 1
    model.save()
    template_name = 'article.html'

My models.py code looks as follows:

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from ckeditor_uploader.fields import RichTextUploadingField
from ckeditor.fields import RichTextField
import math

# Create your models here.
# https://stackoverflow.com/questions/29536180/django-blog-adding-published-date-field-to-new-posts-and-ability-to-login-as-non
class Post(models.Model):
    title = models.CharField(max_length=300)
    keywords = models.CharField(max_length=300, default="default keywords")
    author = models.ForeignKey('UserProfile', on_delete=models.CASCADE)
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(auto_now_add=True,
            blank=False, null=False)
    language = models.ForeignKey('LanguageCategory', on_delete=models.CASCADE)
    image = models.ImageField(upload_to='blog_images/', default='blog_images/image.png')
    body = RichTextField(blank=False, null=False)
    post_view = models.IntegerField(default=0, null=False, blank=False)

When I try to runserver I get the following error:

ine 15, in <module>
    class ArticleView(DetailView):
  File "/PATH/views.py", line 17, in ArticleView
    model.post_view = model.post_view + 1
TypeError: unsupported operand type(s) for +: 'DeferredAttribute' and 'int'

I am guessing that I am getting the aforementioned error because I am not updating the post_view of the Post class model properly in the views.py. How to modify the ArticleView class in views.py to update the post_view variable of the Post object properly to get count of the blog article?

Upvotes: 0

Views: 56

Answers (1)

JPG
JPG

Reputation: 88499

Override the get(...) method of the ArticleView class

class ArticleView(DetailView):
    model = Post
    template_name = 'article.html'

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        self.object.post_view += 1
        self.object.save()
        return response

Here, the self.object is the Post instance which is being retrieved.

Upvotes: 1

Related Questions