Top Banner
12/23/11 Relevant Links _ Django 1/2 sandcurves.com/blog_engine/links/ Useful Links to Django Blog Devopment A complete blog engine using django in 60 minutes This is a great tutorial, and follows the DRY principal very well. I worked through this tutorial and learned a lot from it.&nbps; 60 minutes? It takes a little longer, unless you really know your stuff already. Build a microblog with django This is another useful tutorial. I didn't read through it, so I can't say how good it is. A detailed django tutorial blog basics He is an expert, I am sure it is good. I didn't read this one either. Django Tutorials A list of Django tutorials. The Django Tutorial Go sit at the feet of the masters of Django, and become wise. Django's Documentation I am sure I didn't need to put this link, if you don't dip in the docs, forget being a Django guru, ever. Running Django on Google App Engine Fan of Google App Engine, here are the docs to help you get Django and App engine working together. Django Book This was the main thing I used to learn Django, and I find it really useful. Did you write a good Django Tutorial? Send me a Tweet @sandcurves and I'll check it out and stick up a link. Here are a few other related things you may find useful Emacs The Python Tutorial Sandcurves Home About Me Topics Contact Blogroll About My name is Vernon I live in Namibia I'm a passionate blogger, computer enthusiast, naturalist and father Sandcurves is my personal website and blog More« Blogging Project Meaningful Blog Project Linux and open sourse New Here? _ Subscribe | About Me | Twitter | Contact Sandcurves Blogging Nuts & Bolts _ Vernon Swanepoel's Blog
74

Blog Engine Tutorial

Dec 02, 2014

Download

Documents

Manish Roshan
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Blog Engine Tutorial

12/23/11 Relevant Links | Django

1/2sandcurves.com/blog_engine/links/

Useful Links to Django Blog DevopmentA complete blog engine using django in 60 minutes ­This is a great tutorial, and follows the DRY principal verywell. I worked through this tutorial and learned a lot fromit.&nbps; 60 minutes? It takes a little longer, unless youreally know your stuff already.

Build a microblog with django ­ This is another usefultutorial. I didn't read through it, so I can't say how good itis.

A detailed django tutorial blog basics He is an expert,I am sure it is good. I didn't read this one either.

Django Tutorials ­ A list of Django tutorials.

The Django Tutorial ­ Go sit at the feet of the masters ofDjango, and become wise.

Django's Documentation ­ I am sure I didn't need to putthis link, if you don't dip in the docs, forget being a Djangoguru, ever.

Running Django on Google App Engine ­ Fan ofGoogle App Engine, here are the docs to help you getDjango and App engine working together.

Django Book ­ This was the main thing I used to learnDjango, and I find it really useful.

Did you write a good Django Tutorial? Send me a Tweet@sandcurves and I'll check it out and stick up a link.

Here are a few other related things you may find useful

EmacsThe Python Tutorial

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 2: Blog Engine Tutorial

12/23/11 Relevant Links | Django

2/2sandcurves.com/blog_engine/links/

Dive Into Python [out of date, but super for learningPython]The Gimp Image Manipulation ProgramUbuntuApache Web Server

Return to the contents page of the Django Blog Engine Tutorial

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Don 2 3D TrailerNow Playing Don 2 Trailers in3D. Catch It All on YouTube!youtube.com/Don2

Samsung Microwave OvensDeep & Even Cooking withSamsung Microwave Ovens.Get Details now.www.Samsung.com/in

Page 3: Blog Engine Tutorial

12/23/11 Introduction

1/4sandcurves.com/blog_engine/page/introduction/

IntroductionNote, this is mainly introductory, so you could just scanthrough, make sure you've got the stuff you need, andhead on to the next section

Blogger, Wordpress, Typepad and the legion of a million blogplatforms ­ they are all better than what I offer here. Thousandsof open source web content management systems. Many aregreater than what we will talk about here. And if you want to flexyour muscles and say that you did it the hard way, well writeyour engine in C (I'll even admire you for writing a blog engine inplain PHP).

So, it is not the most convenient or easiest, nor is it the hardest.

But, what Django offers you is Lego blocks, the chance to craftsomething of your own imagination, a blog engine made yourway, made by you, and it gives you all the support you need(documentation and community).

And, we all know, there is only one cool scripting language,right? Python. Python has soul. And Django is deeplyPythonic.

So, do you want to get creative, do you want to be cool ­ write ablog with Django (I know you want to).

I am not sure that I wrote this for any real audience ­ does anyone butme want to write a blog engine, or is it, well, done… boring? Perhaps. I gained a lot just writing it, and so that is enough to justify my doing it. But it certainly would thrill me to bits if someone finds some, if not all,of the tutorial of some use. If you did, why not send me a Tweet@sandcurves.

What is this about: This is a very simple tutorial to take youthrough building a blog using Django. It is simple, but it's notshort. Don't let the length fool you into thinking that it's difficult,it isn't.

Django is mainly aimed at small groups of developers, but withthis tutorial you should be able to do every aspect by

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 4: Blog Engine Tutorial

12/23/11 Introduction

2/4sandcurves.com/blog_engine/page/introduction/

yourself. My main goal is a tutorial where almost anyone withsome patience and the right set of tools (which are all opensource, or free software if you care to distinguish, except foryour computer itself and somewhere to host) can build their ownblog engine.

Who will benefit the most: I am writing this post as a way todocument doing exactly what I had to learn to do. So, to benefitthe most you need to have some of the things I do. You'llcertainly be able to make use of it even if you use some differenttool, but I am going to write with the assumption that we aredoing everything the same way.

You will benefit most if:

You have some idea what Python is about. I am not aprogrammer, but have done several tutorials and workedvery thoroughly through Dive Into Python by MarkPilgrim. If that is your sort of level of experience with thelanguage, you'll do dandy. You will, of course, need to besure Python (version 2.6ish) is on your system. If youhave Linux, you should be all set already. I am not going to teach you the Python needed tounderstand all this stuff. You should at a minimumunderstand basic string manipulation, use of tuples, listsand dictionaries and the very basics of regularexpression. If I did try to teach you the Python, this wouldturn into a book instead of a simple tutorial. But, if you have only a real minimal experience withPython, and learn it alongside this tutorial, you should dofine. It will just take you more time. You need to have Sqlite3. If you have a normal Pythoninstallation, you should be fine anyway. We'll only useSqlite3 for the development. Once you upload, useMySQL. Don't worry to much about that, I'll cover it all indetail. I work on Ubuntu 10.04. If you are on a similar Linuxsystem, you'll be able to follow along well. If you don'thave Ubuntu, but want to try it, you can have it alongsideyour regular operating system. There is plenty of adviceon how to do that on the web. If you are not on a Linuxsystem, this tutorial is going to be very difficult to follow. We are going to work a lot with the Terminal. If you don'teven know what this is, so long as you are on Ubuntu, I'lltalk you right into it. You can do a beginner tutorial inbash. Have some idea about how HTML and CSS work. I'mgoing to give you the stuff you need to get the tutorialworking, and you can simply copy and paste, but thewhole point of rolling your own blog engine is so that youcan have some autonomy as to both how it looks and howit works. So, later on you'll want to learn a bit more andmake your website yours!This isn't required, but I think using a good text editor likeEmacs helps a lot. I am going to assume that you want to load it up to ahosted server. I will explain how to do it with Hostgator. Itis just because I host (indirectly) with them, and it was areally tough job to get everything working. You may find

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Don 2 3D TrailerNow Playing Don 2 Trailers in3D. Catch It All on YouTube!youtube.com/Don2

Latest Bollywood VideosStay Updated On YourFavorite Video CheckYahooFor Full length Video's.www.yahoo.com/video

Page 5: Blog Engine Tutorial

12/23/11 Introduction

3/4sandcurves.com/blog_engine/page/introduction/

some of what I say useful even if you host elsewhere. I'm not going to get to much into working with images, butif you are working on websites, you'll sooner or later wantsome image editing capability. For some reason Ubuntu10.04 has stopped including gimp. I think some decisionmakers fell out of a tree and hit their heads hard on arock. Get the gimp if you don't already have it. If youdon't have it, simply type "sudo apt­get install gimp" inTerminal, and wait a while. Don't know what's terminal,we'll get to that. You need a web browser. Actually, eventually you want atleast access to a few to check that things look rocking inmost popular browsers. For the tutorial, I'm going toassume you are using FirefoxA little time, patience to read the tutorial, and coffee [Mmmm, lets break a minute to get ourselves a cup, shallwe. ] If you don't drink coffee… well, of course you drinkcoffee… you're a Linux geek.

Some Advice for doing the tutorial

If you are experienced, this is probably not the tutorial for youanyway. You may get something out of it, but you are probablygoing to find it really slow and boring. If you are a total beginnerwith this stuff, I advise you to follow the tutorial to a tee, doexactly what I say. Once you have done the whole thing, thenstart digging into more of the Django documentation, get help onforums and start to play around with it. If you play around toearly, you'll get lost, and probably not finish the tutorial. On theflip side, if you do the whole tutorial and you never play aroundwith it, you'll also have lost out. But, if you want to learn howto do this, follow the entire tutorial, all the way through. Iusually do tutorials like this in w3m browser, in Emacs ­ if youcan do it in a text browser (in which it works great) you should ­simply to keep twitter and the like quiet.

If you are somewhere in the middle ­ you have a good bit ofPython, and you have already picked at the Djangodocumentation and just get stuck here and there on exactly howto go about getting a blog working, this should be just the tutorialfor you. When it seems difficult, it is most likely that you aregoing to fast, or not concentrating on the details. Look at itclearly, and occasionally go back a few times.

When writing the tutorial, which I did in a few chunks, what Iwould do is create a blog on my computer following along, then Ijust delete the whole thing and do it again, over and over. In sodoing, I know that everything is working, though I didn't put it upon a server. I am working on another non­blog website withDjango, and so could test out some of what I said while I workedon that site. If you are trying to get a good grip of doing Djangowebsites, I advise you to do the same ­ build one, delete, build itagain, delete. Each time you'll do it different, each time you'lllook something new up, or simply 'get' something in a way youdidn't before.

If you are a hotshot, and just want to have a read through to seeif some tour guide/travel agent can really write good Django

Page 6: Blog Engine Tutorial

12/23/11 Introduction

4/4sandcurves.com/blog_engine/page/introduction/

Share |

apps, you are most welcome, and most of all, please, please,please, send me your feedback. I have sort of invented thelogic side of it for myself, and may well have missed on bestpractices. Sometimes I may just have been stupid as a rock. Feel free to point that out, I would like this tutorial to be useful tosomeone. I am aware that I have at times abandoned the DRYprincipal, but I have, especially with the views, done that in thehope that it helps newbies learn easier ­ trying to learn fromtutorials where the constant drive was to make it follow the DRYprincipal too much made if hard for me, and I am sure otherbeginners, to learn.

If any bit of it doesn't make sense, please let me know. I'll try tohelp you out.

Enough chit­chat, let's build our blog…

Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 7: Blog Engine Tutorial

12/23/11 Step 1: Install Django

1/2sandcurves.com/blog_engine/page/step-1-install-django/

Step 1: Install DjangoOpen your terminal (Applications >> Accessories >> Terminal).

While you are there, just right click on it and click"Add this launcher to Panel" because you are goingto be using it a lot. You should now see the little TVlooking black icon on your panel bar at the top ofyour screen.

If you are new to terminal, don't worry, I'll help you step by step. When you open it, you should see something like this:

vernon@slick:~$

with a blinking cursor in front. In this case 'vernon' is my name,and my user name, and 'slick' is my imaginary computer'sname.

This is well covered by the documentation, so I am not going toget carried away here. Just real quick.

Open your browser (Firefox, I'll assume) and go to this page:http://www.djangoproject.com/download/ I usually set Firefox todownload to my tmp directory. If you are not to familiar with howthese things work, do the same. In Firefox, click on 'Edit'. Godown to the last option, 'preferences' and click it. A little windowopens up. Click on 'General'. Where it shows Downloads, clickon the 'save files to' bit. Click 'browse' to get the directory, andjust start typing "/tmp". It'll auto complete it for you (just pressthe tab key) and press 'close'.

Now, on the Django download page, look for this line:

First, download Django­1.2.3.tar.gz. Then:

Note, the version may have changed. Press on it todownload.

Now open your Terminal and type (with the right versionnumber, of course) all the following:

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 8: Blog Engine Tutorial

12/23/11 Step 1: Install Django

2/2sandcurves.com/blog_engine/page/step-1-install-django/

Share |

vernon@slick:~$ cd /tmp/vernon@slick:/tmp$ tar xzvf Django­1.2.3.tar.gzvernon@slick:/tmp$ cd Django­1.2.3vernon@slick:/tmp/Django­1.2.3$ sudo pythonsetup.py install

Okay, I don't want to get too carried away with installing it. If youhave trouble with that aspect, you'll find lots of help elsewhere.

« Previous Page | Return To Contents Page | Next Page »

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Django Scalable PlatformEasy deployment for Djangoapps. Python2.6 and gitintegration.www.nuagehq.com

Php Application DownloadCode and Debug Your AppsOn The Fly In The Cloud.Download the Trialwindowsazure.com

Page 9: Blog Engine Tutorial

12/23/11 Step 2: Start Project

1/3sandcurves.com/blog_engine/page/step-2-start-project/

Step 2: Start ProjectOkay, ready for the adventure to begin? Unlike PHP or similarthings, you can just put your Django project anywhere. If youhave no idea, and you are on Ubuntu (which I will assume fromnow on), create a file called 'project' in your home directory, likethis:

In your Terminal, type 'cd' to get get back to your homedirectory.

vernon@slick:/tmp$ cd

Now, lets make a project

vernon@slick:~$ mkdir project

Now, lets go into that directory:

vernon@slick:~$ cd project

Lets test that Django is on our python path. Type 'python' at theprompt:

vernon@slick:~$ pythonPython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)[GCC 4.4.3] on linux2Type "help", "copyright", "credits" or "license" formore information.>>>

Now type "import django"

>>> import django>>>

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 10: Blog Engine Tutorial

12/23/11 Step 2: Start Project

2/3sandcurves.com/blog_engine/page/step-2-start-project/

Okay, if you have Django up and running, the nextstep is to actually create our project. In yourterminal, get out of Python by holding downControl and pressing 'd'. From here on I'll simplysay 'press Ctrl­d' and you'll know what I mean.

You should see nothing. If you see something like this:

>>> import djangoTraceback (most recent call last):File "", line 1, in ImportError: No module named django>>>

then Django isn't on your python path. It probably means thatyou did something wrong with your installation. Go carefullythrough the Django documentation and try again.

Okay, now type "django­admin.py startproject zing". I'm calling itzing. You can call it by your name, or your girl/boyfriend or cat'sname, or stephanoaetus_coronatus. Anything. I would keep itshort, it'll help you when you are repeatedly typing that into yourterminal.

vernon@slick:~/project$ django­admin.pystartproject zing

That creates a directory called 'zing' (or whatever you namedit). If you are not familiar with the Linux file systems, you have ahierarchy of directories, starting from '/' as the base directory,into your '/home/username'. When we created 'project' thatwould be '/home/username/project' and now with the djangoproject 'zing' that we created inside of it, we get'/home/username/project/zing'. In our terminal we are still in the'project' directory. Lets go into the 'zing' directory with the 'cd'command again:

vernon@slick:~/project$ cd zingvernon@slick:~/project/zing$

Now, let's see what we made. To see what is in the directory,we use the command 'ls':

vernon@slick:~/project/zing$ ls__init__.py manage.py settings.py urls.pyvernon@slick:~/project/zing$

Okay, if you just want to see what is in a file without actuallygoing into it, you can use the command 'cat'. Don't worry if youdon't understand anything, or if it looks scarry, just type 'cat' and

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Shell Scripting TutorialsIndia's Only ComputerTraining Inst by CorporateTrainers. Register Nowwww.networknuts.net

Logistic Solutions?Airfreight, Seafreight, Road­and Rail Transport & NextDay Delivery!www.mablogistics.com

Page 11: Blog Engine Tutorial

12/23/11 Step 2: Start Project

3/3sandcurves.com/blog_engine/page/step-2-start-project/

Share |

each of the filenames, '__init__.py' 'manage.py', 'cat settings.py','cat urls.py'

vernon@slick:~/project/zing$ cat __init__.pyvernon@slick:~/project/zing$ cat manage.py#!/usr/bin/env pythonfrom django.core.management importexecute_managertry:import settings # Assumed to be in the samedirectory.except ImportError:import syssys.stderr.write("Error: Can't find the file'settings.py' in the directory containing %r. Itappears you've c.................and so on.....

Mmmm, strange thing that __init__.py file didn't seem to haveanything in it. That is a Python thing. Each directory has tohave one of those empty files to make Python treat it as apython package.

As for the rest, we'll get there soon

Pat yourself on the back, you've created a Django project. Itdoesn't do anything, but there it is, all shiny…

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 12: Blog Engine Tutorial

12/23/11 Step 3: Create Base HTML Template

1/4sandcurves.com/blog_engine/page/step-3-create-base-html-template/

Step 3: Create Base HTML TemplateOkay, here I am going to diverge from the normal Djangotutorials, because I want this tutorial to include everything, andthat means that we need to write some HTML as well.

I'm going to assume a little more familiarity with HTML than I didwith the Terminal, but I'll still mostly spell everything out. I wantto be sure that almost anyone reading this tutorial will be able tobuild a blog for themselves.

We can stay in the 'zing' directory for now. Lets make anotherdirectory within it, and call it 'template'.

vernon@slick:~/project/zing$ mkdir templatevernon@slick:~/project/zing$ cd template

Lets create our HTML file. You can type this in any plain texteditor, like Gedit or whatever you use. Just make sure it is not aword processor or a wysiwyg editor. I'm going to use Emacs asmy example.

vernon@slick:~/project/zing/template$ emacsbase.html

This will open your emacs file. Change Emacs for gedit orbluefish or anything whatever it is you use. It must just besomething that is on your system. If you are happy with nano orsomething like that, be my guest. If you have no idea, and youare on the Gnome Ubuntu desktop, just stick with Gedit.

Type the following:

<doctype html>

<html>

<meta charset="UTF­8">

<title>Zing Blog</title>

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 13: Blog Engine Tutorial

12/23/11 Step 3: Create Base HTML Template

2/4sandcurves.com/blog_engine/page/step-3-create-base-html-template/

<link rel="alternate" type="application/rss+xml"title="rss for zing" href="#### We'll come back tothis ####"≷<link rel="stylesheet" type="text/css"href="/media/css/style.css"><link rel="icon" type="image/gif"href="/media/zing.ico"><meta name="description" content="My wonderfulblog"><meta name="robots" content="all">

</head><body>

<!­­ Start title ­­><div id="title">

<h1>Zing Blog</h1><h2>The blog</h2> <!­­ End title ­­></div>

<!­­ Start content ­­><div id="content">

<!­­ End content ­­></div>

<!­­ Start sidebar ­­><div id="sidebar">

<!­­ End sidebar ­­></div>

<!­­ Start footer ­­><div id="footer">

<!­­ End footer ­­></div>

</body></html>

So far, if you know HTML, simple and normal. I included someof the common header stuff, just because I am aiming to makethis tutorial as complete as possible.

Now, lets add the Django stuff. These template tags are going

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Php Application DownloadCode and Debug Your AppsOn The Fly In The Cloud.Download the Trialwindowsazure.com

Jaypee Green Sports CityThe Kove:2/3/4BHK Apts,Delhi/NCR With WorldClassAmenities­View Now!www.Jaypeegreensthekove.com

Page 14: Blog Engine Tutorial

12/23/11 Step 3: Create Base HTML Template

3/4sandcurves.com/blog_engine/page/step-3-create-base-html-template/

to turn your HTML file from a normal one into a template. Addthe text written in red.

<doctype html>

<html>

<meta charset="UTF­8">

<title>% block title %Zing Blog% endblock%</title>

<link rel="alternate" type="application/rss+xml"title="rss for zing" href="#### We'll come back tothis ####"><link rel="stylesheet" type="text/css"href="/media/css/style.css"><link rel="icon" type="image/gif"href="/media/zing.ico"><meta name="description" content="My wonderfulblog"><meta name="robots" content="all">

</head><body>

<!­­ Start title ­­><div id="title">

<h1>Zing Blog</h1><h2>% block under_title %The blog% endblock%</h2>

<!­­ End title ­­></div>

<!­­ Start content ­­><div id="content">

% block content % Here be blog stuff %endblock % <!­­ End content ­­></div>

<!­­ Start sidebar ­­><div id="sidebar">

<!­­ End sidebar ­­></div>

<!­­ Start footer ­­><div id="footer">

Page 15: Blog Engine Tutorial

12/23/11 Step 3: Create Base HTML Template

4/4sandcurves.com/blog_engine/page/step-3-create-base-html-template/

Share |

<p>Copyright your_name &copy; 2010</p><!­­ End footer ­­></div>

</body></html>

Okay, you don't have to go to all the trouble to write it all out. Just copy and paste it from mine. But do take the time to have alook at it carefully so that you can see what is going on.

Once you are done, save it and close your text editor.

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 16: Blog Engine Tutorial

12/23/11 Step 4: Create CSS file

1/3sandcurves.com/blog_engine/page/step-4-create-css-file/

Step 4: Create CSS fileWe have written a lot of HTML stuff, right. Our website must begreat. Take a look:

vernon@slick:~/project/zing/template$ firefoxbase.html

Vernon, that isn't cool:

ZingBlog% block under_title %Theblog% endblock %% block content % Here be blog stuff %endblock %

Copyright your_name © 2010

Okay, and CSS isn't going to save us yet either, bear with me. We just want to add some simple css for the time being. Whenwe upload the site we are going to change things, but for nowjust add the CSS to the file itself.

Open the base.html file in your text editor again "emacs

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 17: Blog Engine Tutorial

12/23/11 Step 4: Create CSS file

2/3sandcurves.com/blog_engine/page/step-4-create-css-file/

base.html"

Just ignore this line:<link rel="stylesheet" type="text/css" href="/media/css/style.css">for now. We'll get back to it.

Add the bit in red to your site.

<doctype html>

<html>

<meta charset="UTF­8">

<title>% block title %Zing Blog% endblock %</title>

<link rel="alternate" type="application/rss+xml"title="rss for zing" href="#### We'll come back tothis ####"≷<link rel="stylesheet" type="text/css"href="/media/css/style.css"><link rel="icon" type="image/gif"href="/media/zing.ico"><meta name="description" content="My wonderfulblog"><meta name="robots" content="all">

<style type="text/css">

/* Page */bodypadding:0;margin:0;font­family:Arial,Helvetica, Tahoma, sans­serif;/* Title section */#titlefloat:left;width:100%;padding:0;margin:0;border:0;border­bottom:1px solid #cccccc;#title h1padding:10px 0 0 50px;font­size:60pt;margin:0;font­family:"Myriad Pro", Arial,Helvetica, Tahoma, sans­serif;#title h2margin:0;padding:0;text­align:center;/* Content section */#contentfloat:left;border:0;margin:0;padding:10px2% 0 2%;width:75%;/* Sidebar section */#sidebarfloat:left;border:0;border­left:1px solid#cccccc;padding;10px 2% 02%;width:20%;margin:0;/* Footer section */#footerfloat:left;border:0;border­top:1px solid#cccccc;padding:0;margin:0;width:100%;text­align:center;

</style>

</head><body>

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Free Website For BusinessEasily Create A Website In 15Mins. Free From Google ToYour Business!www.indiagetonline.in

Want To Design AWebsite?Design Your Website By TheBest Web Design Company InIndia. See More

Page 18: Blog Engine Tutorial

12/23/11 Step 4: Create CSS file

3/3sandcurves.com/blog_engine/page/step-4-create-css-file/

Share |

<!­­ Start title ­­><div id="title">

<h1>Zing Blog</h1><h2>% block under_title %The blog% endblock%</h2>

<!­­ End title ­­></div>

<!­­ Start content ­­><div id="content">

% block content % Here be blog stuff %endblock % <!­­ End content ­­></div>

<!­­ Start sidebar ­­><div id="sidebar">

<!­­ End sidebar ­­></div>

<!­­ Start footer ­­><div id="footer"><p>Copyright your_name &copy; 2010</p><!­­ End footer ­­></div>

</body></html>

Okay, that's not very fancy, but I'll leave the rest of that up toyou. For the tutorial, just leave it like that before you spendhours trying to get your site looking just right; Lets get back toDjango…

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 19: Blog Engine Tutorial

12/23/11 Step 5: Start Blogging app

1/2sandcurves.com/blog_engine/page/step-5-start-blogging-app/

Step 5: Start Blogging appClose your text editor for now, and go back to your Terminal.

If you still have the site open in Firefox, and opened it withTerminal, just close it. You don't even need to bookmark itbecause the next time we look at the site we are going to berunning your own server (thanks Django).

We left off in our template directory and we want to go back tothe 'zing' directory to create our application. Type the following:

vernon@slick:~/project/zing/template$ cd ../

Double dots '..' refers in Linux file system to the parentdirectory. You could get back all the way by chaining themtogether "cd ../../../" Anyway, lets get back to building our blog.

vernon@slick:~/project/zing$ python manage.pystartapp blogvernon@slick:~/project/zing$ lsblog __init__.pyc settings.py template__init__.py manage.py settings.pyc urls.py

If you are familiar with Python, you'll know those .pyc files arejust compiled version of the normal .py files in Python. Eachtime a file is run for the first time, Python makes you a compiledversion (compiled bytecode). Type:

vernon@slick:~/project/zing$ cat settings.pyc

See, crazy stuff for your computer to read. You'll get use to it,when you look at your python directories, you'll sort of look onlyfor the .py.

More importantly, when you ran the 'ls' command, you saw thenew 'blog' directory sitting there. Django was kind enough towrite some stuff for you in there already. Have a look with thiscommand:

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 20: Blog Engine Tutorial

12/23/11 Step 5: Start Blogging app

2/2sandcurves.com/blog_engine/page/step-5-start-blogging-app/

Share |

vernon@slick:~/project/zing$ ls blog__init__.py models.py tests.py views.py

There is another '__init__.py file that you know already. We arenot going to touch the test.py file (you can delete if if you likeeverything neat and clean. You'll get to know the rest later.

Please, if you feel a little overwhelmed at this point, don'tgive up. If you get stuck, please give me some feedback ­ youcan just send me a tweet at @sandcurves or contact me throughthe contact page.

« Previous Page | Return To Contents Page | Next Page »

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

BlogsBlogs and discussions led bybusiness intelligence gurus.Go!www.AllAnalytics.com

Jaypee Green Sports CityThe Kove:2/3/4BHK Apts,Delhi/NCR With WorldClassAmenities­View Now!www.Jaypeegreensthekove.com

Page 21: Blog Engine Tutorial

12/23/11 Step 6: Set Up Database

1/3sandcurves.com/blog_engine/page/step-6-set-database/

Step 6: Set Up DatabaseLater on we'll use MySQL on your actual host server, but fordevelopment, we'll use sqlite3. It should already be on yoursystem, but maybe not on your file path. Type the following inyour terminal:

vernon@slick:~/project/zing$ sqlite3

You should see something like this:

SQLite version 3.6.22Enter ".help" for instructionsEnter SQL statements terminated with a ";"sqlite>

If nothing happens, lets just fix that the easy way:

vernon@slick:~/project/zing$ sudo apt­get installsqlite3

Done, good.

Now, if you were scared off by the thought of the database, don'tbe. All we have left to do is tell Django about our database, andwe'll do that with the settings.py file.

You can open the settings file from your Terminal again. Fromnow on I'll just say emacs, but you know that you can usewhatever your favorite text editor is.

vernon@slick:~/project/zing$ emacs settings.py

At first glance the settings.py file might look a little daunting, butyou'll soon get use to it. We are going to do a few things inhere. Don't be to worried about doing the wrong thing. If it allgoes wrong you can just delete the entire project and start from

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 22: Blog Engine Tutorial

12/23/11 Step 6: Set Up Database

2/3sandcurves.com/blog_engine/page/step-6-set-database/

scratch.

For now, lets edit a few things. First up, scroll down to thissection:

DATABASES = 'default': 'ENGINE': 'django.db.backends.', # Add'postgresql_psycopg2', 'postgresql', 'mysql','sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if usingsqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost.Not used with sqlite3. 'PORT': '', # Set to empty string for default.Not used with sqlite3.

Anything after a '#' in Python is a comment. Read some of thatand you'll see why we start with sqlite3. Change it to this:

DATABASES = 'default': 'ENGINE': 'sqlite3', 'NAME': 'zing.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '',

That should be really easy. Once we start working with MySQLit is a little more complex. You can either delete or keep thecomments. It doesn't really matter.

We specified two things, that we were going to use sqlite3 andthe name. Actually, in the case of sqlite3 we also specified thefile path, and for now we are just going to have it right here, inthe zing directory.

While we are here, lets do something else. Lets add ourtemplate directory. Scroll down to where it says:TEMPLATE_DIRS = ( and change it like this:

TEMPLATE_DIRS = ( '/home/username/project/zing/template')

If you are not familiar with Python, it is really important to keepthe spaces. Keep the indentation to four spaces. If you don'tunderstand what I am talking about, almost any introduction to

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Mobil Engine OilWorld's Famous Brand For Oilengine Learn How We AreBetter Than OthersMobil1.co.in

Database SystemBusiness intelligence expertssharing their secrets with you.Go!www.AllAnalytics.com

Page 23: Blog Engine Tutorial

12/23/11 Step 6: Set Up Database

3/3sandcurves.com/blog_engine/page/step-6-set-database/

Share |

Python will clear that up for you.

We'll be back in the settings.py file later on, but for now we justwant to change one last thing. In the INSTALLED_APPSsection (right at the bottom), change it like this (add the bit inred):

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', # Uncomment the next line to enable the admin: # 'django.contrib.admin', 'zing.blog',)

This is a Python tuple, and it is a good idea to put that comma atthe end (in case you add more.)

We have now told our project which database to use, where tofind our HTML templates and which apps we have created.

Close the text editor and go back to your Terminal again. Dolike so:

vernon@slick:~/project/zing$ python manage.pyvalidate0 errors found

If you get errors, you have done something wrong above. Lookthrough all the steps carefully, and if you can't figure it out, onedrastic option is just to delete the whole thing and start again. You can do this by going to the projects directory, and typing 'rm­r *'. Then you'll have to start from the top again.

I am going to assume all is well and we can carry on.

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 24: Blog Engine Tutorial

12/23/11 Step 7: Write the Model

1/3sandcurves.com/blog_engine/page/step-7-write-model/

Step 7: Write the ModelOkay, now we are going to actually create our database and putsomething in it. If you have ever tried to work with PHP creatingwebsites and using database calls, this is going to be lovely.

I'm going to assume you are catching on the terminal now, anddon't need everything displayed. In your Terminal, type 'cd blog'to get yourself into your blog directory. Open your models.py filein your text editor. Leave the top line, delete the comment line,and add the red below:

from django.db import modelsfrom datetime import datetime

class Category(models.Model): name = models.CharField(max_length=60) def __unicode__(self): return self.name

class Tags(models.Model): name = models.CharField(max_length=60) def __unicode__(self): return self.name

class Post(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=120,unique=True) description = models.TextField() body = models.TextField() published =models.DateTimeField(default=datetime.now) categories = models.ForeignKey(Category) tags = models.ManyToManyField(Tags) def __unicode__(self): return self.title class Meta: ordering = ['­published']

Mmmm… that looks complicated. Actually, it is, but I am sureyou can get the feeling for what we are doing here reallyquickly. We have three classes, but the third one (class Post)

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 25: Blog Engine Tutorial

12/23/11 Step 7: Write the Model

2/3sandcurves.com/blog_engine/page/step-7-write-model/

should tell you basically everything we are doing here In ourblog we want a title, a body, the date it was published, tagsand categories. So all those lines should make sense.

On Sandcurves.com I haven't worried to much about gettingcategories and tags right, but for you, I'm trying to do it right. You can later decide exactly how to implement it, but I amgoing to assume each post has one category, but can haveseveral tags. Here is more on that line of thinking: Tags &Categories dicussion on Problogger.net

We used two TextFields, body and description. That is reallynice if you want a little slug on a main page and the whole poston a detail page. We'll get back to that later. You may not liketo do it that way, but I have found it solves the really tricky stuffof doing that splitting with Python. For now, do it my way, followalong and see how it works.

At the top of the file, the second line, we importeddatetime.datetime. This was needed to implement the publishedfield.

The one unusual thing is the slug field, and it, like the body anddescription fields, is also to help us out a little. The slug is simplya url friendly version of your title, for making the url of your blogpost. We'll get to that.

The other two classes (Categories and Tags) are there to dealwith relationships, meaning the things in those fields are notunique to one blog post, so we want separate tables in ourdatabase for them. If you want to understand it all better, have alook at this page:http://docs.djangoproject.com/en/dev/ref/models/fields/

The rest is quiet self explanatory. Be sure you got theindentation right again, it is important.

Now, close that file, go back into your Terminal, go back to the'zing' directory with 'cd ../'. Now type this again, just to makesure we did everything right:

vernon@slick:~/project/zing$ python manage.pyvalidate0 errors found

If you got errors, perhaps look at the indentation carefully. Good, now type this:

vernon@slick:~/project/zing$ python manage.pysqlall blog

If all has gone well, you get this wonderful database dumpoutput, in nice colors. It looks like it did a lot, but actually it didn'tdo anything. It was just showing you that all's well.

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Jaypee Green Sports CityThe Kove:2/3/4BHK Apts,Delhi/NCR With WorldClassAmenities­View Now!www.Jaypeegreensthekove.com

Latest Bollywood VideosStay Updated On YourFavorite Video CheckYahooFor Full length Video's.www.yahoo.com/video

Page 26: Blog Engine Tutorial

12/23/11 Step 7: Write the Model

3/3sandcurves.com/blog_engine/page/step-7-write-model/

Share |

To actually start to do stuff, type:

vernon@slick:~/project/zing$ python manage.pysyncdb

I'm not going to go into it too much here, but the term 'syncdb'can be a little misleading if you are just starting out with it. Manychanges to your database can't be made with it. Use thatcommand to create new tables, but when you have mistakes,you'll want to actually go into the database shell and fix it there. That's a bit to much to get into for now with this tutorial. Fornow, especially with sqlite3 while you are just starting out (andhave no valuable data in your database), you can just delete thedatabase and re­run 'python manage.py syncdb'.

Okay, back to the job at hand. While you ran that, it was goingto ask you if you wanted to create a superuser. The answer, ofcourse, is yes. I'm sure you can come up with your own names. While you are working on sqlite3, make the password simple. And write it down, you'll want to remember it. I used 'vernon' formy username and, for now, 'yup' for my password. Dosomething similar.

I hope you admired all that database stuff it created. If you type'ls' in Terminal, in the 'zing' directory, you will see the newdatabase file sitting there, 'zing.db'. If you are like me, youprobably already tried to see what is in it. 'cat zind.db' againgives you a meaningless jumble of stuff. If you really want tohave a look, type "sqlite3 zing.db" and then type '.table' Whenyou want to get out, just type 'Ctrl­D' Django gives you a shellfor dealing with your database as well, (with 'python manage.pydbshell') I'm sure you can find out more for yourself with the helpof Google. Lets move on to more adventures.

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 27: Blog Engine Tutorial

12/23/11 Step 8: Write the Admin

1/3sandcurves.com/blog_engine/page/step-8-write-admin/

Step 8: Write the AdminIf you want to blog, you need a back end interface that allowsyou to do that. With Django, the admin interface is included withvery little fuss.

First, lets create an admin file in the blog application to handleour… blog. If you are in Terminal, in your zing directory, type 'cdblog' to get you back in the blog directory. Now, type "emacsadmin.py" to create and open your admin.py file, the file that isgoing to tell Django what we want for our admin interface for theblog.

Now, in that file, type the following content:

from django.contrib import adminfrom zing.blog.models import *

class PostAdmin(admin.ModelAdmin): filter_horizontal = ('tags',) list_display = ('title', 'published',) prepopulated_fields = 'slug': ('title',)

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

Try to have a look through that code as well and understand it. At the top, in the second line we imported our blog models thatwe created before (Tags, Category and Post). The PostAdminclass was just there to tell it how to render some of the fields. Take note of the last line of that class. We are telling the adminsite to pre­populate the 'slug' field with the contents of the titlefield. This is very nice. It means that when you type a title forthe blog, it is going to just fill in the slug field for you.

The last three lines should be obvious, registering each site tobe included with the admin interface.

Okay, a couple small things left to do. First, go back to the 'zing'directory and open up your settings.py file in your text editoragain.

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 28: Blog Engine Tutorial

12/23/11 Step 8: Write the Admin

2/3sandcurves.com/blog_engine/page/step-8-write-admin/

Now, scroll right to the bottom, and look at the last few lines ofthe INSTALLED_APPS bit. See the two commented lines,delete the top one, and uncomment the second like this:

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'zing.blog',)

Close that file and open one we haven't touched so far, theurls.py. First, before we start to change anything, read all thecontents.

Okay, now you can actually just delete everything except thelines that I show below:

from django.conf.urls.defaults import *

from django.contrib import adminadmin.autodiscover()

urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)),)

The url file allow us to map a given url to the content we want itto put out. This is very different to a normal website, but we'llget into that more later. For now just save the file. You can seethat most of what we left behind has to do with the admin site.

Now, we need to add the admin stuff to the database.

You can type 'python manage.py validate' again in yourTerminal just to make sure all is well. Then run 'pythonmanage.py syncdb' again.

Now, open a second terminal, and change to the zing directory('cd project/zing' will get you there). Once in the 'zing' directory,type:

vernon@slick:~/project/zing$ python manage.pyrunserver

This was our free server, included with Django. It is not a heavylifter, so don't use it to serve your site on the Internet. But fordevelopment, it is great.

Now for some fun. Open Firefox again, and enter the followingurl: http://127.0.0.1:8000/

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

BlogsGet great ideas and insightsfrom business intelligencegurus. Go!www.AllAnalytics.com

Jaypee Green Sports CityBiggest Residntial PlannedTownship Presents TheKove,2­4 BHK.Book Now!www.Jaypeegreensthekove.com

Page 29: Blog Engine Tutorial

12/23/11 Step 8: Write the Admin

3/3sandcurves.com/blog_engine/page/step-8-write-admin/

Share |

Okay, you get an error? If it is saying "Page not found" you arefine. If it is some other error, Django gives you heaps of info inthere to try to figure out what you did.

Assuming you got through all that, add 'admin/' to the end of theurl, and this time you should get a login screen.

Remember the superuser we created above… log in with thatuser name and password. You get greeted with this fantasticadmin page.

See the 'Blog' section… we did that! Okay, now click on 'Posts'. What do you see? "0 posts" Of course, we haven't added anyblog posts yet.

In the upper right and side of the page, click on 'add post'. Thisis the page you are going to come to each time you want tocreate a blog post. Okay, be patient, we'll be back here in notime.

Close it all up. We have built the back end, now lets get towriting the actual blog app logic.

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 30: Blog Engine Tutorial

12/23/11 Step 9: Write the View

1/10sandcurves.com/blog_engine/page/step-9-write-view/

Step 9: Write the ViewI don't want to get to much into Django background andphilosophy (there is plenty of info on the web on what Django isabout already). But, just a little idea would be in order here.

Django is more than a CMS, it is a web framework and if you arefamiliar with MVC, Django follows a similar idea. Django hascome up with it's own way of expressing it ­ MTV (Model,Template, View). If you aren't familiar with CMS and MVC, lookthem up, there is plenty of info on the web. I'm only going to talkabout Django's way here.

The idea behind this MTV approach is that we work with threeaspects to create our websites. The Model expresses thedatabase side (as you saw when we created the models.py file).The Template is the HTML, CSS and everything needed toserve that up. The plug between the two is the view, which, inDjango's way of doing things, is the logic.

To put it in really simple terms, we have stuff in our database(models), we have ways to show the stuff (templates) and wehave the logic of what stuff to show where (views).

Good, that's all I'll say about that. You can read more, justGoogle it, or follow the link I gave above. But for now, forgetabout it, and lets concentrate on creating the views for our blog.

Our views.py file is in the blog app, remember. Open it up in atext editor. I am sure you know how to do that by now. You canopen up a second Terminal at this point, to keep one runningour development server.

Bear with me on the views, because I think it is the part of theapplication where you need to really understand what you aredoing. Django comes with generic view, where common logic isbundled together and you don't need to program your own viewat all, and this stuff is actually great for blog, but for now, lets getdown and dirty and write the logic out ourselves. There is a lotof advantage to this, of course… you can twist your site yourway and do really fun things. You'll want to really get intoPython properly in order to take full advantage of the capabilityprovided by the views.

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 31: Blog Engine Tutorial

12/23/11 Step 9: Write the View

2/10sandcurves.com/blog_engine/page/step-9-write-view/

Django gives you lots of ways of doing things, but in the viewswe have a special class called render_to_response. We cansort our logic out in the view, and pass it on using therender_to_response method. It is a part of the django.shortcutspackage, which provides, you guessed, shortcuts. So our firststep is to import that into our view.

from django.shortcuts import render_to_response

Next, we need the stuff from our database. No nasty databasecode needed. We'll just import the models classes and get onwith it. We can do a wildcard (with '*') import, but rememberthey were Post, Tags and Category.

from django.shortcuts import render_to_responsefrom zing.blog.models import *

We are going to import two more thing that we'll get back tolater, the HttpResponseRedirect and datetime. TheHttpResponseRedirect allows us to redirect pages, and you'llsee why later on. The datetime is useful when we are workingwith, you guessed, dates.

from django.shortcuts import render_to_responsefrom zing.blog.models import *from django.http import HttpResponseRedirect

Okay, if you were building your own blog at this point you shouldpause, perhaps get away from a computer and think really hardabout what you want to serve up, and how. Dream up the urlpatterns, and all the bits of contents, and then work on makingpython serve that up by passing in chunks of code that yourtemplate can read. In this case, of course, you don't know howto do that, so lets make a list of wants, and then we'll go aboutcrafting them.

Okay, for this blog application, here is our list:

1. What: A home page with the latest 7 posts. Why7? It really doesn't matter. For this blog we aregoing with 7. How: http://site_name/ This is our homepage.

2. What: A detail page, where we can view the wholepost and add comments.How: http://site_name/year/month/slug/ So we'llhave the year (four numbers, like 2010), the month(two numbers, like 07) and the post slug (rememberthat from our models.py file? This is where we aregoing to use it.

3. What: A page listing all months of a given year. How: http://site_name/year/ This is going to list allthe months of that year, which can be clicked to seeall the posts on that month

4. What: A page listing all posts by month. How: http://site_name/year/month/ This is going

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Django Cloud HostingProduction hosting with push­button deploymentgondor.io

VenzZend PackageWeb development startup kit.Save thousands indevelopment cost.www.venzon­solution.com/

Page 32: Blog Engine Tutorial

12/23/11 Step 9: Write the View

3/10sandcurves.com/blog_engine/page/step-9-write-view/

to list all the months of that year, which can beclicked to see all the posts on that month

5. What: Archive pages, going back after the firstpage in chunks of 10 (just for a rounder number). How: http://site_name/archive/number/ Thenumber refers to numbered archive pages. Ourhome page shows seven, so archive page 1(http://site_name/archive/1/) is going to show us theposts 8 to 17. We could duplicate (or put apermanent redirect.)

6. What: A page listing all the categories. How: http://site_name/category/

7. What: A page listing all the posts per category. How: http://site_name/category/category_name/ Category_name refers, of course, to the name ofthe category.

8. What: A page listing all the tags. How: http://site_name/tags/ A page listing all thetags

9. What: A page listing all the posts tagged with aspecific tag. How: http://site_name/tags/tag_name/ Thetag_name is the name of the tag. A page that listsall the posts for that tag.

We also want a sidebar, which we'll 'include' which will havenavigation, RSS feed, a list of categories and a list of tags. Thisdoesn't affect what we put in our views, but it will be the mainway that some of those pages are linked to.

Note that the month and year patterns mean that if someonechops off the url at the end, they get another useful page. Wedon't actually want to create a link to the year page (It's notmuch use), but we want a site that has intelligent urls in place,and hense any URL that is cut short should be worth somethingand contribute to our website.

Okay, let's build the core functionality. We don't build the urls inthe views, but I find it is a really good way to think about it. Solets just put them in as comments. We'll put the archives andthe home page in one function, because they are doing thesame thing. You'll soon see what I mean. We are not reallyfollowing the DRY principal (don't repeat yourself), but most ofour repeating is really simple stuff, and it helps us understandexactly what we are building. You are more than welcome tocombine the functions afterwords, as you see fit.

from django.shortcuts import render_to_responsefrom zing.blog.models import *

#http://site_name/ andhttp://site_name/archives/number/#http://site_name/year/month/slug/#http://site_name/year/month#http://site_name/year/#http://site_name/category#http://site_name/category/category_name#http://site_name/tag/tag_name

Page 33: Blog Engine Tutorial

12/23/11 Step 9: Write the View

4/10sandcurves.com/blog_engine/page/step-9-write-view/

#http://site_name/tag/

No we need to build a function around each of those, that getsthe request (which comes from the user's browser ­ saying giveme the page. So our first line is a function call, with onearguement, the request object. Don't worry if you don'tunderstand, just follow along. It should all become more clearas we move along.

We need to serve a page and have a way to stick stuff in it, andour render_to_response gives us one quick, easy way to do justthat.

So, lets fill out our views.py much more. This is starting to looklike a lot, but trust me, it isn't hard to understand so far. We arejust doing a lot of the same thing. When you become moreproficient at it, you'll combine a lot of these, but I want to spell itall out.

from django.shortcuts import render_to_responsefrom zing.blog.models import *

def list(request): #http://site_name/ andhttp://site_name/archives/number/ return render_to_response('base.html', ,)

def detail(request): #http://site_name/year/month/slug/ return render_to_response('base.html', ,)

def month(request): #http://site_name/year/month return render_to_response('base.html', ,)

def year(request): #http://site_name/year/ return render_to_response('base.html', ,)

def category(request): #http://site_name/category return render_to_response('base.html', ,)

def one_category(request): #http://site_name/category/category_name/ return render_to_response('base.html', ,)

def one_tag(request): #http://site_name/tag/tag_name/ return render_to_response('base.html', ,)

def tag(request): #http://site_name/tag/ return render_to_response('base.html', ,)

Page 34: Blog Engine Tutorial

12/23/11 Step 9: Write the View

5/10sandcurves.com/blog_engine/page/step-9-write-view/

Okay, to make it more readable, we are going to break it up abit. I'll build each function by itself first.

Note that we have an html file in the return value of the function. I have just put in "base.html" but actually we are going to changethat ­ you'll see.

Lets first do the list page. So we want 7 items on this page anda link to the next lot in the archives, and a previous link when wego further down the archive. Does that make sense? If youdon't understand what I am doing, I think just following along atthis point will soon clear it all up.

We are going to need to import one other thing on this page, thearchive page number. Because our first page doesn't have anumber we can use one of the wonderful little tricks of Python,give a default value. I'll build this first function and then explain.

def list(request, archive=1): #http://site_name/ andhttp://site_name/archives/number/ page = (int(archive)*7) if Post.objects.all().count() > page + 7: posts = Post.objects.order_by('­published')[page­7:page] else: posts = Post.objects.order_by('­published')[page­7:] # next and previous archive pages if Post.objects.all().count() > page next = (int(archive)) + 1 else: next = 0 previous = (int(archive)) ­ 1 return render_to_response('base.html','posts':posts, 'next':next, 'previous':previous, ,)

In the function declaration at the top, we assign a value toarchive as a default value. If the url contains/archive/some_number/ then the number will be passed toarchive (we'll get to how exactly that happens when we talkabout the urlconfig later on).

The next thing is the page variable, where we are creating avariable that is going to give us chunks of seven. So, if we go toarchive page 3, we are going to be looking at posts 22 onwards,and so on.

If you have any familiarity with programming at all, you'll knowabout types (ints, strings, floats and so on). We have to changethe value of the archive variable to an int (type coercion). This is

Page 35: Blog Engine Tutorial

12/23/11 Step 9: Write the View

6/10sandcurves.com/blog_engine/page/step-9-write-view/

because what we get from the url is a string.

Then we have an if statement. This is just in­case we have tofew posts in our database to show seven posts of the first page. So, if we have enough we are going to show seven posts. Remember the Models.py file. We imported everything fromzing.blog.models, and this included Post. Now we are actuallycalling our database and getting a set of objects that match ourquery. Easy, ha?

Post.objects.order_by('­published')[page + 7:page]It is rather simple to understand what we did here. the'order_by' does exactly what it says, and can order based onnumerals or alphabetical. In our case, we have a value'published' for each object, and by adding a minus in front weget the reverse order. '­published'.

If you know a little Python, you'll know about list slicing. If youdon't, it is a useful thing to know about, try reading up on it a bit.

I did some funny logic here, with one multiplying out to be seven,and then I delete 7 again to get the first post. Just trust me thatit works better this way.

If we don't have seven items on that page yet, we can just chopit off at whatever the end value is (hence the list slicing with amissing end number ­ in Python this just means "give meeverything from my starting value until the end").

There is one small problem that we can take care of from hereas well, and that is how to know what the next page andprevious pages are. We'll put a comment in, just so we know weare now dealing with the next bit of logic.

All we need to do is pass the value more than and less than the'archive' variable. Simple to do, but there is a catch, we alsowant to know when we don't have any more archive pages. Wesolve this for next with a simple if statement and make sure thatthere are still values left. For 'previous' we don't actually have toworry, and we'll get to how we work with these guys later.

It should become clear that there is one last annoyance. If weare back at archive page 1, we don't want the url to besite_name/archive/1/, but rather we would like to redirect thatpage to the homepage.

We'll fix that with a simple redirect. Have a look back at the lastthing we imported when we first started working on the views.pyfile.

def list(request, archive=1): #http://site_name/ andhttp://site_name/archives/number/ if archive == "1": return HttpResponseRedirect("/") page = (int(archive)*7) if Post.objects.all().count() > page + 7: posts = Post.objects.order_by('­published')

Page 36: Blog Engine Tutorial

12/23/11 Step 9: Write the View

7/10sandcurves.com/blog_engine/page/step-9-write-view/

[page­7:page] else: posts = Post.objects.order_by('­published')[page­7:] # next and previous archive pages if Post.objects.all().count() > page next = (int(archive)) + 1 else: next = 0 previous = (int(archive)) ­ 1 return render_to_response('base.html','posts':posts, 'next':next, 'previous':previous, ,)

As simple as that. We tested for a string (that is why the onewas in quotes) to see if it came like that from the url.

Alright, the next stop is our detail page. This is the one wherewe actually show the single blog post.

def detail(request, sl): #http://site_name/year/month/slug/ try: post = Post.objects.filter(slug=sl)[0] try: previous_post =post.get_previous_by_published() except: previous_post = "" try: next_post = post.get_next_by_published() except: next_post = "" except: next_post = "" previous_post = "" post = "" return render_to_response('base.html','post':post, 'next_post':next_post, 'previous_post':previous_post, ,)

As you can see, getting the post value is so simple. You'll seewe put a '[]' at the end. This allows us to return one value,rather than a whole queryset, so we can call it directly from thevariable, not having to iterate over it.

Page 37: Blog Engine Tutorial

12/23/11 Step 9: Write the View

8/10sandcurves.com/blog_engine/page/step-9-write-view/

The more difficult stuff (well, it isn't difficult) is getting theprevious and next posts. Django makes this super easy for usby providing as 'get_next_by' function that we can use todetermine the next and previous posts.

Again, when we run out, we assign Null values to avoid errors. You can see that I build the whole thing with error handling (thetry/except). As you know, we don't want to break our websitebecause of stupid coding issues.

The way that we derived the post for this url just ignores the yearand the date. That means that if someone enters the wrongyear, but gets the slug right, they will still see the right blog post. To change that you would need to pass in more parametersfrom the url, and filter the results further. I'm not going to worryabout that here. You should be able to do that yourself withoutany issue by the time you have finished this tutorial.

The next one is a simple one, getting the posts for a givenmonth.

def month(request, year, month): #http://site_name/year/month/ date = datetime.datetime(int(year), int(month),1) try: posts = Post.objects.order_by('­published').filter(published__year=year).filter(published__month=month) except: posts = "" return render_to_response('base.html','posts':posts, 'date':date, ,)

Of course you need the year in the equation as well for findingthe month ­ the given month is repeated each year, so we filterboth for year and for month.

You can keep working that section a lot. You can test if thereare months that are written wrong, if the dates given are in thefuture and so on. And then return different error messages forthem (you'll see when we get to templates). For now, let's justkeep it simple.

Just to help us make nice title tags (wait till you are in thetemplates), we'll also pass in a date value. We need to givedatetime.datetime a year, a month and a day. We don't have, orcare, about the day (we don't need to derive it in our templates),so we'll just make it the first of whatever month we have, hencethe 1.

Now, chop off the month and let's work with the year.

Page 38: Blog Engine Tutorial

12/23/11 Step 9: Write the View

9/10sandcurves.com/blog_engine/page/step-9-write-view/

def year(request, year): #http://site_name/year/ post_error = "" year = int(year) yr = datetime.datetime(year, 1, 1) months =12 by_month = [] ifPost.objects.filter(published__year=year).count(): if year == datetime.datetime.now().year: months = datetime.datetime.now().month for month in range(1, months+1): by_month.append(datetime.datetime(year,month, 1): Post.objects.filter(published__month=month).filter(published__year=year)) elif year > datetime.datetime.now().year: post_error = "It is not yet %d, try an earlieryear." % year else: post_error = "There are no posts for %d." %year return render_to_response('base.html','by_month':by_month, 'yr':yr, 'post_error':post_error, ,)

Under the year we want to show how many posts there are ineach month of that year. This is easy for most years. Thechallange is the current year, because we don't just want toshow results for months that are in the future.

So, if the year is the current year, we find out the month, thenuse that as the value to iterate through the rest of the months. Otherwise we just do 12 months ­ nice and easy.

The 'yr' value is just thrown in there so that we have it for thetemplates as well. That way we have a way to know which yearwe are talking about. You'll understand it better when we getthere.

Next up is the category page. As we did above, we have twoseparate views to write. We could easily combine them, but Iprefer to keep them separate for now.

So the first one is just the list of categories. Things are gettingeasy now.

def category(request): #http://site_name/category/ return render_to_response('base.html',

Page 39: Blog Engine Tutorial

12/23/11 Step 9: Write the View

10/10sandcurves.com/blog_engine/page/step-9-write-view/

Share |

'categories':Category.objects.all(),,)

The only new thing there was that we called a different class inour model, Category. Otherwise, it is just to easy.

So, the next thing is to give posts by individual categories.

def one_category(request, category): #http://site_name/category/category_name/ posts = Post.objects.order_by('­published').filter(categories__name=category.lower()) return render_to_response('base.html','posts':posts, 'category':category, ,)

This one is again really simple, but introduces something new. Do you notice the 'categories__name'. This is because thecategories value in our models.py file is in the Category class. The double underscore says "Get me the name of thecategory". In this case there is only one thing in the Categoryclass ­ name, but if there were more, you would still work with itthe same way.

We also pass a value straight from the function to the return ­the name of the category. We do this so that in our template wecan say something like "Under x category we got these posts".

Another thing I did here was to make sure that what I passed asa value was lower case. It is a good idea to enter all names andthings like that as lower case, and then you can just make themcapitalized or whatever you need in your site. But, just in casesomeone capitalized it in the url, we'll solve their problem andmake it lower case.

The last two, the tags, we will do basically exactly the same thingover again, only this time digging in the Tags class.

I'm going to assume that you can manage that on your own. Doing it on own also means that you need to read what I wroteabove and understand it.

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 40: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

1/11sandcurves.com/blog_engine/page/step-10-sub-templates/

Step 10: Sub­templatesWe have so far been adding 'base.html' to each of the returnvalues, but actually that page is a bit stupid and doesn't knowwhat to do with all we are throwing at it.

We are going to make nice little extensions to that.

In your terminal, go into the templates directory and create anew directory called 'blog'.

Now, once again I am going to do this the long way. We aregoing to create a small file for each of the url pieces that wecreated the view functions for.

Lets go in order. In order to make it easy to work with, namethem the same thing as your view functions. The only differenceis that you should put a .html ending to each one. Actually, youdon't even need to do that, but it is helpful to tell you what kind offile you are making.

The first one we will create is list.html.

Open up your list.html in your text editor. Just as a plug forEmacs, I find that the best way to write my Django apps is toactually open up the template, the view, and the urls.py (whichwe'll get to soon) all at the same time in split windows. Thismakes it so much easier to carry on the logic through.

Anyway, back to work:

% extends 'base.html' %

This simple first line is what we will use in each of our sub­templates. I guess it says exactly what it does.

Now, aside from that line, most other things have to be betweenblock tags to make it do anything of value.

% extends 'base.html' %

% block title %

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 41: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

2/11sandcurves.com/blog_engine/page/step-10-sub-templates/

% endblock %

% block content %

% endblock content %

If you remember on our 'base.html' file we put in some tags forblocks. We had a title block, a under_title block and a contentblock. Simple enough ­ you create the block tags in your basetemplate and then you can write other templates that slot intothose blocks.

If you wanted to get really fancy, you can next them, so that youhave sub­sub­templates filling blocks in your sub­templates. You get the picture.

When you look at the example, you'll see that I wrote theendblocks differently. For the title I just wrote % endblock %but for the content I added the 'content' to the end of it. That'content' is only there for your benefit ­ once your templates getlong and have lots of content, you will start to find it difficult toremember what starts and ends where. There are alsocomments with the templates % comment % (there is more onthat in the Django documentation).

I'm not going to fill in the 'under_title' section ­ I'll leave that up toyour creativity. It is just there so that you can have a sub­heading for the page, under the blogs name, to give someindication of what the page is about. By the time you have therest of this stuff down, that is going to be really easy.

Okay, let's just do it all in one shot ­ it is rather easy once youget the hang of it.

% extends 'base.html' %

% block title %% if previous %Archive previous % else %Zing Blog% endif %% endblock %

% block content %% for post in posts %<a href="/ post.published.year /post.published.month / post.slug /" title="post.title "> post.title </a>

post.description|safe <hr>% endfor %

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

BlogsVisit the expert community fordata management andbusiness analytics.www.AllAnalytics.com

Django Cloud HostingProduction hosting with push­button deploymentgondor.io

Page 42: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

3/11sandcurves.com/blog_engine/page/step-10-sub-templates/

% if previous % <a href="/archive/ previous/">&laquo; Previous</a>% endif %% if next and previous %&nbsp;|&nbsp;% endif %% if next %<a href="/archive/ next /">Next</a>% endif %% endblock content %

Scared? Don't be. If you understand some programming logic,this is just a way to add some logic into our templates.

Lets start at the bottom and work our way up. If you can seeboth the views.py file and the list.html file at the same time, youare going to understand so much faster.

If you look at the last section, look for the line where it says % ifprevious % and lets start from there. I am not going to give youa full lecture on Django template tags, but just the ones we areusing. There is pleanty of documentation that can help you out.

But, rather simply put, the logic is usually in tags with atpersentage sign "%" inside the "". You'll see we use ifstatements:

% if something_or_other %

and for statements:

% for i in some_iterable %

With the if statements we can use an "else" as well. With eachof them, as we did with block, we have to close them:

% if previous % Do this % endif %

Now, in the list.html file, where we are dealing with the lastsection came from the previous and next values passed from theviews file. If you have a look again at the views.py file, in thefunction "list" you'll see the return value had "next":next and"previous":previous.

It is these variables that we are testing for now. We don't needto say 'if previous is not Null', just like in Python, simply saying ifand the variable is enough.

So, if there is a previous page, then we will display the link to theprevious page and if there is a next page, we'll display a link toit.

Just for kicks, between the 'previous' and 'next' I put another ifstatement. This one checks if there are both previous and nextpages, we'll separate the two hyperlinks with spaces and a pipe

Page 43: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

4/11sandcurves.com/blog_engine/page/step-10-sub-templates/

symbol "|".

Okay, that was rather a lot of work to do simple stuff, but it is sortof standard navigation in a blog.

Lets skip the other stuff in the 'content' block first and go up tothe 'title' block. We tested again (using an if statement) for'previous'. Why? Well, we know that if the value of 'previous' isNull, we are on the home page. So we use this to fill the HTMLtitle tags. When we are on the home page, it will say "Zing Blog"in our tab title, but when we go to the first archive page, it will be"Archive 1".

Are you getting the hang of this? Okay, lets tackle the main blogpost bit.

Ah, a 'for' loop. How nice.

We passed the 'posts' value to the template. It is iterable in thetemplate and we can search for each specific blog post. So'post for posts' means that on each loop the 'post' variable getsanother 'posts' object, from which we can get the title, body,published and so on.

If you don't know what I am talking about, remember themodels.py file and look what we did in the views.py file to passthe value to the templates. And then, don't worry, just followalong.

Next we need to create a url.

% for post in posts %<a href="/ post.published.year /post.published.month / post.slug /" title="post.title "> post.title </a>

What a mess. I know, we'll fix it, but make sure you understandwhat it is doing.

To pass a variable to the template, we use the double curlybraces "". Now you can start seeing some of the power of thetemplates. We are digging right into the 'post' object, to get atits guts. 'post.published' would give us the entire value for whenit was published, and we could use that if we wanted to, but weneed a year and a month for the url.

Well, all we have to do is ask and Django giveth. 'post.published.year' gives us the string 2010 if you publishedthis year (at the time of writing).

The 'post.slug' gives us the slug, the bit Django so kindly did forus using the title we created in the admin.

Okay, if you know a bit of HTML then you understand what wedid with the rest of it. We created this fat, wacking greathyperlink for the static page of that blog post.

Page 44: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

5/11sandcurves.com/blog_engine/page/step-10-sub-templates/

We also gave them 'post.description' to give readers a taste ofwhat the whole blog post was about. It is up to you to write it likethat when you create the blog post.

Usually I write my first two paragraphs of the post in thedescription part, and then I just carry on and write the rest of it inthe 'body' section. That way you don't need to do anyprogramming gymnastics to give a snippet of your post ­ you justdo it by hand.

Now, if you look at that 'post.description' again, there is a pipesymbol and the word 'safe'. That allows you to write HTML inyour blog post. If you are like me you like to add your <p>symbols and &nbsp; spaces after each sentence?&bnsp; I writeHTML so much, I have to stop myself when I am writing normalemails. Don't believe me, have a look at the source (right click,'view source') for this file.

Because of that, I don't put the post description in <p> tags. ButDjango would just parse those symbols if we didn't put in safe ­ itis a safety net, so that others can't mess with your site by addingHTML and Javascript in forms, for example.

So 'safe' at the end of a variable allows that variable to containHTML. Even if you think you don't write HTML, think about howyou are going to put images into your blog posts, or if you justwant to make a word red or bold.

Okay, lets get back to that horrid url. We can fix that.

Go into the 'blog' directory again and open your 'models.py' file. Add the lines in red below.

from django.db import modelsfrom datetime import datetime

class Category(models.Model): name = models.CharField(max_length=60) def __unicode__(self): return self.name

class Tags(models.Model): name = models.CharField(max_length=60) def __unicode__(self): return self.name

class Post(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=120,unique=True) description = models.TextField() body = models.TextField() published =models.DateTimeField(default=datetime.now) categories = models.ForeignKey(Category) tags = models.ManyToManyField(Tags) def __unicode__(self): return self.title class Meta:

Page 45: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

6/11sandcurves.com/blog_engine/page/step-10-sub-templates/

ordering = ['­published'] def get_absolute_url(self): return "/%s/%s/%s" % (self.published.year,self.published.month, self.slug)

You should know enough Python to know how to pass valuesinto a string. It should be rather clear what we are doing herewithout me explaining it to much, we made the url, complete withyear, month and the slug.

Now close that file and go back to the 'list.html' template. Change that horrid url to a much simpler one, as shown below:

% for post in posts %<a href=" post.get_absolute_url " title="post.title "> post.title </a>

Sweet!

Okay, don't forget the block that we didn't add, the 'under_title'block.

The last thing I want you to do now is to go back to your'views.py' file and change the file to which therender_to_response is pointing. Look under the function list,and go down to the return value. Where it says 'base.html'change it to 'blog/list.html' because the list.html file is in the 'blog'directory of the templates. Got that?

Moving on, after list, what is the next template that we are goingto concern ourselves with? 'detail.html' Right. So go back intoyour template/blog directory where you created the list.html andmake a new one called 'detail.html'. This is what we are going touse to show our main blog post.

We can start out just the same as we did with 'list.html' in that weare going to extend the same template ('base.html') and we aregoing to fill the same blocks ('title' and 'content' here, and again,I'll leave 'under_title' to you).

As we get into this, they get easier and easier, so lets just jumpright in and write the whole thing out.

% extends 'base.html' %

% block title %% post.title %% endblock %

% block content %

<h3> post.title </h3><p>Posted on post.published|date:"F j, Y" <p>

post.description|safe <br> post.body|safe

Page 46: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

7/11sandcurves.com/blog_engine/page/step-10-sub-templates/

<br>

% if previous_post %<a href=" previous_post.get_absolute_url "title=" previous_post.title ">&laquo;&nbsp;Previous Post:&nbsp;&nbsp;previous_post.title </a>

% if previous_post and next_post%&nbsp;|&nbsp;% endif %

% if next_post %<a href=" next_post.get_absolute_url " title="next_post.get_absolute_url ">Next Post:&nbsp;&nbsp; next_post.title&nbsp;&raquo;</a>% endif %

% endblock content %

If you had followed along on the previous example (when we did'list.html') then this one should be a piece of cake. The use ofthe date was new. Again, that isn't something that I willelaborate on, this is one example of how you can use the datetemplate output that Django gives you. There are lots of otheroptions, just search through the documentation. As a startingpoint, look at the now in Django builtins.

You can see that I didn't make much fuss with the'post.description' and 'post.body' because, as I said earlier, if Iam writing posts, I want the freedom to add my own HTML. Also, the styling for these will be taken care of by the page CSS,but think of description and body as being one on this page. You could put them in a <div> tag if you wanted to, and use aclass to style better. That is all up to you. Moving along…

Next we'll do month.

% extends 'base.html' %

% block title %Posts in date|date:"M, Y"%endblock %

% block content %

% if posts %<ul>% for post in posts %<li><a href=" post.get_absolute_url " title="post.title "> post.title </a></li>% endfor %<ul>

Page 47: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

8/11sandcurves.com/blog_engine/page/step-10-sub-templates/

% else %<p>There are no posts in date|date:"F o\f Y" </p>% endif %

% endblock content %

Okay, we used the date to derive the title tag, making it uniquefor each month. And, at the end we gave an error message ifthe month didn't have any posts.

In that second one, take note of the 'o\f'. What is that all about? Well, simple, we had to escape the 'f' in order for it not to give usa month output. So, in our HTML it will output July of 2010. Justthrew that in for fun, but you can see, once you pass somevalues into the template from the views, you almost need to holdyourself back from being to creative.

Okay, month was easy, lets do year…

% extends 'base.html' %

% block title %Posts in by_month.1|date:"Y"% endblock %

% block content %

% if post_error % post_error % else %

% if by_month %% for i in by_month %% for key, value in i.items % <b> key|date:"M"</b>% if value %<ul>% for x in value %<li><a href=" x.get_absolute_url " title=" x.title "> x.title </a></li>% endfor %</ul>

% else %­ There were no posts in key|date:"F" % endif %

<br>

% endfor %

% endif %% endif %

% endif %

Page 48: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

9/11sandcurves.com/blog_engine/page/step-10-sub-templates/

% endblock content %

I didn't link to each month in here, but I am sure that you'll findthat simple to do if you wanted to. Don't waste to much time onmaking this page really nice, you probably aren't going to have alink to these year pages, they are just there so that when visitorsstart chopping your url at logical points, they have some logic. For that reason, it makes sense to just point people straight tothe posts. That's what I think, of course, you build your blogyour way.

I am sure that the 'year.html' was easy to follow. Lets do the twocategory ones, and then I'll leave the tag ones to you again.

'category.html'…

% extends 'base.html' %

% block title %Categories% endblock %

% block content %

% if categories %<ul>% for category in categories %

<li><a href="/category/ category.name.lower /"title=" category.name.capitalize "> category.name.capitalize </a></li>

% endblock content %

In 'category.html' we simply just give a list of categories. I like tobe sure about lower case and upper case, and this is a goodtime to use that, since I always add the categories as lower case(makes better urls), but capitalize them when displaying them. Django does the Python like capitalize, lower, and upper thingsfor us in templates. Nice…

Note that though easy, we did make a bit more effort with thisone, we provided links to the single categories (for who we'llwrite templates next). Categories is something people will lookup and you may provide links to, so they are worth working on.

Next up, 'one_category.html'…

% extends 'base.html' %

% block title %Category ­ category.capitalize % endblock %

% block content %

<h3>Posts under the Category <span

Page 49: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

10/11sandcurves.com/blog_engine/page/step-10-sub-templates/

style="color:red;"> category.capitalize </span></h3>

% if posts %<ul>% for post in posts %<li><a href=" post.get_absolute_url " title="post.title "> post.title </a></li>% endfor %</ul>

% endblock content %

And there you have it. There is so much else that you can addto the templates, and we aren't done yet totally, but for now, letsmove on. If you have been diligently following this tutorial tohere, you are dying to see it all working. We are almost there.

Don't forget that for each template you write, you need to goback to the view, and change the template (from 'base.html' to'blog/whatever.html') to which it points to the one you havewritten. Okay, there are two exceptions, lets deal quickly withthese two pages.

The first is your 404 page. If you are writing websites, I am sureyou know what a 404 is, but just in case you don't, a 404 is aHTTP 'page not found' error response. This means the userfound your server (in the request) but the actual page didn'texist. A page like thishttp://sandcurves.com/how_to_milk_a_cow/ is an example ­ wedon't have an HTML file like that (okay, if you do, you are anexception ­ strange person). No, jokes aside, what are we goingto do when someone asks a page we don't have ­ we'll politelytell them that we don't have that page.

In your main template directory, create a new file called, youguessed, 404.html. Now, I am going to be really boring hereand tell you that we are simply going to copy, verbatim (it'sunder gnu free document license) , what is in the Django Booksite for a 404 page.

% extends "base.html" %

% block title %Page not found% endblock %

% block content %<h1>Page not found</h1>

<p>Sorry, but the requested page could not befound.</p>% endblock %

Page 50: Blog Engine Tutorial

12/23/11 Step 10: Sub-templates

11/11sandcurves.com/blog_engine/page/step-10-sub-templates/

Share |

…and, you guessed, a 500 page. The 500 page shouldn't relyon Django working properly, it is an error message reporting thatthere is a server error. So write this one in pure HTML. To savetime here, I will again just copy the 500 page from the DjangoBook site (except I'll change the doctype to a more HTML5 likeversion, where you can do what you like.)

<!DOCTYPE html><html lang="en"><head><title>Page unavailable</title></head><body>

<h1>Page unavailable</h1>

<p>Sorry, but the requested page is unavailabledue to a server hiccup.</p><p>Our engineers (Me, Myself, and I) have beennotified, so check back later.</p>

</body></html>

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 51: Blog Engine Tutorial

12/23/11 Step 11: Write the Urlconf

1/3sandcurves.com/blog_engine/page/step-11-write-urlconf/

Step 11: Write the UrlconfOkay, close all those files with templates and all that. We arenow going to write our urls. Now, if you have followed alongdiligently, you have already 'written' the urls in the views as acomment starting each view. We now have to got the the urls.pyfile and map them to those views.

Open your urls.py file in the main 'zing' directory. Add the line inred.

from django.conf.urls.defaults import *from django.contrib import adminadmin.autodiscover()

urlpatterns = patterns('', (r'^admin/',include(admin.site.urls)), (r'^', include('zing.blog.urls')),)

Actually, all we have done now is tell the urls.py file that anythingthat doesn't map to the admin site, we'll deal with under'blog.site.urls'.

Well, in order to do that, we need to write that python file. Onething always to remember is that it is all just Python, and so youcan get creative. You can change file names, use differentdirectories, whatever you want, so long as you import the rightthing when you need it.

As a rule of thumb, I would say, stick to Django's conventionsunless it is actually more clear not to. Most of the time, if youstart to change things around, you are going to confuseyourself.

In this case we aren't doing something radical, we are justwriting some of our views in the 'blog' directory.

Okay, go into your 'blog' directory, where you have the views.py,models.py and admin.py files and create a new one called'urls.py'.

from django.conf.urls.defaults import *

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 52: Blog Engine Tutorial

12/23/11 Step 11: Write the Urlconf

2/3sandcurves.com/blog_engine/page/step-11-write-urlconf/

Share |

urlpatterns = patterns('', (r'^$', list), (r'^archive/(?P\d1,2/$', list), (r'^\d4/d1,2/(?P.*)/$', detail), (r'^(?P\d4)/(?P\d1,2)/$', month), (r'^(?P\d4)/$', year), (r'^category/$', category), (r'^category/(?P.*)/$', one_category), (r'^tag/$', tag), (r'^tag/(?P.*)/$', one_tag), )

Depending on your familiarity with Python, this shouldn't be tohard at this point to figure out. The regular expression (which Iwill not cover here, but if you don't know what it is, do look it up ­it is fun) maps to a specific url.

Simply put, when someone requests a specific url, that url ischecked in this file and when a match is found, it is sent to theview, from were the page is rendered by passing values to thetemplates.

We know which view to use because we specify it at the end ofeach of the tuples within the patterns tuple. So, if you ask forthe home page, it is going to match the first one (because thereis nothing beyond the domain name, which is truncated for theurls. So, it will use the 'list' function in the views.py file, which, inour case, will use the 'list.html' template to extend the 'base.html'template.

Now, if all has gone well, you have a complete, working website.

If you open your terminal, and type runserver, you should beable to try out each url.

vernon@slick:~/project/zing$ python manage.pyrunserver

If you are having problems, look carefully at the error messagesthat Django is giving you. Note, you are not going to be gettingyour 404 and 500 pages that you wrote yet, we'll get to thatwhen we start deploying the site on a server. For now, Django'serror messages are much more useful, they are going to tell youwhat you did wrong (or do their best to try.) Ask me questions,and I'll help where I can, but also dig into Django'sdocumentation a little.

Resist the urge, I think, to get to creative at this point. The toughpart is getting everything to work well with a proper web­server,which we'll get to in a bit.

« Previous Page | Return To Contents Page | Next Page »

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

BlogsVisit the expert community fordata management andbusiness analytics.www.AllAnalytics.com

Django Scalable PlatformEasy deployment for Djangoapps. Python2.6 and gitintegration.www.nuagehq.com

Page 53: Blog Engine Tutorial

12/23/11 Step 11: Write the Urlconf

3/3sandcurves.com/blog_engine/page/step-11-write-urlconf/

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 54: Blog Engine Tutorial

12/23/11 Step 12: Add comments

1/2sandcurves.com/blog_engine/page/step-12-add-comments/

Share |

Step 12: Add commentsNow, Django comes with a rather fun way to work withcomments, but I am going to simply cop out at this point. Youcan learn it if you like: Django's Comment Framework

I would recommend, rather, that you go with a third party app inthis case. It is going to save you a lot of time, and will makecreating feeds and social media gizmos so much easier, andgive you time to actually write blog posts ­ or build another sitewith Django.

If you are considering third party apps, the main ones people inthe Django community seem to use are IntenseDebate andDisqus.

I really couldn't say which is better. I am using IntenseDebate,and have enjoyed it so far.

They are really easy to use, and you can simply go to theirwebsite, and follow the instructions. The code, at least forIntenseDebate is linked to your url, which means you have littlecontrol over it, but they do provide access to it's objects andsome nice CSS stuff. So far, all I have done is stick it in and letit do it's thing. If you want to do the same, the template youneed to put it on is the 'detail.html' page. Simply slot the stuffthey give you into the area below the 'post.body|safe' bit, andyou are all set.

If you want some help with Django's actual comments, well, youare welcome to ask me. It isn't that hard to set up, but it is a littleextra work.

« Previous Page | Return To Contents Page | Next Page »

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 55: Blog Engine Tutorial

12/23/11 Step 12: Add comments

2/2sandcurves.com/blog_engine/page/step-12-add-comments/

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Get New Customers OnlineAdvertise On Google. Get1500 INR Advertising CreditWhen You Sign­Upwww.Google.com/AdWords

VenzZend PackageWeb development startup kit.Save thousands indevelopment cost.www.venzon­solution.com/

Page 56: Blog Engine Tutorial

12/23/11 Step 13: Add Rss

1/2sandcurves.com/blog_engine/page/step-13-add-rss/

Step 13: Add RssOkay, I coped out on Comments, and trust me, I did that forgood reason. But I am not leaving you alone with everything. Lets get some RSS feeds done. Later when you have RSS youcan hock it up to something like feedburner, so that you havenice stats and access to all sorts of ways to promote your site. But to do that, we first need some plain old RSS.

You could write the RSS yourself, knowing what you alreadyknow about Python and Django, as well as a little bit of xmlformatting. I'm sure, if you are writing a blog, you are aware ofRSS and a little of how it works. If you don't, you also will notlearn to much here. Open up your main urls.py file (the one inthe zing directory). Add the lines in red…

from django.conf.urls.defaults import *from zing.blog.feed import ZingFeedfrom django.contrib import adminadmin.autodiscover()

urlpatterns = patterns('', (r'^admin/',include(admin.site.urls)), (r'^', include('zing.blog.urls')), (r'^feed/$', ZingFeed()),)

If you were observant, you would see that we imported a file thatdoesn't exist, 'zing.blog.feed'. So, lets make that there file.

Go into your blog directory, and open up a new file in your texteditor called 'feed.py', and add all of the following.

from django.contrib.syndication.views import Feedfrom zing.blog.models import Post

class ZingFeed(Feed): title = "My Zing Site Feed" link = "/" description = "Zing site, powered by Vernon'sDjango Recipe" def items(self):

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 57: Blog Engine Tutorial

12/23/11 Step 13: Add Rss

2/2sandcurves.com/blog_engine/page/step-13-add-rss/

Share |

return Post.objects.order_by("­published")[:5] def item_title(self, item): return item.title def item_description(self, item): return item.description def item_link(self, item): return item.get_absolute_url()

And that is all there is to that. Open up your site in yourbrowser, and go to whatever it is, 127.0.0.1:8000/feed/, and youshould be all set. Only thing is, all the beautiful RSS that youhave written is just for you, since your site isn't live on theinternet yet.

So, the next step, then, is to change that.

« Previous Page | Return To Contents Page | Next Page »

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Download Google ChromeSearching is fast and easy withGoogle's web browser.www.Google.com/Chrome

Barnes JohnVisit the expert community fordata management andbusiness analytics.www.AllAnalytics.com

Page 58: Blog Engine Tutorial

12/23/11 Step 14: Upload to a server

1/7sandcurves.com/blog_engine/page/step-14-upload-server/

Step 14: Upload to a serverThis is the hardest step, I guess, because there are so manydifferent servers, and they have different setups. I am going togive very specific advice for what it took for me to get mywebsites running on servers run by Hostgator.

Like I said before, this is no plug for them, it is simply because Irun some of my websites with them, and had to go through arather large learning curve to get it done.

I also have to admit, I am kind of stupid about this stuff. I don'tunderstand the ins and outs of Apache very well at all. I haveread some of the documentation, but there is a lot ofdocumentation and I don't hosts sites, I only want to be able getit on there, not get hacked and serve my site. I would rather bebuilding new apps and adding content to my websites thanwaste time becoming an Apache guru. So, follow this bit if youlike, but you may well be better off asking someone else.

I'll add here, if you are the mother of all Apache gurus, and youwant to re­write this section for me, well, you would rock…

There are two web pages that basically spell out most of what Iam going to say here, and you can rather work with them if youlike.

support.hostgator.com/articles/django­with­fastcgidjangobook.com/en/2.0/chapter12/

Okay, lets do some preparation before we actually changeanything on the server. I'll me spell this stuff out in point form:

First up, before we start to get our site ready, make sure,with your Hostgator site, that you have the right packageto be able to run a website with Django and fastcgi. Okay, now ask your contact person for FLUP, fastcgi, andMySQLdb. You will also need to have SSH, which you may have topay extra for. If you don't already, you will need to know your usernameand password for the website. Under your project directory, where we currently havenothing but the main 'zing' directory, create an new

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 59: Blog Engine Tutorial

12/23/11 Step 14: Upload to a server

2/7sandcurves.com/blog_engine/page/step-14-upload-server/

directory and call it 'guts'. If you don't like that name, callit 'public_html' or anything else, but we are going to usethis for the none Django stuff. Under that directory, open a terminal and type thefollowing:

vernon@slick:~/project/guts$ ftpyour_domain_name

Where 'your_domain_name' is, of course, your domainname. In my case, I would be typing sandcurves.com. Note the lack of 'http://' in front of it. Just the name andthe dot_whatever (.com). You may have some fancy­dandy ftp program ­ suityourself. I will stick with basic terminal ftping, just becauseit'll help us stay on the same page. Okay, do like so:

Connected to sandcurves.com. 220­­­­­­­­­­Welcome to Pure­FTPd [privsep] [TLS] ­­­­­­­­­­220­You are user number 1 of 50 allowed.220­Local time is now 05:08. Server port:21.220 You will be disconnected after 15minutes of inactivity.Name (your_domain.something:your_name):your_username

and then…

331 User your_username OK. PasswordrequiredPassword: your_password

Okay, like I said, I am assuming that your set­up is just likemine, and so we are going to download some files fromthe location I have them. If you don't find these fileswhere I am telling you, ask your contacts to help. For themost part, this kind of set­up is fairy standard for Apacheshared host environments. You'll have your nice little 'ftp>" prompt, and so now dothis:

ftp> get .bashrclocal: .bashrc remote: .bashrc200 PORT command successful150 Connecting to port 56619226­File successfully transferred226 0.012 seconds (measured here), 17.79Kbytes per second214 bytes received in 0.01 secs (14.6 kB/s)

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Want To Design AWebsite?Design Your Website By TheBest Web Design Company InIndia. See More

Don 2 3D TrailerNow Playing Don 2 Trailers in3D. Catch It All on YouTube!youtube.com/Don2

Page 60: Blog Engine Tutorial

12/23/11 Step 14: Upload to a server

3/7sandcurves.com/blog_engine/page/step-14-upload-server/

ftp>

Okay, that file isn't so important, but the next one is. Wewill need to change directories on the server, and thenfetch the file. Changing directories on the other site is justthe same as doing it on your own machine. If you neededto change directories on your own site, while using ftp, use'lcd' instead. FTP is very easy to work with, and if youwant to be a web guru, you should know your FTP basicsvery well.

ftp> cd public_html250 OK. Current directory is /public_htmlftp> get .htaccesslocal: .htaccess remote: .htaccess200 PORT command successfuland so on …

ftp> bye221­Goodbye. You uploaded 0 anddownloaded 2 kbytes.221 Logout.vernon@slick:~/project/guts$

You can always log out of ftp using the term 'bye' or'exit'.&nbps;Okay, I'm going to show you basically what I have in there:

# ­FrontPage­AddHandler fcgid­script .fcgiOptions +FollowSymLinksRewriteEngine OnRewriteBase /

IndexIgnore .htaccess */.??* *~ *#*/HEADER* */README* */_vti*

order deny,allowdeny from allallow from all

order deny,allowdeny from all

AuthName domain_name.comAuthUserFile/home/user_name/public_html/_vti_pvt/service.pwdAuthGroupFile/home/user_name/public_html/_vti_pvt/service.grpAddType text/x­python .py

Page 61: Blog Engine Tutorial

12/23/11 Step 14: Upload to a server

4/7sandcurves.com/blog_engine/page/step-14-upload-server/

RewriteRule ^media/(.*)$ ­ [L]RewriteRule ^admin­media/(.*)$ ­ [L]RewriteCond %REQUEST_URI !(zing.fcgi)RewriteRule ^(.*)$ zing.fcgi/$1 [QSA,L]

What is going to be important is those first few lines (Ithink lines 2 to 5) and then all the stuff in the last few lines(the whole last block, where the lines start with'RewriteRule'). The stuff in between is probably similar to what you havealready in that file. So just change your first and last bitsto be exactly like mine ­ where the reference to 'zing.fcgi'can stay 'zing' or be changed to whatever you like. The next step, then, is to create that fcgi file, so open up afile in the 'guts' directory called 'zing.fcgi' (of course,changing the name to whatever you called it in your.htaccess file. Okay, this next bit assumes that your python path is thesame as mine. You can check on that. At the moment Istill have python2.4 on the server ­ you may need to checkthat (you can ask, or ssh and run a python shell, which willshow you the version).

#!/usr/local/bin/pythonimport os, sys

sys.path.insert(0, "/usr/lib/python2.4")sys.path.insert(0, "/home/domain_name/dj")sys.path.insert(0,"/home/domain_name/dj/django")sys.path.insert(0,"/home/domain_name/dj/project")sys.path.insert(0,"/home/domain_name/dj/project/zing")

# Set the DJANGO_SETTINGS_MODULEenvironment variable.os.environ['DJANGO_SETTINGS_MODULE']= "zing.settings"

from django.core.servers.fastcgi importrunfastcgirunfastcgi(method='threaded',daemonize='false')

Next, copy your settings.py file from the 'zing' directory tothe 'guts' directory. When we run the site on the hostserver, for the most part the only thing we want to havedifferent is the settings.py file. So we are going to keepthe one in the 'zing' directory as it is, and make theneeded changes to the other one for what we need on oursite. There is one other file we are going to keep a differentversion of on our home site to our server's site, thebase.html. So copy it form the 'template' directory to the'guts' directory. The reason is that we want to separate CSS from the

Page 62: Blog Engine Tutorial

12/23/11 Step 14: Upload to a server

5/7sandcurves.com/blog_engine/page/step-14-upload-server/

HTML. Look for this line we wrote oh so long ago:

<link rel="stylesheet" type="text/css"href="/media/css/style.css">

Copy all the content between the open <style> tag and theclosing </style> tag. Now, paste that into a file called'style.css'

/* Zing Stylesheet */

/* Page */bodypadding:0;margin:0;font­family:Arial,Helvetica, Tahoma, sans­serif;/* Title section */#titlefloat:left;width:100%;padding:0;margin:0;border:0;border­bottom:1px solid #cccccc;#title h1padding:10px 0 0 50px;font­size:60pt;margin:0;font­family:"Myriad Pro",Arial, Helvetica, Tahoma, sans­serif;#title h2margin:0;padding:0;text­align:center;/* Content section */#contentfloat:left;border:0;margin:0;padding:10px2% 0 2%;width:75%;/* Sidebar section */#sidebarfloat:left;border:0;border­left:1pxsolid #cccccc;padding;10px 2% 02%;width:20%;margin:0;/* Footer section */#footerfloat:left;border:0;border­top:1pxsolid#cccccc;padding:0;margin:0;width:100%;text­align:center;

For the most part, I have tried to leave out as muchunnecessary stuff as possible, but one thing that makessuch a difference is having aliases when you are workingwith ssh. Under bash (the terminal thingi) we can haveone word that we define to mean some script to run. Inour case, all we are going to do is set some 'cd'commands, so that we can quickly get to the directoriesused most. Open the '.bashrc' file (remember that with both this fileand the .htaccess file, they are hidden files under linux. Ifyou have a problem seeing them, just run 'ls ­a' in ourterminal to see the hidden files listed and 'emacs .bashrc'to open it up with emacs. At the bottom of the file, just append these lines, and thenclose and save it. You'll have to change 'user_name' foryour set­up.

# User specific aliases and functionsalias zing='cd/home/user_name/dj/project/zing'

Page 63: Blog Engine Tutorial

12/23/11 Step 14: Upload to a server

6/7sandcurves.com/blog_engine/page/step-14-upload-server/

alias stylo='cd /home/user_name/media/css'

So far we haven't broken anything on our webserver yet. Takea deep breath, play Sodoku, go get coffee, clear your head. Weare about to start tinkering with the insides, the guts, of your hostserver.

Ssh is a fantastic tool where you have command line access toremote computers through a secure tunnel. Unlike FTP, wherewe were just bringing and taking, with SSH we are actually goingto go onto our host server's computer and tinker.

With SSH access to the server computer you can only do alimited amount of thing, so I don't think you need to worry aboutbreaking their computer (I hope), but you can totally destroyyour own website ­ actually, when we start our, that is exactlywhat we are going to do anyway. But, hopefully, we'll also begetting it to work very soon.

The first time you try to connect it is going to ask you if you wantto continue, because it doesn't know the site. Answer 'yes' ofcourse. To get into your webserver with ssh, do the following:

vernon@slick:~/project/guts$ ssh ­p 2222username@domain_name.com

And to exit, simply type exit:

whatever@whatever:~$ exit

Remember each time to exit, same as FTP.

Okay, now, lets get things going. ssh into your server again (itdoesn't matter from which directory you are in your homecomputer right now).

You are at your root directory when you log in. The first thingyou want to do is see if python is working. At the terminal, type'python' and hit enter. It should enter the familiar Python shell.

Next is to see if Django is installed. While still in Python, type"import django" If nothing happens, and python just moves on toan empty python prompt ('>>>') then django is there and youdon't have to worry.

Hit 'Ctrl­d' to get out of python, and make a new directory ('mkdirdj') called 'dj'. cd into it. If you didn't have Django, you can get itwith svn. See this page to help install the development version.

Okay, if that has all gone well, lets make our project directory'mkdir project' and cd into it.

Create your new django project here, with 'django­admin.pystartproject zing'. This is the second time around, so this shouldbe familiar ground.

Page 64: Blog Engine Tutorial

12/23/11 Step 14: Upload to a server

7/7sandcurves.com/blog_engine/page/step-14-upload-server/

Share |

Again, repeating ourselves, make the directory 'mkdir template'for the templates. Then make the 'blog' sub­directory, 'mkdirtemplate/blog'

And our blog application, 'python manage.py startapp blog'.

Type cd to get back to your root directory, and create a newone, 'media'. Then make a sub­directory, 'mkdir media/css' Andthen exit.

« Previous Page | Return To Contents Page | Next Page »

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Page 65: Blog Engine Tutorial

12/23/11 Step 15: Upload Our Site

1/2sandcurves.com/blog_engine/page/step-15-upload-our-site/

Step 15: Upload Our SiteNow, we are going to do a simple bit of ftp. Start in the 'guts'directory. ftp into your site, and, using the keyword 'put' put the.bashrc file up.

cd into 'public_html' and put .htaccess and zing.fcgi into thatdirectory.

From 'public_html' directory, type 'cd ../media/css' to get into ourcss directory and 'put style.css'

The last file in guts we need to worry about for now is the'base.html' file. If you are still in the 'css' directory on yourserver, type 'cd ../../dj/project/zing/template/' to get to thetemplate directory, and put the base.html file there.

Wait first with the settings, we first have some database stuff totake care of.

Now, we want to put the stuff up in our main django project, so,from 'guts' we need to type 'lcd ../zing' to get to zing. We needto be in the same directory on the server, so 'cd ../' (out of'template') to get there. The only thing we need to bother withhere is the 'urls.py' file, so 'put urls.py'.

One thing to note here is that we are not going to use the'zing.db' for the database, it will be a MySQL, and well get to thatsoon.

cd into the 'blog' directory (and lcd the same to get there on yourhome computer). Here you can let rip, and rather than ftp onething at a time, type 'mftp *.py'. Specify the file ending so that itdoesn't put up the pyc files and things like that. It will ask you ifyou want to put up the file, and to say yes you can just hit enter. If there was a file you didn't want to put up (for example, wedon't need to put up the __init__.py file) then just an 'n' andenter will suffice. The '*' is a wildcard, of course ­ 'do it all'.

Now 'cd ../template/blog' and 'lcd ../template/blog' and 'mftp*.html'

Exit ssh.

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 66: Blog Engine Tutorial

12/23/11 Step 15: Upload Our Site

2/2sandcurves.com/blog_engine/page/step-15-upload-our-site/

Share |

« Previous Page | Return To Contents Page | Next Page »

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

PetarackOne petabyte in a single rackunder one Namespace orVolume.aberdeeninc.com/abcatg/petarack.htm

store Your files OnlineGet online data storage anddata backup.www.storage.sifyservices.com

Page 67: Blog Engine Tutorial

12/23/11 Step 16: Set up new Database

1/2sandcurves.com/blog_engine/page/step-16-set-new-database/

Step 16: Set up new DatabaseFor the database, once again, I am going to assume that yoursetup is the same as mine. If it isn't, hopefully it is close enoughto give you a hint of what you need to do.

Okay, instead of doing all of this with ssh, lets just go to cpanel(this is, assuming you have cpanel) and going to the section'Databases', which seems to be a standard. Click on 'MySQL®Databases' It is so easy. Just go to where it says 'Create a newdatabase'. While you do so, note down the database name(which is usually the site username with an underscore and thenthe name you give, such as 'vernon_zingdb' or whatever),username, password and so on.

When you are done, log out of cpanel and go into your gutsdirectory and open the 'settings.py' file that is there.

Under the 'DATABASE = ' enter the following:

DATABASES = 'default': 'ENGINE': 'mysql', 'NAME': 'vernon_zingdb', # The name you ended up with for the database. 'USER': 'the_username_you_created_under_databases_in_cpanel', 'PASSWORD': 'your_password_for_the_database', 'HOST': '', # leave this one black 'PORT': '3306',

You should also set the 'DEBUG' to 'False', but, maybe just waita little bit, lets just get it working up on the server.

Also change these three lines here:

MEDIA_ROOT = 'http://domain_name.com/media'MEDIA_URL = '/media/'ADMIN_MEDIA_PREFIX = '/admin­media/'

ftp the settings.py file from guts to your 'zing' directory.

We are nearing the end now. Ssh into your site again, and

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 68: Blog Engine Tutorial

12/23/11 Step 16: Set up new Database

2/2sandcurves.com/blog_engine/page/step-16-set-new-database/

Share |

(remember what we typed in the .bashrc file) type 'zing' and youshould be whizzed into your 'zing' directory.

Type 'python manage.py validate'. If you get errors, you cancheck your settings.py file or get help from the hostgator helpcenter. Or tweet me, maybe I missed something obvious.

Of course, if it works, run 'python manage.py syncdb'. Ofcourse, you'll have to create a new superuser, like you didbefore on your home site. You may want to use the samepassword as you did on your own site.

Exit ssh, go to your 'http://your_domain.com/admin/ page, log inand see if it is all good. Write a few blog posts and see if theyshow up as you expected on the site. You'll probably want toadd to the CSS, and make it all look better.

If it all went well, you should have a working blog. Now writesomething cracking in there and send me a link to check it out.

« Previous Page | Return To Contents Page | Next Page »

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Data BackupBusiness intelligence expertssharing their secrets with you.Go!www.AllAnalytics.com

store Your files OnlineGet online data storage anddata backup.www.storage.sifyservices.com

Page 69: Blog Engine Tutorial

12/23/11 Step 17: Away You Go

1/2sandcurves.com/blog_engine/page/step-17-away-you-go/

Share |

Step 17: Away You GoNow, go play with it.

You can either work on file on your own system, or if you aremaking just quick tweaks, use nano in ssh to work directly onfiles in your system.

If you actually followed this tutorial all the way through, welldone, very few people make it through a massive tutorial likethis. I hope you learned a lot, but I am also sure you realizedthat there is so much more to Django, not to mention Pythonand Linux itself. Hopefully it is just the start for you, as it is forme.

For more on Gimp: gimpology and the gimp website.

« Previous Page | Return To Contents Page | Next Page »

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 70: Blog Engine Tutorial

12/23/11 Step 17: Away You Go

2/2sandcurves.com/blog_engine/page/step-17-away-you-go/

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Design Course in 12 mthsDo Graphics & Web Designpart­time along with your BABCom BSc degreewww.Arena­Multimedia.com

Audi A6 ­ Luxury SedanFlawless design & efficiency.Book a test drive online now!www.audi­alist.in/testdriveA6

Page 71: Blog Engine Tutorial

12/23/11 Pass on this tutorial

1/2sandcurves.com/blog_engine/page/pass-tutorial/

Share |

Pass on this tutorialDid you enjoy this tutorial? Do you think that others couldbenefit from it? Please feel free to pass it on to others.

You could host the whole tutorial on your own website if youlike. If you give me credit and link back to this site, you areawesome, but I don't require it. If you want some help, contactme and I'll see if I can help you get it up and running on yoursite. The main thing you need to concern yourself with isparsing the HTML so that it doesn't just become part of theHTML of your page.

Of course, you don't have to host it yourself, if you simply linkback to me that it fantastic.

<a href="http://sandcurves.com/blog_engine/" title="A plain and simple Django blog building tutorial">Sandcurves Django Tutorial</a>

« Previous Page | Return To Contents Page

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 72: Blog Engine Tutorial

12/23/11 Pass on this tutorial

2/2sandcurves.com/blog_engine/page/pass-tutorial/

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Get New Customers OnlineAdvertise On Google. Get1500 INR Advertising CreditWhen You Sign­Upwww.Google.com/AdWords

Don 2 3D TrailerNow Playing Don 2 Trailers in3D. Catch It All on YouTube!youtube.com/Don2

Page 73: Blog Engine Tutorial

12/23/11 Relevant Links | Django

1/2sandcurves.com/blog_engine/links/

Useful Links to Django Blog DevopmentA complete blog engine using django in 60 minutes ­This is a great tutorial, and follows the DRY principal verywell. I worked through this tutorial and learned a lot fromit.&nbps; 60 minutes? It takes a little longer, unless youreally know your stuff already.

Build a microblog with django ­ This is another usefultutorial. I didn't read through it, so I can't say how good itis.

A detailed django tutorial blog basics He is an expert,I am sure it is good. I didn't read this one either.

Django Tutorials ­ A list of Django tutorials.

The Django Tutorial ­ Go sit at the feet of the masters ofDjango, and become wise.

Django's Documentation ­ I am sure I didn't need to putthis link, if you don't dip in the docs, forget being a Djangoguru, ever.

Running Django on Google App Engine ­ Fan ofGoogle App Engine, here are the docs to help you getDjango and App engine working together.

Django Book ­ This was the main thing I used to learnDjango, and I find it really useful.

Did you write a good Django Tutorial? Send me a Tweet@sandcurves and I'll check it out and stick up a link.

Here are a few other related things you may find useful

EmacsThe Python Tutorial

Sandcurves

Home About Me Topics Contact Blogroll

About

Myname isVernonI live in

Namibia I'm a passionateblogger, computerenthusiast, naturalist andfather Sandcurves is mypersonal website and blogMore…

Blogging Project

Meaningful Blog Project Linux and open sourse

New Here? | Subscribe | About Me | Twitter | Contact

SandcurvesBlogging Nuts & Bolts | Vernon Swanepoel's Blog

Page 74: Blog Engine Tutorial

12/23/11 Relevant Links | Django

2/2sandcurves.com/blog_engine/links/

Dive Into Python [out of date, but super for learningPython]The Gimp Image Manipulation ProgramUbuntuApache Web Server

Return to the contents page of the Django Blog Engine Tutorial

Tutorials

Blog Engine Tutorial

Keep Up

Subscribe by Email

Subscribe by Feed

Write On Sandcurves

Guest Post on my blog

Work

I work at andBeyond as themanager of our Windhoekoffice. If you want to knowmore about Namibia andthe andbeyond operationsin Namibia, visit ourNamibia pages on thewebsite.

Ads

Copyright © 2010­2011 Vernon Swanepoel | Django powered | Written with Emacs on Debian |Hosted by Integrity Namibia | Subscribe

Don 2 3D TrailerNow Playing Don 2 Trailers in3D. Catch It All on YouTube!youtube.com/Don2

Samsung Microwave OvensDeep & Even Cooking withSamsung Microwave Ovens.Get Details now.www.Samsung.com/in