Writing your first Django app, part 2

This tutorial begins where Tutorial 1 left off.We’ll setup the database, create your first model, and get a quick introductionto Django’s automatically-generated admin site.

Database setup

Now, open up mysite/settings.py. It’s a normal Python module withmodule-level variables representing Django settings.

By default, the configuration uses SQLite. If you’re new to databases, oryou’re just interested in trying Django, this is the easiest choice. SQLite isincluded in Python, so you won’t need to install anything else to support yourdatabase. When starting your first real project, however, you may want to use amore scalable database like PostgreSQL, to avoid database-switching headachesdown the road.

If you wish to use another database, install the appropriate databasebindings and change the following keys in theDATABASES 'default' item to match your database connectionsettings:

  • ENGINE – Either'django.db.backends.sqlite3','django.db.backends.postgresql','django.db.backends.mysql', or'django.db.backends.oracle'. Other backends are also available.
  • NAME – The name of your database. If you’re using SQLite, thedatabase will be a file on your computer; in that case, NAMEshould be the full absolute path, including filename, of that file. Thedefault value, os.path.join(BASE_DIR, 'db.sqlite3'), will store the filein your project directory.If you are not using SQLite as your database, additional settings such asUSER, PASSWORD, and HOST must be added.For more details, see the reference documentation for DATABASES.

For databases other than SQLite

If you’re using a database besides SQLite, make sure you’ve created adatabase by this point. Do that with “CREATE DATABASE database_name;”within your database’s interactive prompt.

Also make sure that the database user provided in mysite/settings.pyhas “create database” privileges. This allows automatic creation of atest database which will be needed in a latertutorial.

If you’re using SQLite, you don’t need to create anything beforehand - thedatabase file will be created automatically when it is needed.

While you’re editing mysite/settings.py, set TIME_ZONE toyour time zone.

Also, note the INSTALLED_APPS setting at the top of the file. Thatholds the names of all Django applications that are activated in this Djangoinstance. Apps can be used in multiple projects, and you can package anddistribute them for use by others in their projects.

By default, INSTALLED_APPS contains the following apps, all of whichcome with Django:

Some of these applications make use of at least one database table, though,so we need to create the tables in the database before we can use them. To dothat, run the following command:

  1. $ python manage.py migrate
  1. ...\> py manage.py migrate

The migrate command looks at the INSTALLED_APPS settingand creates any necessary database tables according to the database settingsin your mysite/settings.py file and the database migrations shippedwith the app (we’ll cover those later). You’ll see a message for eachmigration it applies. If you’re interested, run the command-line client for yourdatabase and type \dt (PostgreSQL), SHOW TABLES; (MariaDB, MySQL),.schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) todisplay the tables Django created.

For the minimalists

Like we said above, the default applications are included for the commoncase, but not everybody needs them. If you don’t need any or all of them,feel free to comment-out or delete the appropriate line(s) fromINSTALLED_APPS before running migrate. Themigrate command will only run migrations for apps inINSTALLED_APPS.

Creating models

Now we’ll define your models – essentially, your database layout, withadditional metadata.

Philosophy

A model is the single, definitive source of truth about your data. It containsthe essential fields and behaviors of the data you’re storing. Django followsthe DRY Principle. The goal is to define your data model in oneplace and automatically derive things from it.

This includes the migrations - unlike in Ruby On Rails, for example, migrationsare entirely derived from your models file, and are essentially ahistory that Django can roll through to update your database schema tomatch your current models.

In our poll app, we’ll create two models: Question and Choice. AQuestion has a question and a publication date. A Choice has twofields: the text of the choice and a vote tally. Each Choice is associatedwith a Question.

These concepts are represented by Python classes. Edit thepolls/models.py file so it looks like this:

polls/models.py

  1. from django.db import models
  2.  
  3.  
  4. class Question(models.Model):
  5. question_text = models.CharField(max_length=200)
  6. pub_date = models.DateTimeField('date published')
  7.  
  8.  
  9. class Choice(models.Model):
  10. question = models.ForeignKey(Question, on_delete=models.CASCADE)
  11. choice_text = models.CharField(max_length=200)
  12. votes = models.IntegerField(default=0)

Here, each model is represented by a class that subclassesdjango.db.models.Model. Each model has a number of class variables,each of which represents a database field in the model.

Each field is represented by an instance of a Fieldclass – e.g., CharField for character fields andDateTimeField for datetimes. This tells Django whattype of data each field holds.

The name of each Field instance (e.g.question_text or pub_date) is the field’s name, in machine-friendlyformat. You’ll use this value in your Python code, and your database will useit as the column name.

You can use an optional first positional argument to aField to designate a human-readable name. That’s usedin a couple of introspective parts of Django, and it doubles as documentation.If this field isn’t provided, Django will use the machine-readable name. In thisexample, we’ve only defined a human-readable name for Question.pub_date.For all other fields in this model, the field’s machine-readable name willsuffice as its human-readable name.

Some Field classes have required arguments.CharField, for example, requires that you give it amax_length. That’s used not only in thedatabase schema, but in validation, as we’ll soon see.

A Field can also have various optional arguments; inthis case, we’ve set the default value ofvotes to 0.

Finally, note a relationship is defined, usingForeignKey. That tells Django each Choice isrelated to a single Question. Django supports all the common databaserelationships: many-to-one, many-to-many, and one-to-one.

Activating models

That small bit of model code gives Django a lot of information. With it, Djangois able to:

  • Create a database schema (CREATE TABLE statements) for this app.
  • Create a Python database-access API for accessing Question and Choice objects.But first we need to tell our project that the polls app is installed.

Philosophy

Django apps are “pluggable”: You can use an app in multiple projects, andyou can distribute apps, because they don’t have to be tied to a givenDjango installation.

To include the app in our project, we need to add a reference to itsconfiguration class in the INSTALLED_APPS setting. ThePollsConfig class is in the polls/apps.py file, so its dotted pathis 'polls.apps.PollsConfig'. Edit the mysite/settings.py file andadd that dotted path to the INSTALLED_APPS setting. It’ll look likethis:

mysite/settings.py

  1. INSTALLED_APPS = [
  2. 'polls.apps.PollsConfig',
  3. 'django.contrib.admin',
  4. 'django.contrib.auth',
  5. 'django.contrib.contenttypes',
  6. 'django.contrib.sessions',
  7. 'django.contrib.messages',
  8. 'django.contrib.staticfiles',
  9. ]

Now Django knows to include the polls app. Let’s run another command:

  1. $ python manage.py makemigrations polls
  1. ...\> py manage.py makemigrations polls

You should see something similar to the following:

  1. Migrations for 'polls':
  2. polls/migrations/0001_initial.py:
  3. - Create model Choice
  4. - Create model Question
  5. - Add field question to choice

By running makemigrations, you’re telling Django that you’ve madesome changes to your models (in this case, you’ve made new ones) and thatyou’d like the changes to be stored as a migration.

Migrations are how Django stores changes to your models (and thus yourdatabase schema) - they’re files on disk. You can read the migration for yournew model if you like; it’s the file polls/migrations/0001_initial.py.Don’t worry, you’re not expected to read them every time Django makes one, butthey’re designed to be human-editable in case you want to manually tweak howDjango changes things.

There’s a command that will run the migrations for you and manage your databaseschema automatically - that’s called migrate, and we’ll come to it in amoment - but first, let’s see what SQL that migration would run. Thesqlmigrate command takes migration names and returns their SQL:

  1. $ python manage.py sqlmigrate polls 0001
  1. ...\> py manage.py sqlmigrate polls 0001

You should see something similar to the following (we’ve reformatted it forreadability):

  1. BEGIN;

— Create model Choice

CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL

);

— Create model Question

CREATE TABLE "polls_question" ( "id" serial NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL

);

— Add field question to choice

ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");ALTER TABLE "polls_choice" ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id" FOREIGN KEY ("question_id") REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED;

COMMIT;

Note the following:

  • The exact output will vary depending on the database you are using. Theexample above is generated for PostgreSQL.
  • Table names are automatically generated by combining the name of the app(polls) and the lowercase name of the model – question andchoice. (You can override this behavior.)
  • Primary keys (IDs) are added automatically. (You can override this, too.)
  • By convention, Django appends "_id" to the foreign key field name.(Yes, you can override this, as well.)
  • The foreign key relationship is made explicit by a FOREIGN KEYconstraint. Don’t worry about the DEFERRABLE parts; it’s tellingPostgreSQL to not enforce the foreign key until the end of the transaction.
  • It’s tailored to the database you’re using, so database-specific field typessuch as auto_increment (MySQL), serial (PostgreSQL), or integerprimary key autoincrement (SQLite) are handled for you automatically. Samegoes for the quoting of field names – e.g., using double quotes orsingle quotes.
  • The sqlmigrate command doesn’t actually run the migration on yourdatabase - instead, it prints it to the screen so that you can see what SQLDjango thinks is required. It’s useful for checking what Django is going todo or if you have database administrators who require SQL scripts forchanges.If you’re interested, you can also runpython manage.py check; this checks for any problems inyour project without making migrations or touching the database.

Now, run migrate again to create those model tables in your database:

  1. $ python manage.py migrate
  2. Operations to perform:
  3. Apply all migrations: admin, auth, contenttypes, polls, sessions
  4. Running migrations:
  5. Rendering model states... DONE
  6. Applying polls.0001_initial... OK
  1. ...\> py manage.py migrate
  2. Operations to perform:
  3. Apply all migrations: admin, auth, contenttypes, polls, sessions
  4. Running migrations:
  5. Rendering model states... DONE
  6. Applying polls.0001_initial... OK

The migrate command takes all the migrations that haven’t beenapplied (Django tracks which ones are applied using a special table in yourdatabase called django_migrations) and runs them against your database -essentially, synchronizing the changes you made to your models with the schemain the database.

Migrations are very powerful and let you change your models over time, as youdevelop your project, without the need to delete your database or tables andmake new ones - it specializes in upgrading your database live, withoutlosing data. We’ll cover them in more depth in a later part of the tutorial,but for now, remember the three-step guide to making model changes:

  • Change your models (in models.py).
  • Run python manage.py makemigrations to createmigrations for those changes
  • Run python manage.py migrate to apply those changes tothe database.The reason that there are separate commands to make and apply migrations isbecause you’ll commit migrations to your version control system and ship themwith your app; they not only make your development easier, they’re alsousable by other developers and in production.

Read the django-admin documentation for fullinformation on what the manage.py utility can do.

Playing with the API

Now, let’s hop into the interactive Python shell and play around with the freeAPI Django gives you. To invoke the Python shell, use this command:

  1. $ python manage.py shell
  1. ...\> py manage.py shell

We’re using this instead of simply typing “python”, because manage.pysets the DJANGO_SETTINGS_MODULE environment variable, which gives Djangothe Python import path to your mysite/settings.py file.

Once you’re in the shell, explore the database API:

  1. >>> from polls.models import Choice, Question # Import the model classes we just wrote.
  2.  
  3. # No questions are in the system yet.
  4. >>> Question.objects.all()
  5. <QuerySet []>
  6.  
  7. # Create a new Question.
  8. # Support for time zones is enabled in the default settings file, so
  9. # Django expects a datetime with tzinfo for pub_date. Use timezone.now()
  10. # instead of datetime.datetime.now() and it will do the right thing.
  11. >>> from django.utils import timezone
  12. >>> q = Question(question_text="What's new?", pub_date=timezone.now())
  13.  
  14. # Save the object into the database. You have to call save() explicitly.
  15. >>> q.save()
  16.  
  17. # Now it has an ID.
  18. >>> q.id
  19. 1
  20.  
  21. # Access model field values via Python attributes.
  22. >>> q.question_text
  23. "What's new?"
  24. >>> q.pub_date
  25. datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
  26.  
  27. # Change values by changing the attributes, then calling save().
  28. >>> q.question_text = "What's up?"
  29. >>> q.save()
  30.  
  31. # objects.all() displays all the questions in the database.
  32. >>> Question.objects.all()
  33. <QuerySet [<Question: Question object (1)>]>

Wait a minute. <Question: Question object (1)> isn’t a helpfulrepresentation of this object. Let’s fix that by editing the Question model(in the polls/models.py file) and adding astr() method to both Question andChoice:

polls/models.py

  1. from django.db import models
  2.  
  3. class Question(models.Model):
  4. # ...
  5. def __str__(self):
  6. return self.question_text
  7.  
  8. class Choice(models.Model):
  9. # ...
  10. def __str__(self):
  11. return self.choice_text

It’s important to add str() methods to yourmodels, not only for your own convenience when dealing with the interactiveprompt, but also because objects’ representations are used throughout Django’sautomatically-generated admin.

Note these are normal Python methods. Let’s add a custom method, just fordemonstration:

polls/models.py

  1. import datetime
  2.  
  3. from django.db import models
  4. from django.utils import timezone
  5.  
  6.  
  7. class Question(models.Model):
  8. # ...
  9. def was_published_recently(self):
  10. return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

Note the addition of import datetime and from django.utils importtimezone, to reference Python’s standard datetime module and Django’stime-zone-related utilities in django.utils.timezone, respectively. Ifyou aren’t familiar with time zone handling in Python, you can learn more inthe time zone support docs.

Save these changes and start a new Python interactive shell by runningpython manage.py shell again:

  1. >>> from polls.models import Choice, Question
  2.  
  3. # Make sure our __str__() addition worked.
  4. >>> Question.objects.all()
  5. <QuerySet [<Question: What's up?>]>
  6.  
  7. # Django provides a rich database lookup API that's entirely driven by
  8. # keyword arguments.
  9. >>> Question.objects.filter(id=1)
  10. <QuerySet [<Question: What's up?>]>
  11. >>> Question.objects.filter(question_text__startswith='What')
  12. <QuerySet [<Question: What's up?>]>
  13.  
  14. # Get the question that was published this year.
  15. >>> from django.utils import timezone
  16. >>> current_year = timezone.now().year
  17. >>> Question.objects.get(pub_date__year=current_year)
  18. <Question: What's up?>
  19.  
  20. # Request an ID that doesn't exist, this will raise an exception.
  21. >>> Question.objects.get(id=2)
  22. Traceback (most recent call last):
  23. ...
  24. DoesNotExist: Question matching query does not exist.
  25.  
  26. # Lookup by a primary key is the most common case, so Django provides a
  27. # shortcut for primary-key exact lookups.
  28. # The following is identical to Question.objects.get(id=1).
  29. >>> Question.objects.get(pk=1)
  30. <Question: What's up?>
  31.  
  32. # Make sure our custom method worked.
  33. >>> q = Question.objects.get(pk=1)
  34. >>> q.was_published_recently()
  35. True
  36.  
  37. # Give the Question a couple of Choices. The create call constructs a new
  38. # Choice object, does the INSERT statement, adds the choice to the set
  39. # of available choices and returns the new Choice object. Django creates
  40. # a set to hold the "other side" of a ForeignKey relation
  41. # (e.g. a question's choice) which can be accessed via the API.
  42. >>> q = Question.objects.get(pk=1)
  43.  
  44. # Display any choices from the related object set -- none so far.
  45. >>> q.choice_set.all()
  46. <QuerySet []>
  47.  
  48. # Create three choices.
  49. >>> q.choice_set.create(choice_text='Not much', votes=0)
  50. <Choice: Not much>
  51. >>> q.choice_set.create(choice_text='The sky', votes=0)
  52. <Choice: The sky>
  53. >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
  54.  
  55. # Choice objects have API access to their related Question objects.
  56. >>> c.question
  57. <Question: What's up?>
  58.  
  59. # And vice versa: Question objects get access to Choice objects.
  60. >>> q.choice_set.all()
  61. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
  62. >>> q.choice_set.count()
  63. 3
  64.  
  65. # The API automatically follows relationships as far as you need.
  66. # Use double underscores to separate relationships.
  67. # This works as many levels deep as you want; there's no limit.
  68. # Find all Choices for any question whose pub_date is in this year
  69. # (reusing the 'current_year' variable we created above).
  70. >>> Choice.objects.filter(question__pub_date__year=current_year)
  71. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
  72.  
  73. # Let's delete one of the choices. Use delete() for that.
  74. >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
  75. >>> c.delete()

For more information on model relations, see Accessing related objects. For more on how to use double underscores to performfield lookups via the API, see Field lookups. Forfull details on the database API, see our Database API reference.

Introducing the Django Admin

Philosophy

Generating admin sites for your staff or clients to add, change, and deletecontent is tedious work that doesn’t require much creativity. For thatreason, Django entirely automates creation of admin interfaces for models.

Django was written in a newsroom environment, with a very clear separationbetween “content publishers” and the “public” site. Site managers use thesystem to add news stories, events, sports scores, etc., and that content isdisplayed on the public site. Django solves the problem of creating aunified interface for site administrators to edit content.

The admin isn’t intended to be used by site visitors. It’s for sitemanagers.

Creating an admin user

First we’ll need to create a user who can login to the admin site. Run thefollowing command:

  1. $ python manage.py createsuperuser
  1. ...\> py manage.py createsuperuser

Enter your desired username and press enter.

  1. Username: admin

You will then be prompted for your desired email address:

  1. Email address: admin@example.com

The final step is to enter your password. You will be asked to enter yourpassword twice, the second time as a confirmation of the first.

  1. Password: **********
  2. Password (again): *********
  3. Superuser created successfully.

Start the development server

The Django admin site is activated by default. Let’s start the developmentserver and explore it.

If the server is not running start it like so:

  1. $ python manage.py runserver
  1. ...\> py manage.py runserver

Now, open a Web browser and go to “/admin/” on your local domain – e.g.,http://127.0.0.1:8000/admin/. You should see the admin’s login screen:Django admin login screenSince translation is turned on by default,the login screen may be displayed in your own language, depending on yourbrowser’s settings and if Django has a translation for this language.

Enter the admin site

Now, try logging in with the superuser account you created in the previous step.You should see the Django admin index page:Django admin index pageYou should see a few types of editable content: groups and users. They areprovided by django.contrib.auth, the authentication framework shippedby Django.

Make the poll app modifiable in the admin

But where’s our poll app? It’s not displayed on the admin index page.

Only one more thing to do: we need to tell the admin that Question objectshave an admin interface. To do this, open the polls/admin.py file, andedit it to look like this:

polls/admin.py

  1. from django.contrib import admin
  2.  
  3. from .models import Question
  4.  
  5. admin.site.register(Question)

Explore the free admin functionality

Now that we’ve registered Question, Django knows that it should be displayed onthe admin index page:Django admin index page, now with polls displayedClick “Questions”. Now you’re at the “change list” page for questions. This pagedisplays all the questions in the database and lets you choose one to change it.There’s the “What’s up?” question we created earlier:Polls change list pageClick the “What’s up?” question to edit it:Editing form for question objectThings to note here:

  • The form is automatically generated from the Question model.
  • The different model field types (DateTimeField,CharField) correspond to the appropriate HTMLinput widget. Each type of field knows how to display itself in the Djangoadmin.
  • Each DateTimeField gets free JavaScriptshortcuts. Dates get a “Today” shortcut and calendar popup, and times geta “Now” shortcut and a convenient popup that lists commonly entered times.The bottom part of the page gives you a couple of options:

  • Save – Saves changes and returns to the change-list page for this type ofobject.

  • Save and continue editing – Saves changes and reloads the admin page forthis object.
  • Save and add another – Saves changes and loads a new, blank form for thistype of object.
  • Delete – Displays a delete confirmation page.If the value of “Date published” doesn’t match the time when you created thequestion in Tutorial 1, it probablymeans you forgot to set the correct value for the TIME_ZONE setting.Change it, reload the page and check that the correct value appears.

Change the “Date published” by clicking the “Today” and “Now” shortcuts. Thenclick “Save and continue editing.” Then click “History” in the upper right.You’ll see a page listing all changes made to this object via the Django admin,with the timestamp and username of the person who made the change:History page for question objectWhen you’re comfortable with the models API and have familiarized yourself withthe admin site, read part 3 of this tutorial to learnabout how to add more views to our polls app.