Make a Blog using Django Part 2

From previous post, you have configured and ran django, also added admin site to the django.

To view the working source of this tutorial, check here at: https://github.com/ruddra/myblog

Now click on the myblog section and click add to add new blog, which will look like this:

You can create new tags using Tags section of the admin page or clicking the (+) button right beside the Tags section on the new blog creation page, marked with blue circle in the previous image. After successfully adding a new blog, you can see this page:

Creating new tags is easy, just click on the Tags section in the admin page and press add tags button.

Now you have created new blogs and tags. Its time for showing them in templates.

For making data visible in templates, you need to use views to send data to them. let’s use Class Based View(CBV) for that. ListView is most appropriate for viewing all blogs in one page as it renders a page representing a list of objects. You can directly use this generic CBV in urls like:

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls), name='admin-site'),
    url(r'^$', ListView.as_view(model = MyBlog, template_name = 'blog_list.html'), name='blog_list'),
    )

Here, you need to create a template as well to view the data sent from this view:

<ul>
    {% for blog in object_list %}
        <li> {{ blog.title }} <br/>
        <p> {{ blog.body }} </p>
    {% endfor %}
</ul>

So now if you go to url: 127.0.0.1:8000, you will see this:

Voila!! You can see the posts you are creating in admin site in this page.

Now, for accessing each blog post separately, you can use Class Based View (CBV) for that. You can use DetailView for viewing content of one myblog object. For that, you can directly use it in urls like:

# ------------- Models ---------------
from myblog.models import Tag, MyBlog
# ------------- Generic Views --------
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView


urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls), name='admin-site'),
    url(r'^$', ListView.as_view(model = MyBlog, template_name = 'blog_list.html'), name='blog_list'),
    url(r'^details/(?P<pk>[0-9]+)/', DetailView.as_view(model = MyBlog, template_name = 'blog_details.html'), name='blog_details'),
    # Why naming the urls? Check below for usage of named urls
    )


<h2>{{ object.title }}</h2>
<p>{{ object.body }}</p>

<b>Tags:</b>
    <p>
    {% for item in object.tags.all %}
        {{ item }}
    {% endfor %}
    </p>

Blog details can visible to this url: 127.0.0.1:8000/details/1/ . This should look like this:

Now you can see all the posts and tags separately. Will do some tune-ups in next post. Cheers!!!

comments powered by Disqus