首页 > 解决方案 > 如何使用cloud firestore在django中以表格的形式获取数据?

问题描述

1 2 3
我正在尝试以表格的形式获取数据,但是没有获取数据,我不知道如何获取记录,我正在使用cloud firestore获取数据。

在我的代码中,我使用 {{buldings.building}} 来获取记录,但这不是从火力库中获取记录。

这是我的表格代码

<div class="row">
        
        <div class="col-lg-12 mb-4">
          <!-- Simple Tables -->
          <div class="card">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
             <a href="{% url 'building:registerBuilding'%}" class="btn btn-sm btn-primary"><i class="fas fa-plus-circle "></i> Add Building</a>
         </div>
            <div class="table-responsive">
              <table class="table align-items-center table-flush" id="buildingList">
                <thead class="thead-light">
                  <tr>
                    <th>BUILDING NAME</th>
                    <th>POSTAL CODE</th>
                    <th>CITY</th>
                    <th>STREET</th>
                    <th>HOUSE NO.</th>
                    <th>TOWN</th>
                    <th>ADDITIONAL INFO</th>
                    <th colspan="2">ACTION</th>
                    
                  </tr>
                </thead>

                <tbody>
             {% for building in buildings %}     
           <tr>  
              <td>{{ buildings.building }}</td>  
              <td>{{ buildings.postalCode }}</td>  
              <td>{{ buildings.city }}</td>
              <td>{{ buildings.houseNo }}</td>
              <td>{{ buildings.street }}</td>
              <td>{{ buildings.town }}</td>  
              <td>{{ buildings.additionalInfo }}</td>
              <td><a href="#" class="btn btn-primary btn-xs" data-title="Edit"  ><i class="glyphicon glyphicon-pencil"></i>Edit</a></p></td>
              <td><a href="#" class="btn btn-danger btn-xs" data-title="Delete"  ><i class="glyphicon glyphicon-trash"></i>Delete</a></p></td>  
             </tr>  
            {% endfor %}
               
               
               
              
                </tbody>
              </table>
            </div>
            <div class="card-footer"></div>
          </div>
        </div>
        
      </div>
    </div>
    
    <!---Container Fluid-->
  </div>

视图.py 文件

def buildingMag(request):  

context = {
     'buildings': db.collection('Buildings').get()
}
return render(request,"EmployeeAdmin/buildingMag.html",context)

标签: djangogoogle-cloud-firestore

解决方案


db.collection('Buildings').get()应该返回一个 Firestore 列表,该列表DocumentSnapshot通过buildingskey 发送到模板上下文。循环buildings将允许您使用列表中的每个项目填充模板(表)。像下面的东西。

在您的观点中构建字典DocumentSnapshot并返回字典

视图.py

buildings = db.collection('Buildings').get()
context = {
     'buildings': [building.to_dict() for building in buildings]
}

模板.html

{% for building_obj in buildings %}
    <tr>
        <td>{{ building_obj.building }}</td>  
        <td>{{ building_obj.postalCode }}</td>  
        <td>{{ building_obj.city }}</td>
              ...
              ...
    </tr>
{% endfor %}

推荐阅读