【问题标题】:Data not showing on template数据未显示在模板上
【发布时间】:2019-08-16 06:35:41
【问题描述】:

这是我第一次在真实项目中实现基于类的视图,但模板上没有显示数据。

        <div class="container">
          <h4 class="heading-decorated text-center mt-5">Our Volunteers</h4>
          {% for volunteer in volunteers %}
          <div class="row row-30 text-center mb-5">
            <div class="col-sm-6 col-md-3">
              <figure class="box-icon-image"><a href="#"><img class="rounded" src="{{volunteer.volunteer_image.url}}" alt="" width="126" height="102"/></a></figure>
                <p class="lead">{{volunteers.volunteer_name}}</p>
            </div>
          </div>
          {% endfor %}
        </div>

views.py

class VolunteerListView(ListView):
    model = Volunteers
    context_object_name = 'volunteer'
    template_name = 'add_my_language/home.html'

models.py

class Volunteers(models.Model):
    volunteer_image = models.ImageField(upload_to='media/volunteers')
    volunteer_name = models.CharField(max_length=255, blank=False)

def __str__(self):
    return self.volunteer_name

我错过了什么吗?

【问题讨论】:

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


    【解决方案1】:

    我发现我的主页模型是分开的,因此数据没有显示。一旦我为主页组合了所有模型,我上面的答案就奏效了。

    【讨论】:

      【解决方案2】:

      在执行此视图时,self.object_list 将包含视图正在操作的对象列表(通常但不一定是查询集)。

      列表视图:

      class VolunteerListView(ListView):
      
          model = Volunteers
      
          def get_context_data(self, **kwargs):
             context = super().get_context_data(**kwargs)
             # extra context goes here
             return context
      

      模板

      <h1>Volunteers</h1>
      
         {% for volunteer in object_list %}
           <p class="lead">{{volunteers.volunteer_name}}</p>
      
         {% endfor %}
      

      进一步阅读

      Generic display views Official Django docs

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-15
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        • 2019-01-14
        • 2022-01-22
        相关资源
        最近更新 更多