Reputation: 1166
I want to populate, in my django application, my table from base.html
with the results from urlparse.py (this returns a list of 20 URLs from a site).
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>
Can anybody point me into the right direction ? How do I parse the results from urlparse.py into the second <td>
tag and what modification will appear in other files ? (forms,views,urls).
Upvotes: 3
Views: 7458
Reputation: 45555
Pass the list of urls to the template and use the {% for %}
tag to loop them.
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>
...
Upvotes: 4