[Answer]-How to asyncronously load posts from DB to django template on google app engine?

1👍

This is my solution. It now loads asyncrously when you scroll to the bottom. Its based on the second example from this site

Template.html:

<div id="postswrapper">
           <div class="item">content</div>
           <div id="loadmoreajaxloader" style="display:none;"><center><img src="ajax-loader.gif" /></center></div>
    </div>
    <script type="text/javascript">
        var pageCounter = 2;
        $(window).scroll(function()
        {
            if (pageCounter > 0)
            {
                if($(window).scrollTop() == $(document).height() - $(window).height())
                {
                    $('div#loadmoreajaxloader').show();
                    $.ajax({  url: "./page/" + pageCounter , success: function(html)  {
                            if(html)
                            {
                                $("#postswrapper").append(html);
                                $('div#loadmoreajaxloader').hide();
                                pageCounter++;
                            }else
                            {
                                pageCounter = -1;
                                $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
                            }
                        }
                    });
                    pageCounter = -1;
                }
            }
        });
    </script>

And this is the method in main,py which loads the posts from DB.

class Page(webapp2.RequestHandler):
    def get(self,page):
        numberOfPages = int(page)
        records_query = db.GqlQuery("SELECT * FROM Record order by date desc")
        records = records_query.fetch(numberOfPages * 10)
        records = records[((numberOfPages- 1) * 10):]
        if len(records) > 0:
            template_values = {
             'records': records,
            }
            path = os.path.join(os.path.dirname(__file__), 'posts.html')
            self.response.out.write(template.render(path, template_values))

This is the template thats loaded into the main template.
posts.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
{% for record in records %}
<div class="oneRecord">
    <img src="{{ record.imageCacheURL }}" />
    <a href ="./{{ record.imageID }}"> {{ record.title|escape }}</a>
</div>
{% endfor %}
</body>
</html>
👤bogen

Leave a comment