Python 如何在 Django 模板中显示模型数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35071257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:57:15  来源:igfitidea点击:

How to display Model data in a Django Template

pythondjangodjango-templates

提问by user908759

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

我是 Django 的新手。我正在尝试使用模板在索引视图中显示来自我的项目模型的数据。我尽我最大的努力来构建这个类似于民意调查应用程序的应用程序。我不确定我做错了什么。我正在使用 python 2.7 和 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'

当我转到该页面时,我得到一个 h1 项目、一个空的 ul 和一行显示“列表结束”

采纳答案by masnun

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

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

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

在您的模板中,您不需要执行project.get_querysetget_queryset为您调用该方法并将值作为object_listand<objectname>_list以及其他参数传递给模板。在您的情况下,该对象Project应该project_listobject_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

您可以在此处阅读更多相关信息:https: //docs.djangoproject.com/en/1.9/ref/class-based-views/generic-display/#listview

回答by Shang Wang

You might want to try:

您可能想尝试:

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

object_listis the default name of queryset if you use ListView, you can change that by defining context_object_namein your view. Here's django doc about that.

object_list是 queryset 的默认名称,如果您使用ListView,您可以通过context_object_name在视图中定义来更改它。这是关于那个django 文档

回答by Sayse

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...

您的 get queryset 不会立即返回查询集,目前它只是返回相关的管理器。你应该让它返回一个查询集......

def get_queryset(self):
    return Project.objects.all()  # added all