3

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

1 Answer 1

4

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>
...
Sign up to request clarification or add additional context in comments.

7 Comments

thanks for this fast answer. Unfortunately, nothing seems to happen. The table is still empty. Any hints ?
What do you mean by "table is still empty"? Table has no rows in the <tbody>? Or <td> with url is empty?
I mean there are no populated rows in my table. It just says: No data available in table. So, the urls are not parsed into the table as they should.
Add print urls as in my updated answer and check the output of the devsever's console. I suspect that the p.site_list is empty.
I cleared my cache and there is another problem: NameError at /.global name 'MyHTMLParser' is not defined
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.