Kaleab Woldemariam
Kaleab Woldemariam

Reputation: 2993

How to pass database queryset objects from class based views to templates in Django 2.0

I am building a web app.I am trying to pass a queryset from a class based view to templates as variables in Django 2.0. But the variables were not displayed at http://localhost:8000/joblist/. Other text are displayed on this url routing, but the queryset objects are not displayed as variables on the page. The models.py and the database work fine, and the database is populated with ~10k records. What am i missing? I would also like to know the advantages of class based views over function based views in simple words. Thank you. My views.py:

from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import ListView,DetailView
from joblist.models import Jobs

def index(request):
    context = {}
    html = TemplateResponse(request,'welcome.html',context)
    return HttpResponse(html.render())

class JobList(ListView):
    model=Job
    context_object_name = 'job_title'
    queryset=Job.objects.all()
    template_name = 'job_list.html'

class JobDetail(DetailView):

    model = Job
    context_object_name = 'job_detail'
    queryset = Job.objects.all()
    template_name = 'job_detail.html'

My template: joblist.html

{% extends 'welcome.html' %}
<h1> Job Title </h1>

<ul>
    {% for job in object_list %}
        <li>{{ job_title }}</li>
    {% endfor %}
</ul>

Upvotes: 1

Views: 1461

Answers (3)

Mahfuzur Rahman
Mahfuzur Rahman

Reputation: 524

You have to modify your code as below:

<ul>
  {% for job in job_title %}
    <li>{{ job.model_field_name }}</li>
  {% endfor %}
</ul>

Upvotes: 0

Mahfuzur Rahman
Mahfuzur Rahman

Reputation: 524

You may try this code for iterating context_object_name in list. Thanks

 <ul>
        {% for job in job_title %}
            <li>{{ job.model_field_name }}</li>
        {% endfor %} 
 </ul>

Upvotes: 1

wobbily_col
wobbily_col

Reputation: 11891

You have set the context_object_name to "job_title", so thats what you should use in the template, not "object_list" which is the default. job_list would seem a more sensible name.

<ul>
    {% for job in job_title %}
        <li>{{ job }}</li>
    {% endfor %} 
</ul>

Upvotes: 3

Related Questions