On the last part, we have tried display article post in homepage. And now, we will try implement into detail page. The source code just simple like the last part. Are you ready to write a code?

A. Url

Open urls.py, and add the following script: 

1
2
3
4
5
urlpatterns = patterns('',
    url(r'^$', 'myblog.views.home', name='home'),
    url(r'^detail/(?P<slug>[\w-]+)$', 'article.views.detail'),
    ...
)

 

Explanation

1
url(r'^detail/(?P<slug>[\w-]+)$', 'article.views.detail'),


This is the code to register 'detail' url into web, so we can access http://localhost:8000/detail/slug-of-post

B. View

Open views.py in the article app directory, and add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from article.models import Category, Post
 
# Create your views here.
 
def detail(request, slug):
    post = Post.objects.get(slug=slug)
    data = {
        'post' : post
    }
    return render_to_response('detail.html', data, context_instance=RequestContext(request))

 

Explanation

1
post = Post.objects.get(slug=slug)


This code is used to query the data. Get the detail data where slug is same with the request. It will return a single data, so it can't to loop.

C. Template

Copy the last index.html, and rename it to detail.html. Change the content inside tag blog-main to be like this:

1
2
3
4
5
6
7
8
9
...
<div class="col-sm-8 blog-main">
        <div class="blog-post">
            <h2 class="blog-post-title">{{ post.title }}</h2>
            <p class="blog-post-meta">{{ post.created_on|date:"F j, Y" }}
            {{ post.content }}
        </div>
</div>
...

 

Explanation

We don't need for tag again, because the data parsed is a singel data.  

Next?

Ok, now we have made 2 pages, homepage and detail. We have 2 html with same in the some of code / html tag. So for the next, we will discuss about django templating. We try to merge the same into one file, and make it possible call in homepage and detail.

Thanks    

Comments

Re: Django Tutorial - Create a Blog - Part 7 : MVT (Model, View, Template) (Section 2 - Detail Article page)

mgfacioli | 27/10/2014, 15:10

Great tutorial!!!

Congratulations.

Add comment

authimage