Home > Back-end >  Any idea why contexts are not showing in template?
Any idea why contexts are not showing in template?

Time:10-08

So, I have this two function in my views.py

class TheirDetailView(DetailView):
    model = List
def listcomments(request): 
    modell = Review.objects.all()
    return render(request, 'app/list_comment.html', {'model' : modell})

And have these two paths set in my apps urls

    path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'),
    path('comment/',views.listcomments, name='ListComments'),

So I have two templates list_detail.html & list_comment.html

Here in list_detail.html I have included list_comment.html (just the comment section is there in list_comment.html)

In my list_detail.html

..
...
....
<div  id="comments-id">
        <div class = "commentscarrier">
            <div ><p>Comments(3)</p></div>
            <hr>
            {% include "app/list_comment.html" %}
...
..

In my list_comment.html

{% load static %}
{% for i in model %}
<div ><p >{{i.user.username}}
    </p></div>
    <div ><p>{{i.comment}}</p></div>
    </div>
{% endfor %}

In my models.py

class Review(models.Model):
    user = models.ForeignKey(User, models.CASCADE)
    List = models.ForeignKey(List, models.CASCADE)
    comment = models.TextField(max_length=250)
    rate = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.comment)
class List(models.Model):
    title = models.CharField(max_length=65)
    genre = models.ManyToManyField('Genre')
    creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True)
    posted = models.DateTimeField(auto_now_add=True)
    content = RichTextField(null=True,default=' ')
    type = models.CharField(max_length=10,default="Movie")
    slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True)

I have created 5 objects of Review model manually in admin. So that should show in my template. But its not showing anything. I am guessing I must have been messed up in my urls. But cant exactly figure out what. Sorry if my question is too immature. Beginner here.

CodePudding user response:

With your TheirDetailView, the attribute model of the class doesn't mean that there will be a context variable of the same name available in the template. Instead, what will be available in the context is the variable object (its value will be the one List instance that is fetched for the given slug). See here.

CodePudding user response:

I got this answer from reddit

User - stratified_n_fold

So you are using class based views. Okay update your code with this piece of code

class TheirDetailView(DetailView):

model = List

def get\_context\_data(self, \*\*kwargs):        

context = super().get\_context\_data(\*\*kwargs)          

modell = Review.objects.all() 

context\["model"\] = modell        

return context
  • Related