如何在Django模板中显示模型数据 [英] How to display Model data in a Django Template

查看:105
本文介绍了如何在Django模板中显示模型数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手。我正在尝试使用模板在索引视图中显示来自我的Project模型的数据。我尽力构造类似于民意调查应用程序的该应用程序。我不确定自己在做什么错。我正在使用python 2.7和Django 1.8.6

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

这是我的网址:

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'),
]

这是我的模型:

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)

这是我的视图:

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

这是我的模板:

{% 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

当我转到页面时,我得到一个h1项目,一个空白ul,并在一行中显示列表结尾

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

推荐答案

在您的 get_queryset ,您应该返回 Project.objects.all()

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

在模板中,您无需执行 project.get_queryset ,即会为您调用get_queryset 方法,并将值作为 object_list < objectname> _list 传递给模板code>,以及其他参数。在您的情况下,对象是 Project ,因此也应该有一个 project_list 变量以及 object_list

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.

您可以执行以下操作:

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

或:

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

您可以在此处了解更多信息: https://docs.djangoproject.com/zh-CN/1.9/ ref / class-based-views / generic-display /#listview

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

这篇关于如何在Django模板中显示模型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆