Getting Started with Python Programming: Creating a Blog

Sep 13, 2012
Python
130 Shares
By

How do you create a simple, dynamic website using the Python programming language? In this tutorial we are going to learn how to do exactly that. First, lets get some basics about Python.

Classes and Methods in Python

Python is primarily object-oriented. Class instances (objects) in Python are defined as shown below:

class coder:
          coding_languages = 10
david = coder()
david.coding_languages = 5
print “David knows s languages.” % david.coding_languages

Running the above script from the terminal gives the results below:

“David knows 5 languages.”

Methods in Python are functions contained within a class. Methods are written in Classes and referenced using objects. Methods are defined as shown below:

class coder:
         coding_languages = 10

         def learn(self):

         print “I know s languages.” % self.coding_languages

Consider another method below:

class google(coder):
           def chrome(self):
           print “Ow snap!”
david = coder()
david.chrome()

Variables get inherited the same way as Classes.

In languages like PHP, you only need to code the functions specific to your website. When using Python you can use frameworks like Django, Web.py, Grok and TurboGears. When using Django, install it both locally and on your server when deploying. Django is an MVC framework which is feature-rich and its tutorials are easily available online and this is what we are going to be using in this tutorial.

Creating a Simple Blog

Start your first Django project using the command below:

Django-admin.py startproject SimpleBlog

When you list the files inside the above folder, SimpleBlog, you will see three files have been created: manage.py, settings.py and urls.py

We will start by creating our first app as follows:

Python manage.py startapp blog

This creates a directory called “blog” which is our app. We need to define our models using the models.py file. For a blog we will need a table. We create a table as shown below:

class posts(models.Model):
       author = models.CharField(max_length = 30)
       title = models.CharField(max_length =100)
       bodytext = models.TextField()
       timestamp = models.DateTimeField()

After installing mySQL as your database, install the Python library for interfacing with the DB (I use Easy Install) and then create the database. Set your Django project to work with your mySQL database.

Add all the models we created into the database using the command below:

manage.py syncdb

This command simply adds new fields and does not alter existing ones in the database.

Set up the urls pattern (urls.py) to the appropriate module as shown:

Urlpatterns = patterns(),
url(r’^$’, ‘SimpleBlog.blog.views.home’, name= ‘home’),

Under views.py, add the code below:

from django.shortcuts import render_to_response
from blog.models import posts
def home(request);
     return render_to_response(*index.html*)

Create a new directory called “templates” in the “blog” folder we created earlier. Create the “index.html” file and save it in the folder. Locate the ‘Settings.py’ file and under the “Template_Dirs’ add the string below that defines where to look for the templates:

TEMPLATE_DIRS = (
“blog/templates”,

Lay out some boilerplate HTML5 code to define the basic structure of the website. Python allows you to embed variables straight into you HTML document. Use the following syntax to accomplish this:

{{ author }}

Now we can go back to our earlier code on views.py and add a second argument as shown below:

def home(request);
    posts.objects.all()
    content = {
	‘title’ : ‘First Post’
	‘author’ : ‘David’,
	‘date’ : ‘5 September 2012’’
	‘body’ : ‘This is our first blog made using the Python
                     programming language and the Django
                     framework.

          return render_to_response(‘index.html’, content)

We are now managing to pass variables into our template from our views.py. To retrieve data from the database, we import the app under the settings.py file. Under ‘Installed_Apps’, add the string below to the list:

‘SimpleBlog.blog’,

Since Django returns all of the data from the database in a special structure called a query set, we can replace the above code in views.py with the one below:

def home(request):
    entries = posts.objects.all()()[:10]
    return render_to_response(‘index.html’,{‘posts’:entries})

In your index.html file, add the string below where you want the posts to be displayed:

<body>
<div class=”container”>
            <h1>Simple Blog</h1>
<hr />
<div class=”post”>
    {% for post in posts %}
            <h2>({ post.title})</h2>
            <h2>Posted on ({ post.timestamp}) by {{ post.author}} </h2>
            <p>({ post.bodytext})</p>
</div>
<hr />
{% endfor %}
</div>
</body>

Sync the DB and run.

  • David Gitonga

    I would love your opinions on using Python for your projects. I love it. How about you?

  • Harrison Nene

    Thank you for rekindling my interest in Python

    • http://twitter.com/DavGit David Gitonga

      Hey Harrison. You are most welcome.

  • karl

    your templating system for the code has completely destroyed the right python syntax. You might have to fix a few things such as %s.

    The blog you are proposing is not that simple. It relies on django that people will have to install.

    • http://twitter.com/DavGit David Gitonga

      Yes Karl. Like I mentioned, this is a Django project that assumes that you have some basic knowledge of Django. You will have a working blog if you follow the steps above. Check out Tutsplus for a similar tutorial.