Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display Model data in a Django Template

I am new to Django. I am trying to display data from my Project model in my index view, using a template. I tried my best to structure this app similar to the polls app. I'm not sure what I am doing wrong. I am using python 2.7, and django 1.8.6

Here is my url:

from django.conf.urls import url

from . import views

app_name = 'project'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]

Here is my Model:

import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.auth.models import User
from django.utils import timezone


@python_2_unicode_compatible  # only if you need to support Python 2
class Contractor(models.Model):
    #project
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=100, blank=True)
    phone = models.CharField(max_length=14, blank=True)
    city = models.CharField(max_length=60, blank=True)
    state = models.CharField(max_length=2, blank=True)
    created_by = models.ForeignKey(User, related_name='Contractor_created_by')
    created_date = models.DateTimeField()
    modified_by = models.ForeignKey(User, related_name='Contractor_modified_by')
    modified_date = models.DateTimeField()

    def __str__(self):
        return self.name

@python_2_unicode_compatible  # only if you need to support Python 2
class Project(models.Model):
    name = models.CharField(max_length=50)
    jobNumber = models.CharField(max_length=8)
    shopOut = models.DateTimeField(null=True)
    shopIn = models.DateTimeField(null=True)
    delivery = models.DateTimeField(null=True)
    job1 = models.CharField(max_length=50, null=True)
    job2 = models.CharField(max_length=50, null=True)
    job3 = models.CharField(max_length=50, null=True)
    contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, default=101)
    created_by = models.ForeignKey(User, related_name='Project_created_by')
    created_date = models.DateTimeField(auto_now_add=True)
    modified_by = models.ForeignKey(User, related_name='Project_modified_by')
    modified_date = models.DateTimeField(auto_now=True)
    def __str__(self):
        return self.name
    def save(self, *args, **kwargs):
        if not self.id:
            self.created_by = User.objects.get(id=1)
            self.modified_by = User.objects.get(id=1)
            super(Project, self).save(*args, **kwargs)
            year = datetime.datetime.now().year
            self.jobNumber = '{}{:04d}'.format(year, self.id)
        self.modified_by = User.objects.get(id=1)
        super(Project, self).save(*args, **kwargs)

Here is my View:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone

from .models import Project

# Create your views here.
class IndexView(generic.ListView):
    model = Project
    template_name = 'project/index.html'

    def get_queryset(self):
        return Project.objects

class DetailView(generic.DetailView):
    model = Project

Here is my Template:

{% load staticfiles %}
<h1>Projects</h1>
<ul>
{% for projects in project.get_queryset %}
    in for loop
    <!-- <li><a href="{% url 'projects:detail' projects.id %}">{{ projects.name }}</a></li> -->
    <li><a href="#">Test</a></li>
{% endfor %}

</ul>
end of list

When I go to the page I get a h1 Project, an empty ul, and a line that says 'end of list'

like image 841
user908759 Avatar asked Jan 28 '16 20:01

user908759


People also ask

What is model template view in Django?

The MVT (Model View Template) is a software design pattern. It is a collection of three important components Model View and Template. The Model helps to handle database. It is a data access layer which handles the data. The Template is a presentation layer which handles User Interface part completely.

How you can pass dynamic data in Django?

Using Views and Django Template we can display data in the template. There are lots of Django Template Tags and Filter for displaying data dynamically. We can pass the Model data to view for rendering it in the template.


2 Answers

In your get_queryset, you should return Project.objects.all().

In your template, you don't need to do project.get_queryset, the get_queryset method is called for you and the values are passed to the template as object_list and <objectname>_list, along with other parameters. In your case, the object is Project so there should be a project_list variable too along with object_list.

You can do:

{% for project in project_list %}
    <li><a href="{% url 'projects:detail' project.id %}">{{ project.name }}</a></li>
{% endfor %}

Or:

{% for project in object_list %}
    <li><a href="{% url 'projects:detail' project.id %}">{{ project.name }}</a></li>
{% endfor %}

You can read more about it here: https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-display/#listview

like image 125
masnun Avatar answered Sep 22 '22 12:09

masnun


Your get queryset doesn't return a query set at the minute, currently its just returning a related manager. you should make it return a queryset...

def get_queryset(self):
    return Project.objects.all()  # added all
like image 44
Sayse Avatar answered Sep 19 '22 12:09

Sayse