A Crash Course in Django

Share this article

Are you after a web framework that drastically cuts the time it takes to build data-driven web apps? If so, the Python-based Django might be worth investigating. With a unique architecture enabling extensive code reuse and an automatic admin system, Django is the state of the art for independent web developers, as well as being a strong tool for large scale web projects. In this article, I’ll show you how the basics of setting up your own Django-powered web site.

Introducing Django

Django is a fully-fledged, high-level web application framework that enables web developers to get robust applications up and running in record time. It’s powered by Python, which you might be unfamiliar with, but is easy to pick up. If you need a quick crash course in Python, I recommend Learn Python in 10 minutes, though A Quick, Painless Tutorial on the Python Language also offers a lot of depth.

Django’s key feature for web developers is the concept of a single web site being powered by multiple, self-contained, function-based applications. These applications might provide a blog, a user login system, or even a TinyURL-style redirection service. Your web site consists of a set of applications, and when constructing it, you simply pick existing applications—or build your own—that provide the functionality you require.

Another killer feature is the automatic admin system. When you build models in Django, you’re gifted with a free admin system to add, delete, and update them, managing the underlying database automatically. The admin system will provide a rich interface for end users to update the data in the database. The automatic admin system is a complete end-to-end solution as a data interface, and is ready for production use out of the box; it’s also extremely customizable.

Before You Begin

Before exploring this tutorial, you should have basic web development experience with database back ends, and preferably a basic Python background. Experience building PHP applications with some major framework is sufficient. Django takes advantage of sophisticated approaches to web applications and does require a solid grasp of web development concepts.

You’ll need Django installed for this tutorial. Run through the installation documentation if you’ve yet to set this up, clicking on Install an official release. This article was written using 1.2 alpha; 1.1 is generally available and this tutorial should work with any 1.x release.

When installing, make sure the django-admin.py tool is on your system path. This should happen automatically, but to check, open up your system’s terminal or command line console and run django-admin.py; if the output reads Type 'django-admin.py help' for usage (or something similar), you’re ready to go.

To explore the Django framework, we’re going to create our own blog application (though there are plenty available) and use it to power a simple blog site. We’ll also be using the built-in admin, comments, and authentication applications. Make sure you’re comfortable with the command line, as we’ll be working with it frequently.

You can download a copy of the finished application here, but we’ll be covering all the code required, so you’d be best to simply follow along and create the files as you go.

Setting up the Admin Site

Start by choosing a folder to store your Django projects—I use ~/Development/Django/—and switch to this folder on the command line. We need to start a new Django project for our web site, so run django-admin.py startproject spblog when you’re ready. Then switch to the newly created spblog folder and have a look at the files the django-admin.py utility created (Windows users: use dir instead of ls). This is what it all looks like in the terminal:

$ cd ~/Development/Django$ django-admin.py startproject spblog$ cd spblog$ ls__init__.py  manage.py  settings.py  urls.py

The django-admin.py script has created four files, but we only really need to worry about two: settings.py and urls.py.

Your first Django app is now ready to go! Let’s start up a test server and take it for a spin:

$ python manage.py runserverValidating models...0 errors foundDjango version 1.2 pre-alpha SVN-11600, using settings 'spblog.settings'Development server is running at http://127.0.0.1:8000/Quit the server with CONTROL-C.

The manage.py script provides access to a number of helpful tools in the context of this particular Django project. One of these tools is a built-in web server (for development purposes only!), which is now serving up your web application at http://127.0.0.1:8000/. Load that URL in your web browser and you’ll see the following page.

Figure 1. It worked!

It worked!

As the welcome page suggests, we still need an app to provide content to look at. Let’s start with the built-in administration site.

To use the admin site, we first need to configure the database. We’ll use the file-based SQLite database, and install the admin application. First open settings.py and change the following settings:

DATABASE_ENGINE = 'sqlite3'DATABASE_NAME = 'dev.db'

We also need to add django.contrib.admin to the end of the INSTALLED_APPS setting: it should look like this:

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

Now head back to your command line. We’re going to create the database using the manage.py syncdb command, which will also prompt us to create an administrator user account. Here’s what your command history should look like:

$ python manage.py syncdbCreating table auth_permissionCreating table auth_groupCreating table auth_userCreating table auth_messageCreating table django_content_typeCreating table django_sessionCreating table django_siteCreating table django_admin_logYou just installed Django's auth system, which means you don't have any superusers defined.Would you like to create one now? (yes/no): yesUsername (Leave blank to use '…'): E-mail address: …Password: Password (again): Superuser created successfully.Installing index for auth.Permission modelInstalling index for auth.Message modelInstalling index for admin.LogEntry model

Create an account with a username and password of your choice during the process—you’ll use this to log in to the admin site in a moment.

There’s one more task we need to complete before we can use the admin site: configure the URLs. Django has a unique approach to URL routing, where URLs do not automatically map to specific request handling code (or controller methods/actions, if you’ve used another MVC framework). Instead, we use regular expressions to map URLs to views. For more details on URLs in Django, see the URL Dispatcher section in the documentation.

Open urls.py and uncomment these lines related to the admin system (Python single-line comments begin with a #):

from django.contrib import adminadmin.autodiscover()⋮(r'^admin/', include(admin.site.urls)), 

Now, all URLs beginning with admin/ will be delegated to the admin system. In addition, we call the autodiscover method: this will make the admin system inspect the database to discover what database tables it will be managing. We put this command into urls.py, because it will be run once every time the server is started.

Save urls.py and head back to your command line; the development server should have restarted automatically (if not, kill it with CtrlC and run it again).

Now if we refresh our browser at http://localhost:8000/, we see a different page:

Figure 2. Page not found

Page not found

This is a special 404 page for development purposes only—once you switch DEBUG from True to False in your settings, it will no longer appear. However, now that you have some URLs configured, Django no longer displays the welcome page, and instead offers a list of valid URLs (assuming the one you’re attempting to access is invalid). As our admin/ URL seems to be okay, let’s head to http://localhost:8000/admin/ to check out our admin site.

Log in to the admin site using the username and password you configured while running the syncdb command; you should see the admin home page:

Figure 3. Django administration

Django administration

Your admin site is ready to go! Take some time to explore, create some users, and experiment with the tools available.

Frequently Asked Questions (FAQs) about Django Crash Course

What is Django and why is it important in web development?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It’s built by experienced developers and takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source, which makes it highly customizable and adaptable for various types of web development projects. Django is important in web development because it provides a set of components to help developers create websites or web applications faster and easier.

How can I install Django on my system?

Django can be installed on your system using pip, which is a package manager for Python. You can install Django by running the command ‘pip install Django’ in your command prompt or terminal. Before installing Django, make sure that Python and pip are already installed on your system.

What are Django models and how do they work?

Django models are a part of Django’s Object-Relational Mapping (ORM) layer. They define the data structure of a database. Each model maps to a single database table and contains fields and behaviors of the data that is stored. Essentially, Django models are the source of information for your data. They contain essential fields and behaviors of the data you’re storing.

How can I create views in Django?

In Django, a view is a Python function that receives a web request and returns a web response. You can create a view by defining a function inside your views.py file in your application directory. This function needs to take a request argument and return a response.

What is Django’s admin interface and how can I use it?

Django’s admin interface is a powerful built-in feature that automatically provides a user interface for managing the data related to your models. To use it, you first need to create a superuser by running the command ‘python manage.py createsuperuser’ in your terminal. Then, you can access the admin interface by navigating to ‘/admin/’ on your local server.

How can I handle forms in Django?

Django provides several ways to handle forms, including form classes which you can instantiate and use in your views and templates. Django’s form handling uses all of the same techniques that we’ve already talked about – handling form data is really just handling POST data.

What are Django templates and how do they work?

Django templates are a key component of the Django framework. They define how the user sees and interacts with your web application. Django’s template language is designed to strike a balance between power and ease. It’s designed to feel comfortable to those used to working with HTML.

How can I deploy a Django application?

Deploying a Django application can be done in several ways, depending on your hosting provider. Some popular options include using platforms like Heroku, PythonAnywhere, or even a traditional web server with a WSGI server.

How can I use Django with a database?

Django comes with a built-in database abstraction layer that can use different backends such as MySQL, PostgreSQL, SQLite, Oracle, or a third-party database backend. You can set up your database in the settings.py file of your Django project.

How can I handle user authentication in Django?

Django comes with a built-in user authentication system that handles objects like users, groups, user-permissions and cookie-based user sessions. This allows you to authenticate users, along with the ability to add, edit, and delete users, and more.

Akash MehtaAkash Mehta
View Author

Akash Mehta is a web developer and freelance writer specializing in web application development.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week