Manish Shah
Manish Shah

Reputation: 401

How to pass a value to the template in class based views in django?

I want to send a value of a variable to a PostDetail template, Here's the function of the views.py file

class PostDetailView(DetailView):
    model = Post
    def get_object(self):
        obj = super().get_object()
        obj.view_count += 1
        obj.save()
        return obj

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        texts = self.object.content
        Read_Time=get_read_time(texts)
        print(Read_Time)
        return context

Here's the output of the terminal:-

[04/Sep/2020 19:29:04] "GET /post/this-blog-contains-an-image-with-it/ HTTP/1.1" 200 6089
0:02:00
[04/Sep/2020 19:29:24] "GET /post/this-blog-contains-an-image-with-it/ HTTP/1.1" 200 6089

I want to send the 0:02:00 to my template, How can I make this happen?

Upvotes: 0

Views: 440

Answers (1)

JPG
JPG

Reputation: 88439

I would prefer to make a method in the Post model as

class Post(models.Model):
    # your fields
    
    def read_time(self):
        return get_read_time(self.content)

Then you can access the read time in the template by

{{ object.read_time }}

Upvotes: 1

Related Questions