【问题标题】:Displaying a list of table entries in Django在 Django 中显示表条目列表
【发布时间】:2014-09-08 13:05:40
【问题描述】:

我有一个数据库表,可让您输入有关特定人员的详细信息。然后我如何列出该表的所有条目以显示添加到数据库中的所有人员。

urls.py

url(r'^accounts/loggedin/locations/all/$', 'assessments.views.locations'),
url(r'^accounts/loggedin/locations/get/(?P<location_id>\d+)$',   'assessments.views.location'),
url(r'^accounts/loggedin/locations/create/$', 'assessments.views.create'),

models.py

class People(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

view.py

def people(request):
    return render_to_response('dashboard/people.html', {'people': People.objects.all})

people.html

<body>
    <h1>People</h1>
    {% for p in people %}
    <h1><a href="/people/get/{{ people.id }}/">{{ people.first_name }}</a></h1>
    {% endfor %}
    </body>
</html>

【问题讨论】:

  • 你现在的输出是什么?看起来你应该在你的 for 中使用{{ p.first_name }}。这样,如果您的数据正确,它将遍历所有 people 并为每个人打印一个 &lt;h1&gt;,并使用正确的名称。
  • 有什么问题?
  • 我已经尝试了建议的内容,但屏幕上没有输出。它只是银行

标签: python django django-templates django-views


【解决方案1】:

两个问题:

  • 您应该致电all() 获取结果,请注意()

    People.objects.all()
    
  • 在模板中,您应该使用{{ p.first_name }} 而不是{{ people.first_name }},因为您正在迭代people 变量,这是一个QuerySet - 基本上是一个对象列表

【讨论】:

    【解决方案2】:

    this link 是同一个问题


    如果你有下面的Question 模型,

    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField(verbose_name='date published')
    

    通过此代码,您可以看到所有条目(或字段、特征)。

    fields = Question._meta.get_fields()
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      相关资源
      最近更新 更多