Home > Articles > Open Source > Python

This chapter is from the book

This chapter is from the book

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

018pro02.jpg

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

    • timezone
    • 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.

If you navigate your browser to http://127.0.0.1:8000/, you should be greeted with the screen printed in Figure 1.6.

Figure 1.6

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

018pro02.jpg

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

  1. Create a new App
  2. 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020