1.7 Creating a New Django Project and Django Apps
In the following section, we create a new Django project in preparation for the website laid out in the last section. We then create Django apps, which are like small libraries within our project (we go over them in detail when we create them). By the end, we will be ready to start coding our website.
We do not cover how to install Django here. The official website has an excellent and updated guide2 to do this. Just in case, however, I have supplied my own writing on the subject in Appendix G.
1.7.1 Generating the Project Structure
Inversion of control means that Django already provides most of the code required to run a website. Developers are expected to supplement or extend the existing code so that the framework may then call this code; by placing code in key places, developers instruct the framework how to behave according to the developers’ desires. Think of it as creating a building: even though many of the tools and contractors are supplied, the developer must still give these contractors orders, and the process requires a very specific scaffolding. Originally, building the scaffolding was a real pain, as developers had to manually account for framework conventions. Luckily, modern frameworks supply tools that generate the correct scaffolding for us. Once this scaffolding is in place, we can instruct the various contractors to behave in specific ways.
With Django correctly installed (please see Appendix G), developers have access to the django-admin command-line tool. This command, an alias to the django-admin.py script, provides subcommands to automate Django behavior.
Our immediate interest with django-admin is the startproject subcommand, which automatically generates correct project scaffolding with many, but not all, of the expected Django conventions. To create a project named suorganizer (start up organizer), you can invoke the command shown in Example 1.2.
Example 1.2: Shell Code
$ django-admin startproject suorganizer
Inside the new folder by the name of our new project, you will find the folder structure shown in Example 1.3.
Example 1.3: Shell Code
Please note the existence of two directories titled suorganizer. To avoid confusion between the two directories, I distinguish the top one as root, or /, throughout the rest of the book. As such, instead of writing suorganizer/manage.py, I will refer to that file by writing /manage.py. Importantly, this means /suorganizer/settings.py refers to suorganizer/suorganizer/settings.py. What’s more, all commands executed from the command line will henceforth be run from the root project directory, shown in Example 1.4.
Example 1.4: Shell Code
$ ls manage.py suorganizer
Let’s take a look at what each file or directory does.
- / houses the entire Django project.
- /manage.py is a script much like django-admin.py: it provides utility functions. We will use it in a moment. Note that it is possible to extend manage.py to perform customized tasks, as we will see in Part II.
- /suorganizer/ contains project-wide settings and configuration files.
- /suorganizer/--init--.py is a Python convention: it tells Python to treat the contents of this directory (/suorganizer/) as a package.
/suorganizer/settings.py contains all of your site settings, including but not limited to
- database configuration
- key for cryptographic hashing
- locations of various files (templates, media, static files, etc)
- /suorganizer/urls.py contains a list of valid URLs for the site, which tells your site how to handle each one. We will see these in detail in Chapter 5.
- /suorganizer/wsgi.py stands for Web Server Gateway Interface and contains Django’s development server, which we see next.
1.7.2 Checking Our Installation by Invoking Django’s runserver via manage.py
While Django has only created a skeleton project, it has created a working skeleton project, which we can view using Django’s testing server (the one referenced in /suorganizer/wsgi.py). Django’s /manage.py script, provided to every project, allows us to quickly get up to speed.
Django requires a database before it can run. We can create a database with the (somewhat cryptic) command migrate (Example 1.5).
Example 1.5: Shell Code
$ ./manage.py migrate
You should be greeted with the output (or similar output) shown in Example 1.6.
Example 1.6: Shell Code
Operations to perform: Synchronize unmigrated apps: staticfiles, messages Apply all migrations: contenttypes, auth, admin, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying sessions.0001_initial... OK
We’ll see exactly what’s going on here starting in Chapter 3 and in detail in Chapter 10. For the moment, let’s just get the server running by invoking the runserver command shown in Example 1.7.
Example 1.7: Shell Code
$ ./manage.py runserver Performing system checks... System check identified no issues (0 silenced). May 2, 2015 - 16:15:59 Django version 1.8.1, using settings 'suorganizer.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
Figure 1.6: Runserver Congratulations Screenshot
Django is running a test server on our new project. As the project has nothing in it, Django informs us we need to create an app using /manage.py.
To quit the server, type Control-C in the terminal.
1.7.3 Creating New Django Apps with manage.py
In Django nomenclature, a project is made of any number of apps. More expressly, a project is a website, while an app is a feature, a piece of website functionality. An app may be a blog, comments, or even just a contact form. All of these are encapsulated by a project, however, which is the site in its totality. An app may also be thought of as a library within the project. From Python’s perspective, an app is simply a package (Python files can be modules, and a directory of modules is a package).
We have two features in our site: (1) a structured organization of startups according to tags and (2) a blog. We will create an app for each feature.
As with a project, Django supplies a way to easily create the scaffolding necessary to build an app. This time, we invoke /manage.py to do the work for us, although we could just as easily have used django-admin. Let’s start with the central focus of our site, our startup organizer, and create an app called organizer, as shown in Example 1.8.
Example 1.8: Shell Code
$ ./manage.py startapp organizer
The directory structure of the project should now be as shown in Example 1.9.
Example 1.9: Shell Code
Let’s take a look at the new items.
- /organizer/ contains all the files related to our new organizer app. Any file necessary to running our blog will be in this directory.
- /organizer/--init--.py is a Python convention: just as for /suorganizer/--init--.py, this file tells Python to treat the contents of this directory (/organizer/) as a package.
- /organizer/admin.py contains the configuration necessary to connect our app to the Admin library supplied by Django. While Admin is a major Django feature, it is not part of Django’s core functionality, and we will wait until Part II to examine it, along with the rest of the Django Contributed Library (apps included with Django’s default install). If you are very impatient, you should be able to jump to Chapter 23: The Admin Library as soon as you’ve finished reading Chapter 5.
- /organizer/migrations/ is a directory that contains data pertaining to the database tables for our app. It enables Django to keep track of any structural changes the developer makes to the database as the project changes, allowing for multiple developers to easily change the database in unison. We will see basic use of this database table in Chapter 3 and revisit the topic in Chapter 10.
- /organizer/migrations/--init--.py marks the migration directory as a Python package.
- /organizer/models.py tells Django how to organize data for this app. We do see how this is done in the next chapter.
- /organizer/tests.py contains functions to unit test our app. Testing is a book unto itself (written by Harry Percival), and we do not cover that material.
- /organizer/views.py contains all of the functions that Django will use to process data and to select data for display. We make use of views starting in Chapter 2 but won’t fully understand them until Chapter 5.
Django encapsulates data and behavior by app. The files above are where Django will look for data structure, website behavior, and even testing. This may not make sense yet, but it means that when building a site with Django, it is important to consider how behavior is organized across apps. Planning how your apps interact and which apps you need, as we did earlier in this chapter, is a crucial step to building a Django site.
We can create our blog app in exactly the same way as the organizer app, as shown in Example 1.10.
Example 1.10: Shell Code
$ ./manage.py startapp blog
Note that the directory structure and all the files generated are exactly the same as for our organizer app.
1.7.4 Connecting Our New Django Apps to Our Django Project in settings.py
Consider for a moment the difference between /organizer/ (or /blog/) and /suorganizer/. Both encapsulate data, the former for our organizer (or blog) app and the second for our project-wide settings, a phrase that should mean more now that we know the difference between an app and a project (reminder: a project is made up of one or more apps).
We must now connect our new apps to our project; we must inform our project of the existence of organizer and blog. On line 33 of /suorganizer/settings.py, you will find a list of items titled INSTALLED_APPS. Currently enabled in our project are a list of Django contributed apps (you can tell because these items all start with django.contrib), some of which we examine in Part II. We append the list with our new apps, as shown in Example 1.11.
Example 1.11: Project Code
suorganizer/settings.py in ba014edf45
33 INSTALLED_APPS = ( 34 'django.contrib.admin', 35 'django.contrib.auth', 36 'django.contrib.contenttypes', 37 'django.contrib.sessions', 38 'django.contrib.messages', 39 'django.contrib.staticfiles', 40 'organizer', 41 'blog', 42 )
Let’s run our test server again (Example 1.12).
Example 1.12: Shell Code
$ ./manage.py runserver 7777 Performing system checks... System check identified no issues (0 silenced). February 10, 2015 - 19:09:25 Django version 1.8.3, using settings 'suorganizer.settings' Starting development server at http://127.0.0.1:7777/ Quit the server with CONTROL-C.
Navigating to the page in your browser, you should be greeted by exactly the same page in your browser, telling you once again to
- Create a new App
- Configure our site URLs
We have successfully done item 1 and will demonstrate item 2 in our Hello World example in the next chapter.
We will return to our main project in Chapter 3, where we organize our data and create a database. In Chapter 4, we create templates to display data. In Chapter 5, we build our URL configuration (expanding on item 2 above) and the rest of the MVC Controller. These activities will effectively reveal how Model-View-Controller theory maps to Django.