gpt4 book ai didi

python - 如何使用 django 列表中的信息填充 html 表

转载 作者:行者123 更新时间:2023-11-28 16:33:39 25 4
gpt4 key购买 nike

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

模型.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]

网址.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)

View .py

from django.shortcuts import render, render_to_response, RequestContext

# Create your views here.

基础.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 的结果解析为第二个 <td>标签以及其他文件中会出现什么修改? (表单、 View 、网址)。

最佳答案

将 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>
...

关于python - 如何使用 django 列表中的信息填充 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29336520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com