Python from Scratch – Create a Dynamic Website
videos

Python from Scratch – Create a Dynamic Website

Tutorial Details
  • Program: Python
  • Difficulty: Easy
  • Estimated Completion Time: 1 Hour
This entry is part 5 of 5 in the Python from Scratch Session
« Previous

We’ve covered quite a bit of Python in the previous tutorials in this Session. Today, we’re going to combine everything we’ve learned so far to build a dynamic website with Python.


Prefer a Video Tutorial?

So, how do you get started creating websites with Python? Well, you could do it all yourself, and write a program that runs on a web server, accepting page requests and serving up responses in the form of HTML and other resources. However, that’s a lot of work, so why go to all the trouble when there are plenty of existing tools out there to do the job for you? These tools are called frameworks, and they’re what we’ll use today to create our website.

Python Frameworks

There are quite a few Python web frameworks, but here are some of the best:

  • Django – We’re going to use this today. It has a huge set of features, but remains simple to use. The documentation is also excellent, so if you get stuck, you’ll have the easiest time solving your problem with Django.
  • Grok – Another framework with a feature set that comes close to Django. If you decide you don’t prefer Django, this is a good alternative.
  • WebPy – A much more lightweight framework. It doesn’t have as many features, though it did power Reddit for a period of time!
  • TurboGears – Though previously having a reputation for poor documentation, TurboGears has improved substantially in the last year.

A more comprehensive list can be found on the Python website if you’re in need of additional options. Today we’re going to set Django up for development on a local machine, and then build a simple blog. We’re also going to review the process of installing it on a remote web server.


Installing Django

We’ll be performing most of our work today in the Terminal. This should all work on Mac and Linux; however, if you’re running Windows, the process is somewhat different. A familiarity with the command line isn’t necessary if you’re only writing Python, though, if you’re planning on using Django, or running a dynamic website in general, it’s worth learning.

Terminal Tutorials

Consider reviewing these tutorials to get yourself up and running with the Terminal.

Here are the commands you need to install Django. It’s not compatible with Python 3, so you’ll need to install version 2.7 or earlier to get it running.

    wget http://www.djangoproject.com/download/1.3.1/tarball/
    tar xzvf Django-1.3.1.tar.gz
    cd Django-1.3.1
    python setup.py install

Next, we can optionally remove the install files.

    cd ..
    rm Django-1.3.1.tar.gz

That should do it! Let’s test it out.

    python
    from django import get_version
    get_version()

You should see ’1.3.1′. If you do, everything worked and Django is installed on your system. Congratulations! We’re ready to begin creating our site!


Building our Blog

We’re going to build a blog system today, because it’s an excellent way to learn the basics. First, we need to create a Django project.

cd ~/Documents/Projects
django-admin.py startproject FirstBlog
cd FirstBlog
ls

What do each of these files do?

  • __init__.py tells Python that this folder is a Python package. We learned about these in the third lesson; it allows Python to import all of the scripts in the folder as modules.
  • manage.py isn’t actually part of your website; it’s a utility script that you run from the command line. It contains an array of functions for managing your site.
  • settings.py contains your website’s settings. Django doesn’t use XML files for configuration; everything is Python. This file is simply a number of variables that define the setting for your site.
  • urls.py is the file that maps URLs to pages. For example, it could map yourwebsite.com/about to an About Us page.

Django refers to itself an MTV framework, which stands for Model Template View.

Apps

However none of these files on their own make a functional website. For that, we need Apps. Apps are where you write the code that makes your website function, but before we take a look at them, we need to understand a bit about Django’s design principles.

First, Django is an MVC framework, which stands for Model View Controller. Django refers to itself an MTV framework, which stands for Model Template View. It’s a slightly different approach than MVC, but fundamentally, they’re quite similar. Anyhow, MVC is an architectural pattern that provides a method for structuring your projects. It separates the code that’s used to process data from the code that manages the user interface.

Django subscribes to the DRY, or “Don’t Repeat Yourself” philosophy.

Secondly, Django subscribes to the DRY, or Don’t Repeat Yourself philosophy, which means that you should never be writing code that performs a certain task more than once. For example, in our blog, if we wrote a feature that picked a random article from the archive, and implemented this feature on multiple pages, we wouldn’t code it again each time it was needed. We’d code it once and then use it on each page.

So how does this relate to apps? Well, apps allow you to write your website in a DRY style. Each project, like the one we have here, can contain multiple apps. Conversely, each app can be part of multiple projects. Using the example from earlier, this means that if we made another site in the future that also needed a random page feature, we wouldn’t have to write it all over again. We could simply import the app from this project. Because of this, it’s important that each app serves one distinct purpose. If you write all the functionality of your site within one app, and then need to use part of it again later, you have to import it all. If you were making an eCommerce website, for example, you wouldn’t want to import all the blog features. However, if you make one app for the random feature and one app for the blog publishing system, you could pick and choose the bits that you require.

This also means that within the site, the code is well organized. If you want to alter a feature, you don’t have to search through one massive file; you can instead browse to the relevant app and change it without worrying about interfering with anything else.

python mangage.py startapp blog
cd blog
ls

Again, we’ve got an __init__.py file to make it a package, and three other files: models, tests and views. We don’t need to worry about tests for now, but the other two are important. Models and Views are the M and V parts of MVC.

In models, we define our data structures.

If you’ve ever worked with PHP before, you might have used PhpMyAdmin to create your MySQL tables, and then written out your SQL queries manually in your PHP scripts. In Django, it’s much easier. We define all the data structures we need in this models file, then run a command and all the necessary databases are made for us.

When you wish to access that data, you go via these models by calling method on them, instead of running raw queries. This is very helpful, because Django can use several database programs. We’re going to use MySQL today, because it’s the most powerful, and is what most hosts provide, but if we needed to switch to a different database in the future, all of the code will still be valid! In other languages, if you wanted to switch to SQLite or something similar, you would need to rewrite the code that accesses your database.

In the views file, we write the code that actually generates the web pages. This ties all the other parts together. When a user types in a URL, it is sent by the urls script we saw earlier to the views script, which then gets relevant data from the models, processes it and passes it into a template, which finally gets served up as the page the user sees. We’ll take a look at those templates shortly. They’re the easiest part – mostly HTML.

For a blog, we’ll need a table of posts, with several fields for the title, body text, author, the time it was written, and so on. A real blog would have comments, but that’s beyond the scope of today’s demo.

from django.db import models

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

MySQL

These models are just a description. We need to make an actual database from them. First, however, we need MySQL running on our system. On an actual web server, this wouldn’t be a problem, because they usually have it preinstalled. Luckily, with a package manager, it’s easy to install. First, you need to install Homebrew and Easy Install

brew install mysql
easy_install mysql-python

mysqld_safe --skip-grant-tables #let anyone have full permissions
mysql -u root
UPDATE mysql.user SET Password=PASSWORD('nettuts') WHERE User='root'; #give the user 'root' a password
FLUSH PRIVILEGES;

mysql -u root -p #log in with our password 'nettuts'
CREATE DATABASE firstblog;
quit

python2.6 manage.py runserver

When you reboot, MySQL won’t be running, so every time you need to do this in the future, run mysqld to start the server. You can then run python2.6 manange.py runserver in a new tab to start the development server.

This command won’t run the server yet, it will just return an error. That’s because we need to configure our settings. Let’s take a look at settings.py.

You need to change the database settings first. These begin on line twelve.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'firstblog',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'nettuts',                  # 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.
    }
}

If you try to run the server again, it should work, provided that you successfully installed MySQL. If you visit 127.0.0.1:8000 in your web browser, you should see the default Django page.

Now let’s turn our Django site into a blog. First, we need to use our Models to create tables in the database by running the following command:

python2.6 manage.py syncdb

Every time you change your models, you should run this command to update the database. Note that this can’t alter existing fields; it may only add new ones. So if you want to remove fields, you’ll have to do that manually with something like PhpMyAdmin. Because this is the first time we’ve run the command, Django will set up all the default built in tables for things like the administration system. Just type ‘yes’ and then fill in your details.

Now let’s set up the urls.py file. Uncomment the first line in the examples section, and change it to say url(r'^$', 'FirstBlog.blog.views.home', name='home') .

Now, let’s create the views file to respond to these requests.

from django.shortcuts import render_to_response

from blog.models import posts

def home(request):
    return render_to_response('index.html')

Templates

This index.html file doesn’t exist yet, so let’s make it. Create a folder, called templates in the blog app and save a file in it called index.html, which can simply contain “Hello World” for now. Then, we need to edit the settings file so Django knows where this template is located.

Line 105 is where the section for declaring template folders starts; so adjust it, like so:

TEMPLATE_DIRS = (
    "blog/templates",
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

If you run the server again and refresh the page in your browser, you should see the “Hello World” message. We can now begin laying out our blog. We’ll add some boilerplate HTML for the home page.

<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="css/style.css">
    <link href="images/favicon.ico" rel="shortcut icon">
    <title>First Blog</title>
</head>

<body>

<div class="container">
    <h1>First Blog</h1>
    <h2>Title</h2>
    <h3>Posted on date by author</h3>
    <p>Body Text</p>

</div>

</body>

</html>

If you save and refresh the page, you should see that the page has been updated with this new content. The next step is to add dynamic content from the database. To accomplish this, Django has a templating language that allows you to embed variables with curly braces. Change the middle section of your page to look like this:

<div class="container">
    <h1>First Blog</h1>
    <h2>{{ title }}</h2>
    <h3>Posted on {{ date }} by {{ author }}</h3>
    <p>{{ body }}</p>

</div>

We can then pass in values to these variable placeholders from the views.py file by creating a dictionary of values.

from django.shortcuts import render_to_response

from blog.models import posts

def home(request):
    content = {
        'title' : 'My First Post',
        'author' : 'Giles',
        'date' : '18th September 2011',
        'body' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam cursus tempus dui, ut vulputate nisl eleifend eget. Aenean justo felis, dapibus quis vulputate at, porta et dolor. Praesent enim libero, malesuada nec vestibulum vitae, fermentum nec ligula. Etiam eget convallis turpis. Donec non sem justo.',
    }
    return render_to_response('index.html', content)

Save and refresh, and you should see that you’re now passing in content to a template from your views file. The final step is to get data from our database and pass that in instead. Luckily, we can do this all without SQL queries, using Django’s models. We need to add our blog app to our FirstBlog project by changing another setting. Go to INSTALLED_APPS on line 112, and add the

'FirstBlog.blog',

to the list.

Then change views.py so it adds data from the database.

from django.shortcuts import render_to_response

from blog.models import posts

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

Next, update the template to access this data.

<div class="container">
    <h1>First Blog</h1>
    <hr />
    {% for post in posts %}
        <div class="post">
        <h2>{{ post.title }}</h2>
        <h3>Posted on {{ post.timestamp }} by {{ post.author }}</h3>
        <p>{{ post.bodytext }}</p>
        </div>
        <hr />
    {% endfor %}
</div>

Here, we can access all the data in our table in the views.py file, then select only the first ten entries. We pass this data into the template, loop through the entries and display the data with the HTML of our site. This won’t work just yet, because there’s nothing in the database. Stop the server and run:

python2.6 manage.py syncdb

This will add the new table for our posts to the database. Then, open a new tab and type:

mysql -u root -p

…type your password, hit enter, and execute:

INSERT INTO blog_posts (author, title, bodytext) values ('Bob', 'Hello World', 'Lorem Ipsum');

Return to the previous tab and run the server again. Refresh the page and you should see a blog post with the dummy content you just added. If you run the MySQL command a few more times, you should see more posts appear on the page when you refresh.

Django’s Admin System

The last thing we need to do today is review Django’s administration system. This is a really powerful feature of Django that lets you manage your site without writing any more code, as you would have to if you were creating a site from scratch. To enable it, we need to change a few settings. First, uncomment lines 4, 5, 13 and 16 within urls.py, so that you can actually access the admin page. Next, go to the INSTALLED_APPS section of settings.py and uncomment 'django.contrib.admin', and 'django.contrib.admindocs',. To let the admin control your posts table, create a new file called admin.py in the blog folder, and add the following lines:

from django.contrib import admin
from blog.models import posts

admin.site.register(posts)

Run python2.6 manage.py syncdb again to add the tables for the admin section, and restart the server.

If you visit 127.0.0.1:8000/admin now in your browser, you should see a login page. Use the details you chose earlier when you first ran the syncdb command to log in. You should see a section, called Blog, with a subtitle for the posts table. You can use this to create, edit and remove blog posts with a simple interface.

That’s all there is to do. You’ve just created a fully functioning, albeit simple, blog. To finish this lesson, we’re going to look at installing Django on a web server.


Installing on a Web Server

There are two types of web hosting, and which one you have will affect whether you can use Django. If you have shared hosting, you’re entirely at the mercy of your host.

Many cheap web hosts don’t support Python. While PHP is nearly guaranteed, support for other languages often isn’t. You’ll have to check the control panel to determine if Python (and Django) are available. Obviously the process is slightly different with every host. Almost all hosting runs on Apache, and we can use it to host Django, using the mod_wsgi or mod_python Apache modules.

Most web hosts run scripts in several languages using CGI. Django can run on FastCGI, and also, theoretically, on CGI, but this is not officially supported and would be far too slow for an actual production website. You’ll need to check if these are installed. They’re usually found under a heading, like “CGI and Scripting Language Support”.

If you have VPS hosting, or are lucky enough to have a dedicated server, your life is much easier. Usually these come with Python preinstalled, and from there, you only need to follow the same steps we went through to get a local copy of Django running. If you don’t have Python, you can install it with a package manager. Your system may even come with Django.

ssh root@example.com

wget http://www.djangoproject.com/download/1.3.1/tarball/
tar xzvf Django-1.3.1.tar.gz
cd Django-1.3.1
python setup.py install

Once you’ve installed Django on your server, upload the site you just made using any file transfer client. You can put the files anywhere, but keep them out of the public folder, or anyone will be able to see the source code of your site. I use /home for all my projects.

Next, create a MySQL database, called ‘firstblog’ on your server and run syncdb again. You’ll have to create your account for the admin control panel again, but this is a one-time thing.

If you try and run this, you might receive an error, and that’s because the settings for the server are different those on your local computer. You may need to change the database password within settings.py, but depending on your server configuration, you may also encounter other issues. Google is your friend in these situations!

To run the server this time, the command is slightly different. You have to specify an IP address and port so that you can access the site over the internet.

python manage.py runserver 0.0.0.0:8000

If you visit your site in a web browser, on port 8000, you should see your site!


Conclusion

That’s it for this lesson…and our series. I hope you’ve learned a number of useful skills over these past five lessons, and that you’re ready to go on and learn even more Python in the future. If you like the look of Django, and wish to continue increasing your knowledge of the framework, here’s some additional tutorials on the subject.

As always, I’m happy to discuss any questions about this tutorial or Python in general within the comments. Thanks for reading.

Tags: Videos
Add Comment

Discussion 55 Comments

  1. kylia says:

    Great tutorial for nettuts+++ ! And good approach for making a real project!

    it’s just awesome…

  2. TheAL says:

    As someone who has never written Python (it was the intro programming class at Uni, and I passed it up to take VB6 back in the day), I am going to power through this and see how it feels. Much appreciated.

  3. Mateus Caldas Craveiro says:

    Thank You for this great tutorial! It’s helped a lot. But i have a doubt, the templates directory don’t need to be the absolute path?

  4. Carlos says:

    Giles, it’s an excellent tutorial, you did a great job, very clear and productive. Congrats!

  5. Bealso says:

    since I saw the IWC website by odopod, I was so hook to DJango. I’m excited that you made this tutorial.

  6. Farshid says:

    I know a little bit of Python and I have always wondered how it tied in with web dev and Django.

    This is a great tutorial that is bookmarked for later use.

  7. Robert Smith says:

    Thank you very much. Great tutorial!

  8. Oscar B. says:

    Nice tutorial. Also, ‘Flame War Trigger’ detected:

    If you’ve ever worked with PHP before, you might have used PhpMyAdmin to create your MySQL tables, and then written out your SQL queries manually in your PHP scripts. In Django, it’s much easier. We define all the data structures we need in this models file, then run a command and all the necessary databases are made for us.

    Yes, you are right, in flat PHP you would go to phpMyAdmin and do all db stuff by hand, and this goes the same for Python. Did I hear Django? lets talk about Symfony…

    Anyhow, nice tutorial, I will pocket it for sure :)

    • Giles Lavelle says:
      Author

      Good point, I guess my wording was a little ambiguous here. No flame wars intended!

      Obviously there are PHP frameworks that make the process just as simple as Django makes it for Python, I wasn’t trying to imply it was an advantage native to Python.

      Before I used Python I wrote all my websites in PHP, without using frameworks, so I was mostly talking about the differences I’ve personally noticed.

  9. Ivanhoe says:

    Thumb up for the article!

    It would be nice to continue the session showing how to further customize and build such blog

  10. TurboGears? This framework is constantly dying. What a strange recommendation. IMHO You should mention Pyramid instead.

    • Rob Charlwood says:

      I’m not sure how you have been using it, but Django has never died for us and we are using it on sites with 2.6 million users and hundreds of thousands of requests a second at peak time! :-) Django is very scalable and reliable in my experience. That’s not to say that Turbogears and Pyramid are not worth looking into because they are, but the author has selected a perfectly good framework for the example he was trying to get across. :-)

      Cheers,
      Rob

  11. Kevin says:

    Brilliant to see more Python on the site, especially Django. I’ve been a php developer for longer than I can remember and for the past 6 months been digging deeper into Python and Django. Django is an awesome framework and has given me that feeling of discovery again!

    In regards to the tutorial, one thing I would add is, rather than downloading the Django package you can simply to `easy_install -U django’ or even better, use pip, `pip install django`.

    Let’s see some more Python tutorials on nettuts!

  12. Goant says:

    I can’t install the MySQL-python on Lion with Xcode 4.

    Either using easy_install or downloading it from soundforge and trying to build, I keep getting an error saying that can’t find gcc4.0 – I’ve also tried installing the 32/64bit Python2.7.2 and then i just changes the error to “can’t find gcc4.2″

    I know I could just use sqlite for the practice of this but eventually I will need to figure the MySQL connection out anyway.

    Any suggestions?

  13. Daniel says:

    Thank God this is not a Premium Tutorial =]

    I’ve stated learning Python last week and that is amazing….I’m trying to find a way to make it work with PHP.

    This tutorial was a great help! Thanks a lot!

    PS: Sorry about my poor English =/

  14. Adam says:

    If you develop locally definitely check out virtualenv and pip. These tools will allow you to dev locally with multiple versions of django, extra software and really anything you want.

    It’s a good idea even on your production servers.

  15. Sergio says:

    Thanks for the tutorial. I’m really interested in learning Django and using Python for my web pages.

    However the problem I see with all the Django tutorials is that they use the web server included in the package (same with Rails tutorials) and I cannot have an independent web server for each application I have, plus I already have some PHP websites that I need to keep running.

    Can you in an upcoming tutorial teach us how to use Django with Apache Web server? There is an extension for apache to run Python pages (PSP) but I don’t know how to get Django to run within it.

  16. eglyph says:

    Django setup step is a little bit complicated. Instead, preferable way would be to get easy_install from http://peak.telecommunity.com/dist/ez_setup.py and set the django as `easy_install django`. This way will pay off in future because a lot of django apps are available via PyPi.

  17. Sizar says:

    Great tutorial. Thank you!

  18. Siros says:

    Thank you so much , I have been waiting for this forever.

    The fun part was spending 4 hours trying to install MysqlDb for python on my mac.

    I manged to do it with pip which is similar to easy_install.

  19. Josh Bedo says:

    Awesome tutorial some what short but contains a ton of useful information. I’ve heard of django before but have never found any good tutorials. I’ve always got stuck on the installation and setup, going to give it a go again this afternoon.

  20. Alistair says:

    This is a wonderful series, and beautifully well presented.

    My 3 fav Authors here on Nettuts at the moment.

    Burak Guzel
    Jeff Way
    Giles Lavelle

    Thanks for sharing guys, this would be a great premium tut.

  21. Cam Carnell says:

    Thanks Giles! I’ve been looking forward to Django tutorials.. keep them coming xD

  22. I was anxious to see what server you’d use to run the site. You say to NOT use the “runserver” command on a production box. So what are the alternatives?

    • Rob Charlwood says:

      You can server a Django app using mod_wsgi and mod_python under Apache

      You can also run it in CGI but is not officially supported.

      You can also run under other lighter weight web servers such as GUnicorn and uwsgi.

      It is also recommended practice to use a high performance lightweight http server such as nginx to serve static content.

      Hope this helps.

      Cheers.

  23. Nice information… sure i will learn. Recently developed small app using python : http://infoanillabs.appspot.com/ by internet tutorials file. Now i can easy to learn to build the apps…

  24. Rob Charlwood says:

    This is a good tutorial for beginners to Python and Django development. Nice work! :-)

    My only constructive criticism would be that it encourages bad practices regarding installing locally and deployment to servers. You should really be using virtualenv and pip or buildout to install python libraries in an isolated ‘sand-boxed’ environment. This avoids stomping on any globally installed python packages and makes maintenance across lots of different projects a complete doddle since you can pin down to a specific version of a package for each project. With buildout you can even apply patches, run isolated instances of Python and C libraries…. which is awesome!

    I appreciate that to go through this kind of setup and config in this tutorial would be a long and lengthy process and that’s why you kept it simple to get people up and running. However, this will only cause people problems further down the line. Maybe this should have been Part 2 of a ‘Python from Scratch’ series of tutorials with part 1 being getting an isolated and correctly setup development platform?

    Cheers!

  25. Louis says:

    Just to be sure, is:

    python mangage.py startapp blog

    meant to be

    python manage.py startapp blog

    ?

  26. john conroy says:

    Well done guys, great job on this :3

  27. Hey Giles!

    Thanks a bundle for a set of loverly tutorials. They’ve been really informative and entertaining aswell.

    I just would’ve loved if someone had warned me about installation on Windows – which can seem a daunting task for beginners. A task that in the PHP community often has been solved by software stacks like Xampp(Mampp / Lampp etc.)

    I’ve recently found one that seems to work great on PC – combined with an apache/mysql stack – which I may think other people could benefit from.

    BitNami – Djangostack : http://bitnami.org/stack/djangostack

    I know a lot of people would argue against it – but to me, it seems great for beginners – because nothing scares away more people than having to struggle for hours with the initial install, as I did.

    It almost turned me off of the language.. I’m glad it didn’t though.

    So for non-pyrists (purists – sorry) and people who just want to play around with django and learn the ropes – this seems like a viable option.

    I hope it could be of help to someone :)

  28. Michael says:

    this tutorial is so helpful i started with tutorial one and i had no problem because time to time you explained how to deal with windows,where you didn’t explain like how to instal o windows i found my way out. i got lost on creating dynamic web using django on windows. please expound how you do it on windows. Moreover i am developing a dynamic website using oracle on my back end and i would want my db to send mail on certain reports and also the user can access the db data using phone. Thank you.

  29. Alejandro says:

    Hi, I’m having some problems with the installation of Python-Mysql library.

    Here’s the error.

    django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/alejandro/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): no suitable image found. Did find:
    /Users/alejandro/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so: mach-o, but wrong architecture

    Does anyone have that problem?

    • Rob Charlwood says:

      aha, the old python-mysql issue on Mac OSX rears its disgustingly ugly face again! :-)

      This error is to do with you having incompatible versions of MySQL and Python.

      If you are running the 32 bit version of Python then you must also be running the 32 bit version of MySQL.
      If you are running the 64 bit version of Python then you must also be running the 64 bit version of MySQL.

      My guess is that you are probably using the inbuilt mac version of Python which is 32 bit and you are running the 64 bit version of MySQL. The MySQL python adapter needs MySQL to be on the same architecture as your Python. I would try installing the 32 bit version of MySQL for your mac. Just remember to take backups of all your databases first as a fresh install will wipe everything ;-)

      Hope this helps.

      Cheers,
      Rob

  30. Oscar B. says:

    Done! Excellent tutorial. I enjoyed a lot more than any RoR tutorial I’ve read/watched. Hope you can bring us more Django!

  31. Ketan says:

    How to server static content like js ,css ?

  32. Paul says:

    I followed the instructions, installed mysql, but when I try to run “mysqld”, I get the following error message:

    Fatal error: Can’t open and lock privilege tables: Table ‘mysql.host’ doesn’t exist

    • d says:

      yes, I am having the same issue. I either get the error mentioned above or this: “Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)”

      any help would be much appreciated!

  33. Jacob says:

    You really should tell people that ‘homebrew’ is Mac OS X ..
    I know that, but others might not.
    Otherwise, refreshing to see an up to date Django tutorial. :)
    Thumbs up.

    • Jacob says:

      Skip my comment about ‘homebrew’ – just watched the video where all is explained in detail..
      Probably the best video tutorial I’ve seen. :)
      And maybe the only Django tutorial you simply *must* watch/follow.

  34. nixnoob says:

    Am unable to install mysql-python on my ubuntu 10.10 distro.. any suggestions for linux users?

  35. akashalo says:

    Hello,
    Thank you for nice writing. It will help me for my research on prescription medications.
    Thanks.

  36. Very good tutorial Giles..!

    Just one thing…

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

    When we filter we don’t show the latest 10 entries.. We show our 10 first blog posts

  37. A very nice tutorial, i must say. Liked it a lot. I also have a blog on tutorials. Here are posts on <a href=”http://www.code2learn.com/search/label/python%20tutorial?&max-results=5″>python tutorial</a>.

  38. hector says:

    Thanks a lot for the tutorial, easy to understand and very easilly explained.

    Looking forward a new tutorial on media serving (css, images) in a real server.

  39. Leandro says:

    Hello and thanks for this great tutorial!

    I’m having this issue with DJango. Whenever I try to enter to localhost it throws me this error:

    ViewDoesNotExist at /

    Could not import FirstBlog.blog.views. Error was: cannot import name posts

    Request Method: GET
    Request URL: http://localhost:8000/
    Django Version: 1.3.1
    Exception Type: ViewDoesNotExist
    Exception Value:

    Could not import FirstBlog.blog.views. Error was: cannot import name posts

    Exception Location: C:\Python27\lib\site-packages\django\core\urlresolvers.py in _get_callback, line 167
    Python Executable: C:\Python27\python.exe
    Python Version: 2.7.2

    What could it be the cause?

  40. Federico says:

    What happened to this session? Are you working on making more of this screencast?

    I really love them and I can wait to see the next one.

  41. brandon says:

    I’m having an issue installing MySQL and making it work with python.

    When I run mysqld in terminal i get

    120408 1:12:12 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/mysql/data/ is case insensitive
    120408 1:12:12 [Note] Plugin ‘FEDERATED’ is disabled.
    mysqld: Table ‘mysql.plugin’ doesn’t exist
    120408 1:12:12 [ERROR] Can’t open the mysql.plugin table. Please run mysql_upgrade to create it.
    120408 1:12:12 InnoDB: The InnoDB memory heap is disabled
    120408 1:12:12 InnoDB: Mutexes and rw_locks use GCC atomic builtins
    120408 1:12:12 InnoDB: Compressed tables use zlib 1.2.3
    120408 1:12:12 InnoDB: Initializing buffer pool, size = 128.0M
    120408 1:12:12 InnoDB: Completed initialization of buffer pool
    120408 1:12:12 InnoDB: highest supported file format is Barracuda.
    120408 1:12:12 InnoDB: Waiting for the background threads to start
    120408 1:12:13 InnoDB: 1.1.8 started; log sequence number 1595675
    120408 1:12:13 [ERROR] Fatal error: Can’t open and lock privilege tables: Table ‘mysql.host’ doesn’t exist

    So I then run mysql_upgrade and get

    Looking for ‘mysql’ as: mysql
    Looking for ‘mysqlcheck’ as: mysqlcheck
    Running ‘mysqlcheck with default connection arguments
    mysqlcheck: Got error: 2002: Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2) when trying to connect
    FATAL ERROR: Upgrade failed

    I’ve been hunting around the web for the past few hours trying to find a solution. Can’t get anything to work.

    Do you guys have any ideas?
    Thank you!

    • William says:

      Great tutorial Giles. So glad it was in video format. I just finished it. I hope net tuts continues to do more python and django tutorials!!!

      I feel like the python developers and those new to the language are underrepresented on net tuts.

      We need more python and django tutorials of this quality!

      Great work!

    • William says:

      Hey Brandon,

      When you install mysql with homebrew there are some instructions at the top that you must follow. Here they are:

      Set up databases to run AS YOUR USER ACCOUNT with:
      unset TMPDIR
      mysql_install_db –verbose –user=`whoami` –basedir=”$(brew –prefix mysql)” –datadir=/usr/local/var/mysql –tmpdir=/tmp

      To set up base tables in another folder, or use a different user to run
      mysqld, view the help for mysqld_install_db:
      mysql_install_db –help

      and view the MySQL documentation:
      * http://dev.mysql.com/doc/refman/5.5/en/mysql-install-db.html
      * http://dev.mysql.com/doc/refman/5.5/en/default-privileges.html

      To run as, for instance, user “mysql”, you may need to `sudo`:
      sudo mysql_install_db …options…

      Start mysqld manually with:
      mysql.server start

      Note: if this fails, you probably forgot to run the first two steps up above

  42. vivek says:

    hello everyone , your series was amazing…er,i have a request “can nettuts help me in making gui with python?” the catch here is the ‘gui’ should be made without using a module(i mean build a gui without tkinter so the gui should be built from scratch) in short gui should be made in a single python file wiht using import or from

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.