django模板在bootstrap表上显示python字典

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (42)

我有一个django视图,返回这个字典

args={'Residential': 'N/A', 'School': ('481 address', 600), 'Park': 'N/A', 'Religious': 'N/A', 'Childcare': ('123 address', 5)}

我有这个代码,可以在HTML页面上正确显示它

<h5><b>Nearest Childcare Parcel</b> = {{ Childcare }}</h5>
<h5><b>Nearest Park Parcel</b> = {{ Park }}</h5>
<h5><b>Nearest Religious Parcel</b> = {{ Religious }}</h5>
<h5><b>Nearest Residential Parcel</b> = {{ Residential }}</h5>
<h5><b>Nearest School Parcel</b> = {{ School }}</h5>

这个输出

这是好的,但它的丑陋和凌乱。

我想把它放在一张表里。

所以这是我使用django jinja模板的html代码

<div class="container">
      <h2>Property Search Results</h2>
      <table class="table">
        <thead>
          <tr>
            <th>Layer</th>
            <th>Address</th>
            <th>Distance to Property</th>
          </tr>
        </thead>

        <tbody>            
          <tr>
            {% if args %}
            <td>Childcare</td>            
            <td>{ args['Childcare'][0] }</td>
            <td>{ args['Childcare'][1] }</td>
            {% endif %}

          </tr>      
          <tr class="success">
            {% if args %}
            <td>Park</td>
            <td>{ args['Park'][0] }</td>
            <td>{ args['Park'][1] }</td>
            {% endif %}
          </tr>
          <tr class="danger">
            {% if args %}
            <td>Religious</td>
            <td>{ args['Religious'][0] }</td>
            <td>{ args['Religious'][1] }</td>
            {% endif %}
          </tr>
          <tr class="info">
            {% if args %}
            <td>Residential</td>
            <td>{ args['Residential'][0] }</td>
            <td>{ args['Residential'][1] }</td>
            {% endif %}
          </tr>
          <tr class="warning">
            {% if args %}
            <td>School</td>
            <td>{ args['School'][0] }</td>
            <td>{ args['School'][1] }</td>
            {% endif %}
          </tr>

        </tbody>
      </table>
    </div>

没有任何错误,但桌面上根本没有显示任何内容。

让它太有效的最佳方法是什么?我应该通过args字典做一个for循环吗?

这是整个视图

class HomePageView(TemplateView):
    template_name = 'index.html'
    def get(self, request):
        cur = conn.cursor()
        cur.execute("delete from reporter_post")
        form = HomeForm()
        #posts = Post.objects.all()

        #args = {'form': form, 'posts': posts}
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = HomeForm(request.POST)
        print(form)
        if form.is_valid():
            cur = conn.cursor()
            cur.execute("delete from reporter_post")
            form.save()
            g = geocoder.bing(str(form.cleaned_data['address']), key=bingkey)
            try:
              x,y=g.latlng[1],g.latlng[0]
              print(x,y)
              pre_qry='''with a as(select parcelid,owner_name,geom
                              from macomb_parcels_zoning_mun mpzu 
                              where st_intersects(geom,st_transform(st_setsrid(ST_FlipCoordinates(st_makepoint({0}, {1})),4326),102690))
                              )
                      update reporter_post set parcelid=a.parcelid, owner_name=a.owner_name,geom=a.geom from a;
                      '''.format(y,x)
              cur.execute(pre_qry)
              conn.commit()
              qry = '''                                    
                      with address1 as(select '{0}'::text subject_parcel_address, mpzu.*
                              from macomb_parcels_zoning_mun mpzu 
                              where st_intersects(geom,st_transform(st_setsrid(ST_FlipCoordinates(st_makepoint({1}, {2})),4326),102690))
                               ),
                      process 
                        as(select distinct on(zone_from_parcels,subject_parcel_address) zone_from_parcels,subject_parcel_address,buffered_parcel_address,owner_name,dist
                              from(select aa.address buffered_parcel_address,aa.owner_name,aa.zone_for_buff zone_from_parcels,
                                  round(st_distance(aa.geom,t.geom)::numeric,2 ) dist, t.subject_parcel_address
                                      from mac_parcels_union aa
                                      cross join lateral (
                                          select m.geom,m.subject_parcel_address, mbu.geom geom_buff 
                                          from address1 m join mac_buffer_union mbu on st_dwithin(m.geom,mbu.geom,2000)
                                              where mbu.parcelid = aa.parcelid and aa.parcelid <> m.parcelid 
                                          )t
                                  group by buffered_parcel_address,owner_name,zone_from_parcels,dist,subject_parcel_address
                                  order by dist) t
                          order by subject_parcel_address,zone_from_parcels,dist
                          )
                    SELECT zone_from_parcels zone_,subject_parcel_address,buffered_parcel_address,owner_name,dist::integer 
                                FROM process
                          '''.format(str(form.cleaned_data['address']), y, x)
              cur.execute(qry)
              row=cur.fetchall()
              print(row)
              if not row:
                  return render(request, self.template_name, {'form': form,'text': 'N/A'})
              else:
                  zones={'Childcare': 'N/A', 'School': 'N/A', 'Park': 'N/A', 'Residential': 'N/A', 'Religious': 'N/A'}
                  for x in row:
                      for k, v in zones.items():
                          if x[0] == k:
                              print(k, x[0])
                              zones[k] = x[2], x[4]


                  args = {'form': form, 'Residential': zones['Residential'],
                          'School': zones['School'], 'Religious': zones['Religious'],
                          'Childcare': zones['Childcare'], 'Park': zones['Park']}
                  return render(request, self.template_name, args)
                  print args
            except:
              args={'Residential': 'N/A', 'School': ('481 address', 600), 'Park': 'N/A', 'Religious': 'N/A', 'Childcare': ('123 address', 5)}
              return render(request, self.template_name, args)
提问于
用户回答回答于

问题是在这段代码中:

args = {'form': form, 'Residential': zones['Residential'],
        'School': zones['School'], 'Religious': zones['Religious'],
        'Childcare': zones['Childcare'], 'Park': zones['Park']}
return render(request, self.template_name, args)

没有名为args的变量被传递给模板。模板中可用的变量正是您在这里称为args的字典的键 - 所以形式,学校,宗教,儿童保育和公园。模板对您选择用于字典本身的变量名称一无所知(事实上,在这里传递字典文字并不常见,根本没有变量名称 - 尽管如果它更方便,将它放入变量是完全合法的) 。

所以条件{%if args%}总是被解释为False,因为就模板而言args不存在。

还有一个错误,就是在Django模板语言中,与Python本身不同,任何类型的所有属性访问都是通过点表示法完成的,绝不使用方括号。所以Childcare [0]根本不起作用 - 你需要做Childcare.0。

官方文档中有关于Django模板语言的大量信息。

扫码关注云+社区

领取腾讯云代金券