【问题标题】:How to populate html table with info from list in django如何使用 django 列表中的信息填充 html 表
【发布时间】:2015-03-30 00:08:50
【问题描述】:

我想在我的 django 应用程序中使用来自 urlparse.py 的结果填充来自base.html 的表(这将返回来自站点的 20 个 URL 的列表)。

models.py

from django.db import models
from django.utils.encoding import smart_unicode

# Create your models here.

urlparse.py

import HTMLParser, urllib2

class MyHTMLParser(HTMLParser.HTMLParser):
    site_list = []

    def reset(self):
        HTMLParser.HTMLParser.reset(self)
        self.in_a = False
        self.next_link_text_pair = None
    def handle_starttag(self, tag, attrs):
        if tag=='a':
            for name, value in attrs:
                if name=='href':
                    self.next_link_text_pair = [value, '']
                    self.in_a = True
                    break
    def handle_data(self, data):
        if self.in_a: self.next_link_text_pair[1] += data
    def handle_endtag(self, tag):
        if tag=='a':
            if self.next_link_text_pair is not None:
                if self.next_link_text_pair[0].startswith('/siteinfo/'):
                    self.site_list.append(self.next_link_text_pair[1])
            self.next_link_text_pair = None
            self.in_a = False

if __name__=='__main__':
    p = MyHTMLParser()
    p.feed(urllib2.urlopen('http://www.alexa.com/topsites/global').read())
    print p.site_list[:20]

urls.py

from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    #url(r'^$', 'signups.views.home', name='home'),
    url(r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

views.py

from django.shortcuts import render, render_to_response, RequestContext

# Create your views here.

base.html

<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Rank</th>
                <th>Website</th>
                <th>Description</th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td>Something</td>
                <td>{{site.urls}}</td><!--What to put here ?-->
                <td>something</td>
            </tr>
        </tbody>
    </table>

谁能指出我正确的方向?如何将 urlparse.py 的结果解析为第二个 &lt;td&gt; 标记,其他文件中会出现哪些修改? (表单、视图、网址)。

【问题讨论】:

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


    【解决方案1】:

    将url列表传递给模板并使用{% for %}标签循环它们。

    urls.py

    urlpatterns = patterns('',
        url(r'^$', 'myapp.views.top_urls', name='home'),
        url(r'^admin/', include(admin.site.urls)),
    )
    

    views.py

    def top_urls(request):
        p = MyHTMLParser()
        p.feed(urllib2.urlopen('http://www.alexa.com/topsites/global').read())
        urls = p.site_list[:20]
        print urls
        return render(request, 'top_urls.html', {'urls': urls})
    

    top_urls.html

    ...
    <tbody>
        {% for url in urls %}
            <tr>
                <td>Something</td>
                <td>{{ url }}</td>
                <td>something</td>
            </tr>
        {% endfor %}
    </tbody>
    ...
    

    【讨论】:

    • 感谢您的快速答复。不幸的是,似乎什么也没有发生。桌子还是空的。有什么提示吗?
    • “桌子还是空的”是什么意思?表在&lt;tbody&gt; 中没有行?还是 &lt;td&gt; 的 url 为空?
    • 我的意思是我的表中没有填充行。它只是说:No data available in table。因此,url 没有按应有的方式解析到表中。
    • 在我更新的答案中添加print urls 并检查开发服务器控制台的输出。我怀疑p.site_list 是空的。
    • 我清除了缓存,还有一个问题:NameError at /.global name 'MyHTMLParser' is not defined
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2011-02-23
    相关资源
    最近更新 更多