首页 > 解决方案 > 条目未显示在 django 表中

问题描述

问题:我有一个联系人模型。在这个联系模型中,我有多个类型(供应商、客户和员工)。数据已上传到 SQL 表中,但未显示在 Django/html 表中。我是否需要更改模型的编写方式?

提前致谢

模型:

class Contact(models.Model):

    CONTACT_TYPE = (      
        (0, 'Customer'),
        (1, 'Supplier'),
        (2, 'Employee'),
      
        )
    GENDER = (      
        (0, 'Male'),
        (1, 'Female'),
        )
    

    type = models.IntegerField(choices=CONTACT_TYPE,default=1)
    gender = models.IntegerField(choices=GENDER,default=0)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True)

意见:

def index_supplier(request):
    contacts = Contact.objects.all()
    suppliers = Contact.objects.filter(type=1).all()
    count_supplier= Contact.objects.filter(type=1).count()        
    context = {
                'contacts': contacts,
                'count_supplier': count_supplier,                   
                         
            }
    return render(request, 'contacts/index_supplier.html', context)

模板:

<div class="container-fluid">
     <div class="col-sm-20">
           <table id="dtBasicExample" class="table table-striped table-hover">
           <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
           <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
           <script>
                   $(document).ready(function(){
                   $('#dtBasicExample').DataTable();
            });
           </script>                    
           <thead>
               <tr>
                    <th>Type</th> 
                    <th>Contact Name</th>
                    <th>Company</th>                             
               </tr>
           </thead>
           <tbody>
               {% for contact in suppliers.all %}
               <tr>                                                  
                    <td>{{ contact.get_type_display }}</td>
                    <td>{{ contact.first_name }}</td>
                    <td>{{ contact.company }}</td>                      
               </tr>
               {% endfor %}
      </div>
</div>

标签: pythonsqldjango

解决方案


您需要修复context变量:

context = {
            'contacts': contacts,
            'count_supplier': count_supplier,                   
            'suppliers': suppliers,
        }

推荐阅读