迭代数据库对象并将它们呈现给模板

时间:2014-08-16 00:12:42

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

我有一些我想要提供给模板的数据。这是尝试这样做的视图的片段:

   def get(self, request, *args, **kwargs):
        user = User.objects.get(username=request.user.username)
        beac_data = user.get_profile().owned_beacons.all()
        for beacon in beac_data:
            beacon_data_name = beacon.name
            beacon_data_factory_id = beacon.factory_id
            beacon_data_location = beacon.location
            beacon_data_visible = beacon.visible
            beacon_data_config_id = beacon.config_id
        #more code here

        return render(request, self.template_name, {
            'form': self.form, 
            'location': location, 
            'beacon_data_name': beacon_data_name,
            'beacon_data_factory_id': beacon_data_factory_id,
            'beacon_data_location': beacon_data_location,
            'beacon_data_visible': beacon_data_visible,
            'beacon_data_config_id': beacon_data_config_id,
        }) 

如图所示,我遍历数据库中的对象并在我的html文件中提供相关的模板标记:

           {{ beacon_data_name }}
           {{ beacon_data_factory_id }}
           {{ beacon_data_location }}
           {{ beacon_data_visible }}
           {{ beacon_data_config_id }}

模板标记有效,但它只呈现第一个对象的信息。为什么不返回数据库中所有对象的所有数据?一些帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

在上下文中传递beac_data并在模板中迭代它:

def get(self, request, *args, **kwargs):
    user = User.objects.get(username=request.user.username)
    beac_data = user.get_profile().owned_beacons.all()

    return render(request, self.template_name, {
        'form': self.form, 
        'location': location, 
        'beac_data': beac_data
    }) 

然后,在模板中:

{% for beacon in beac_date %}
    {{ beacon.name }}
    {{ beacon.factory_id }}
    {{ beacon.location }}
    {{ beacon.visible }}
    {{ beacon.config_id }}
{% endfor %}