这是我第一次在真实的项目中实现基于类的视图,但是数据没有显示在模板上。
<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
我有什么想念吗?
答案 0 :(得分:0)
您有context_object_name = 'volunteer'
,但是您正在模板中使用volunteers
进行迭代:您可以将其更改为
class VolunteerListView(ListView):
model = Volunteers
context_object_name = 'volunteers'
template_name = 'add_my_language/home.html'
就像@ruddra在模板的注释中说的那样,而不是{{volunteers.volunteer_name}}
更改为{{volunteer.volunteer_name}}
答案 1 :(得分:0)
我发现我的主页模型是分开的,因此没有显示数据。合并首页的所有模型后,上面的答案就起作用了。
答案 2 :(得分:-1)
在执行此视图时,self.object_list将包含该视图所操作的对象列表(通常,但不一定是查询集)。
ListView:
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 %}
进一步阅读