On the last part, we have setting the template. And now, we will get article data from model and show it in template. So, when we access the home url, it will show list the last ten article. On this section, we are focus only on home page. for other page, we will discuss on the next section. Are you ready to write a code? 

A. View

Open views.py in the project directory (parallel with settings.py and urls.py), and change the source code like this:

1
2
3
4
5
6
7
8
from article.models import Category, Post
...
def home(request):
    post = Post.objects.all()[:10]
    data = {
        'article' : post
    }
    return render_to_response('index.html', data, context_instance=RequestContext(request))

 

Explanation

1
from article.models import Category, Post


This code is used to load the models

1
post = Post.objects.all()[:10]


This code is used to query the data. Get all the last 10 post data.

1
2
3
4
data = {
    'article' : post
}
return render_to_response('index.html', data, context_instance=RequestContext(request))


This code is used to parse the data into variable, so it will be used in template.

B. Template

Open the index.html and change the source code. Remove the content inside tag blog-main and change it like this

1
2
3
4
5
6
7
8
9
10
11
...
<div class="col-sm-8 blog-main">
    {% for post in article %}
        <div class="blog-post">
            <h2 class="blog-post-title"><a href="/detail/{{ post.slug }}">{{ post.title }}</a></h2>
            <p class="blog-post-meta">{{ post.created_on|date:"F j, Y" }}
            {{ post.content|safe|truncatewords:"25" }}
        </div>
    {% endfor %}
</div>
...

Explanation

1
 {% for post in article %}


This is tag used to loop the data

1
{{ post.title }}


This is tag to get the data.

And this is the documentation about django template tag.

Layout 

homepage-template 

Next?

For the next, we try to make the detail post page for each article

Thanks   

Comments

Add comment

authimage