Blog

In This tutorial we will guide you to the step by step blog development in Django, at this tep we are assuming that you have covered the previous chapters about Django setup.

Step 1: Starting your Application

Open Pycharm and create new project in my case project name is “Global bridge Blog” and our application is “globalbridge_blog” , you will need to replace my references “Global bridge Blog” and “globalbridge_blog” throughout this tutorial with any name you want.

Navigate to your project directory folder, this should contain “__init__.py” , “manage.py” , “settings.py” , “urls.py”.

Click The Start button to run the Application.

You Should Also now have a folder called “gbs_blog” containing files. “__init__.py” , “models.py” , “views.py”.

-> Open and edit “settings.py” file located in your project folder. Find “INSTALLED_APPS” and add ‘globalbridge_blog’ after editing you should have something like that:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gbs_blog',
]

Step 2: Creating Models For Blog

Django models are your database structure. You can start creating model by opening “models.py” file, and create table and add fields/columns. Note: As for this tutorial we are keeping thing simple. So lets add your database tables.


class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    posted = models.DateField(db_index=True, auto_now_add=True)
    category = models.ForeignKey('blog.Category')

class Category(models.Model):
    title = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, db_index=True)

Explanation of each part

This line will create database table “Post”.

class Post(models.Model):

These are basic fields to be created in your database table “Post”

title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
body = models.TextField()
posted = models.DateTimeField(db_index=True, auto_now_add=True)

Foreign key Field , a little more advanced. This field populates its data from another database table, in this case Category, so you will need to populate the Category table field first.

category = models.ForeignKey('blog.Category')

Finalising your Model

There are few important lines that we are going to add in our model, after adding these lines our model file will look like this.

from django.db import models
from django.db.models import permalink

# Create your models here.

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    posted = models.DateTimeField(db_index=True, auto_now_add=True)
    category = models.ForeignKey('gbs_blog.Category')

    def __unicode__(self):
        return '%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('view_blog_post', None, { 'slug': self.slug })

class Category(models.Model):
    title = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, db_index=True)

    def __unicode__(self):
        return '%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('view_blog_category', None, { 'slug': self.slug })

Explanation:

The __unicode__ function sets the text reference for each record. This is used mainly in the automated django admin, but this is still available to use on your own site.

get_absolute_url function defines a URL, again used in the admin area, for each record.

if we dont use @permalink decorator the following would not work. This returns a URL calculated from the urls.py file which will be explained shortly. its recommended using this method as it allows you to change the URL for a page in only one location.

return ('view_blog_post', None, { 'slug': self.slug })

Example:

Title: Django Tutorial For Beginners – My First Application
Response from __unicode__: Django Tutorial For Beginners – My First Application
Response from get_absolute_url: /blog/view/django-tutorial-for-beginners-my-first-application.html

Step 3: Activation of Administration Panel.

In blog Folder open “admin.py” or create if not exist.This admin.py file is automatically checked by django admin for every application defined under INSTALLED_APPS in the settings.py

In admin.py add this code

from django.contrib import admin
from gbs_blog.models import Post, Category

admin.site.register(Blog)
admin.site.register(Category)

Explanation of each part

With this import command we register our models that we created.

from django.contrib import admin

This is used to import our models

from gbs_blog.models import Post, Category

Time to Register our models Post & Category with the admin.

fadmin.site.register(Post)
admin.site.register(Category)

With these line we can work with the admin panel, but we want to add litle more functionality to admin.py and here is the final file will look like:

from django.contrib import admin
from gbs_blog.models import Post, Category

# Register your models here.

class PostAdmin(admin.ModelAdmin):
    exclude = ['posted']
    prepopulated_fields = {'slug': ('title',)}

class CategoryAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',)}


admin.site.register(Post,PostAdmin)
admin.site.register(Category,CategoryAdmin)

Done with the admin panel, Now you might want to add blog posts and categories.

At this point: go to the terminal of pycharm , in terminal run this command to create your database table and admin superuser.

python manage.py syncdb

After table being created it will ask you to if you want to create superuser. Type yes to create superuser.

You can login into admin by browsing url form you machine “http://127.0.0.1:8000/admin/” and your admin will look like this once you are logged in.

Step 4: Django blog Views and URLs

This step is to setup URLs and writing views for your Django blog.

Views

The view is where you do all the logic to be sent to your templates, it can contain few other features you will be likely to use in the future.
In our Example we need to create three views.

1) Display your categories & latest posts

2) Display the posts in a specific category

3) Display the post

Open views.py file and write this code:

# Create your views here.

from gbs_blog.blog.models import Blog, Category
from django.shortcuts import render_to_response, get_object_or_404

def index(request):
    return render_to_response('index.html', {
        'categories': Category.objects.all(),
        'posts': Post.objects.all()[:5]
    })

def view_post(request, slug):   
    return render_to_response('view_post.html', {
        'post': get_object_or_404(Blog, slug=slug)
    })

def view_category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    return render_to_response('view_category.html', {
        'category': category,
        'posts': Post.objects.filter(category=category)[:5]
    })

Explanation of each part

First we need to import a couple of functions for displaying our template.

from django.shortcuts import render_to_response, get_object_or_404

The index page will display list of all categories and 5 most recent posts.

variable “request” also need to be specify when defining functions.This is the request object, which contains details of the User, POST & GET data as well as a few other bits. we are also specifying slug which is mapped to from the urls.py file as you will see next.

def view_category(request, slug):

“render_to_response” sets the template file that we are going to be using.

render_to_response('test.html', {

Database queries for both posts and categories.Category and Post are the names of the models we created earlier.

'categories': Category.objects.all(),
'posts': Post.objects.all()[:5]

In the other two functions view_post & view_category we use one of the rather useful Django shortcuts. This queries the database trying to match where slug=slug, the first slug being the field in the model, the second slug being the input into the function call, more on this in a second when we define the URL’s.

 get_object_or_404(Post, slug=slug)

Defining Django URLs for Blog

Goto you project folder and open “url.py” file and add the following lines.

 (r'^$', 'djangorocks.blog.views.index'),
    url(
        r'^blog/view/(?P[^\.]+).html',
        'globalbridge_blog.gbs_blog.views.view_post',
        name='view_blog_post'),
    url(
        r'^blog/category/(?P[^\.]+).html',
        'globalbridge_blog.gbs_blog.views.view_category',
        name='view_blog_category'),
 

Step 5: Django templates

Templating in Djnago is extremely powerful. In this tutorial we will be using very basic example.

First step is to we need to create base template.

-> Goto templates directory and create new file “base.html”

-> Open base.html file and add these line:

<html>
    <head>
        <title>{% block head_title %}Welcome to Globalbridge blog{% endblock %}</title>
    </head>
    <body>
        <h1>{% block title %}Welcome to my block{% endblock %}</h1>
        {% block content %}

        {% endblock %}
    </body>
</html>

-> Now create “index.html” in templates directory and add the following code.

{% extends 'base.html' %}
{% block title %}Welcome to Globalbridge blog{% endblock %}

{% block content %}
    <h2>Categories</h2>
    {% if categories %}
        <ul>
        {% for category in categories %}
            <li><a href="{{ category.get_absolute_url }}">{{ category.title }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>There are no posts.</p>
    {% endif %}

    <h2>Posts</h2>
    {% if posts %}
        <ul>
        {% for post in posts %}
            <li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>There are no posts.</p>
    {% endif %}

{% endblock %}

-> Create new File in templates “view_post.html” and add following code:

{% extends 'base.html' %} 
{% block head_title %}{{ post.title }}{% endblock %}
{% block title %}{{ post.title }}{% endblock %}

{% block content %}
    {{ post.body }}
{% endblock %}

-> Create new file in templates “view_category.html” and add following code in it.

{% extends 'base.html' %} 
{% block head_title %}Viewing category {{ category.title }}{% endblock %}
{% block title %}{{ category.title }}{% endblock %}

{% block content %}
    {% if posts %}
        <ul>
        {% for post in posts %}
            <li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>There are no posts.</p>
    {% endif %}
{% endblock %}

Explanation

In the base.html we are defining the base content that will be shared and common in all files , we will extend this base in other pages rather than writing these lines in every page.As you can see first line of all three pages is :

{% extends 'base.html' %}

This line calls the base.html template file. Inside this we define the blocks very much the same way as in the base.html file, however this time we add the content we want to display. Using the example from index.html

We define the block for content,

{% block content %}
    ...
{% endblock %}

Next is we are checking if there are any categories,

{% if categories %}
    ....
{% else %}
    <p>There are no posts.</p>
{% endif %}

If any categories are found this will be run.

<ul>
    {% for category in categories %}
        <li><a href="{{ category.get_absolute_url }}">{{ category.title }}</a></li>
    {% endfor %}
</ul>

This will loop the response from the Category model as defined in views.py, and print out the results that are entered into the database.

Congratulation! Blog Finished.

Now you can visit admin panel and add post and categories. you should be able to see listing of blog post. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *