Django-ListView-循环模板不显示任何项目

时间:2018-07-19 01:07:33

标签: django django-models django-templates django-views

这是我想要实现的:

enter image description here

well_list.html

<thead>
  <tr>
    {% for item in well_info %}
    <th>item</th>
    {% endfor %}
  </tr>
</thead>

project / urls.py

from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
from django.urls import path, re_path, include
from eric_base import views

urlpatterns = [
    path('contextual/', include('eric_base.urls')),
    path('well_list/', views.well_list)
]

views.py

from django.shortcuts import render
from django.views.generic import View, TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView

from . import models

class WellInfoListView(ListView):
    template_name = 'well_list.html'
    context_object_name = 'well_info'
    model = models.WellInfo

models.py

from django.db import models
from django.urls import reverse


# Create your models here.
class WellInfo(models.Model):
    api = models.CharField(max_length=100, primary_key=True)
    name = models.CharField(max_length=100)
    region_location = models.CharField(max_length=100)
    spud_date = models.CharField(max_length=100)
    well_bore = models.CharField(max_length=100)
    rig_name = models.CharField(max_length=100)
    status = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("")

由于我在context_object_name = 'well_info'中正确定义了views.py,并且在html中使用了{% for item in well_info %},所以我期望至少可以从模型属性中得到一些东西。但是,当我运行此代码时,我什么也没得到。标题行就像下面的屏幕快照一样消失了:

enter image description here

我希望表头具有在models.py中定义的属性名称,但是显然它没有从中获取任何东西。为什么它没有从models.py抓取任何属性,我如何只显示属性名称作为列标题?

所以我希望表头为:

Api | Name | Region Location | Spud Date | Well Bore | Rig Name | Status

,不包含每个键的值。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用Model _meta API。在您的视图中,您可以将字段放入列表,例如:

from django.shortcuts import render
from django.views.generic import View, TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView

from .models import WellInfo

class WellInfoListView(ListView):
    template_name = 'well_list.html'
    context_object_name = 'well_info'
    model = WellInfo

    def get_context_data(self, **kwargs):
        ctx = super(WellInfoListView, self).get_context_data(**kwargs)
        ctx['fields'] = [field.name for field in WellInfo._meta.get_fields()]
        return ctx

然后在您的模板中可以拥有

<thead>
    {% for field in fields %}
    <th>{{ field }}</th>
    {% endfor %}
</thead>