Search code examples
djangodjango-modelsdjango-viewsdjango-templatesdjango-filter

Django view template can't show model data


I defined a Model called Visit. There are several models.

In models.py

class Visit(models.Model):
    case = models.ForeignKey(Case, on_delete = models.CASCADE)
    location = models.ForeignKey(Location, on_delete = models.CASCADE)
    date_from = models.DateField()
    date_to = models.DateField()
    category = models.CharField(max_length = 20)

Then, I made a view template. It is to view all the visits made by a specific case. So that if the url is "sth/visit/1", it shows all the visits of case with pk1.

in views.py

class VisitView(TemplateView):
    template_name = "visit.html"
    def get_context_data(self, **kwargs):
        case_pk = self.kwargs['case']
        context = super().get_context_data(**kwargs)
        context['visit_list'] = Visit.objects.filter(case = case_pk)
        print("context[visit_list]: ",context['visit_list'])

I printed the context['visit_list'] in the console for url "sth/visit/1", it shows

context[visit_list]:  <QuerySet [<Visit: Visit object (1)>, <Visit: Visit object (2)>]>

for url "sth/visit/2", it shows

context[visit_list]:  <QuerySet [<Visit: Visit object (3)>]>

so I assume up to this moment, it works. but in the html document

<ul>
{% for visit in visit_list %}
  <li>[{{visit.date_from }}] {{ visit.date_to }} </li>
{% empty %}
  <li>No visit yet.</li>
{% endfor %}
</ul>

it shows no visit yet. for both 1 and 2. No error message. Just No visit. May I know what's the problem? Thank you very much please help TOT. I have been stucking here for several hours.


Solution

  • Yes because you are not returning the context to the template, so the context variables cannot be accessed

    class VisitView(TemplateView):
        template_name = "visit.html"
        def get_context_data(self, **kwargs):
            case_pk = self.kwargs['case']
            context = super().get_context_data(**kwargs)
            context['visit_list'] = Visit.objects.filter(case = case_pk)
            print("context[visit_list]: ",context['visit_list'])
            return context