Writing your first Django app, part 2¶
This tutorial begins whereTutorial 1 left off.We’ll setup the database, create your first model, and get a quick introductionto Django’s automatically-generated admin site.
Where to get help:
If you’re having trouble going through this tutorial, please head over totheGetting Help section of the FAQ.
Database setup¶
Now, open upmysite/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 appropriatedatabasebindings 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 arealso available.NAME
– The name of your database. If you’re using SQLite, thedatabase will be a file on your computer; in that case,NAME
should be the full absolute path, including filename, of that file. Thedefault value,BASE_DIR/'db.sqlite3'
, will store the file in yourproject directory.
If you are not using SQLite as your database, additional settings such asUSER
,PASSWORD
, andHOST
must be added.For more details, see the reference documentation forDATABASES
.
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 “CREATEDATABASEdatabase_name;
”within your database’s interactive prompt.
Also make sure that the database user provided inmysite/settings.py
has “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 editingmysite/settings.py
, setTIME_ZONE
toyour time zone.
Also, note theINSTALLED_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:
django.contrib.admin
– The admin site. You’ll use it shortly.django.contrib.auth
– An authentication system.django.contrib.contenttypes
– A framework for content types.django.contrib.sessions
– A session framework.django.contrib.messages
– A messaging framework.django.contrib.staticfiles
– A framework for managingstatic files.
These applications are included by default as a convenience for the common case.
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:
$python manage.py migrate
...\> py manage.py migrate
Themigrate
command looks at theINSTALLED_APPS
settingand creates any necessary database tables according to the database settingsin yourmysite/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),SHOWTABLES;
(MariaDB, MySQL),.schema
(SQLite), orSELECTTABLE_NAMEFROMUSER_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 runningmigrate
. 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 followstheDRY 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
andChoice
. AQuestion
has a question and a publication date. AChoice
has twofields: the text of the choice and a vote tally. EachChoice
is associatedwith aQuestion
.
These concepts are represented by Python classes. Edit thepolls/models.py
file so it looks like this:
fromdjango.dbimportmodelsclassQuestion(models.Model):question_text=models.CharField(max_length=200)pub_date=models.DateTimeField('date published')classChoice(models.Model):question=models.ForeignKey(Question,on_delete=models.CASCADE)choice_text=models.CharField(max_length=200)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 aField
class – e.g.,CharField
for character fields andDateTimeField
for datetimes. This tells Django whattype of data each field holds.
The name of eachField
instance (e.g.question_text
orpub_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 forQuestion.pub_date
.For all other fields in this model, the field’s machine-readable name willsuffice as its human-readable name.
SomeField
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.
AField
can also have various optional arguments; inthis case, we’ve set thedefault
value ofvotes
to 0.
Finally, note a relationship is defined, usingForeignKey
. That tells Django eachChoice
isrelated to a singleQuestion
. 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 (
CREATETABLE
statements) for this app. - Create a Python database-access API for accessing
Question
andChoice
objects.
But first we need to tell our project that thepolls
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 theINSTALLED_APPS
setting. ThePollsConfig
class is in thepolls/apps.py
file, so its dotted pathis'polls.apps.PollsConfig'
. Edit themysite/settings.py
file andadd that dotted path to theINSTALLED_APPS
setting. It’ll look likethis:
INSTALLED_APPS=['polls.apps.PollsConfig','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]
Now Django knows to include thepolls
app. Let’s run another command:
$python manage.py makemigrations polls
...\> py manage.py makemigrations polls
You should see something similar to the following:
Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question - Create model Choice
By runningmakemigrations
, 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 amigration.
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 filepolls/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 calledmigrate
, 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:
$python manage.py sqlmigrate polls0001
...\> py manage.py sqlmigrate polls 0001
You should see something similar to the following (we’ve reformatted it forreadability):
BEGIN;---- Create model Question--CREATETABLE"polls_question"("id"serialNOTNULLPRIMARYKEY,"question_text"varchar(200)NOTNULL,"pub_date"timestampwithtimezoneNOTNULL);---- Create model Choice--CREATETABLE"polls_choice"("id"serialNOTNULLPRIMARYKEY,"choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL,"question_id"integerNOTNULL);ALTERTABLE"polls_choice"ADDCONSTRAINT"polls_choice_question_id_c5b4b260_fk_polls_question_id"FOREIGNKEY("question_id")REFERENCES"polls_question"("id")DEFERRABLEINITIALLYDEFERRED;CREATEINDEX"polls_choice_question_id_c5b4b260"ON"polls_choice"("question_id");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
FOREIGNKEY
constraint. Don’t worry about theDEFERRABLE
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), orintegerprimarykeyautoincrement
(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 runpythonmanage.pycheck
; this checks for any problems inyour project without making migrations or touching the database.
Now, runmigrate
again to create those model tables in your database:
$python manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessionsRunning migrations: Rendering model states... DONE Applying polls.0001_initial... OK
...\> py manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessionsRunning migrations: Rendering model states... DONE Applying polls.0001_initial... OK
Themigrate
command takes all the migrations that haven’t beenapplied (Django tracks which ones are applied using a special table in yourdatabase calleddjango_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
pythonmanage.pymakemigrations
to createmigrations for those changes - Run
pythonmanage.pymigrate
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 thedjango-admin documentation for fullinformation on what themanage.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:
$python manage.py shell
...\> py manage.py shell
We’re using this instead of simply typing “python”, becausemanage.py
sets theDJANGO_SETTINGS_MODULE
environment variable, which givesDjango the Python import path to yourmysite/settings.py
file.
Once you’re in the shell, explore thedatabase API:
>>>frompolls.modelsimportChoice,Question# Import the model classes we just wrote.# No questions are in the system yet.>>>Question.objects.all()<QuerySet []># Create a new Question.# Support for time zones is enabled in the default settings file, so# Django expects a datetime with tzinfo for pub_date. Use timezone.now()# instead of datetime.datetime.now() and it will do the right thing.>>>fromdjango.utilsimporttimezone>>>q=Question(question_text="What's new?",pub_date=timezone.now())# Save the object into the database. You have to call save() explicitly.>>>q.save()# Now it has an ID.>>>q.id1# Access model field values via Python attributes.>>>q.question_text"What's new?">>>q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)# Change values by changing the attributes, then calling save().>>>q.question_text="What's up?">>>q.save()# objects.all() displays all the questions in the database.>>>Question.objects.all()<QuerySet [<Question: Question object (1)>]>
Wait a minute.<Question:Questionobject(1)>
isn’t a helpfulrepresentation of this object. Let’s fix that by editing theQuestion
model(in thepolls/models.py
file) and adding a__str__()
method to bothQuestion
andChoice
:
fromdjango.dbimportmodelsclassQuestion(models.Model):# ...def__str__(self):returnself.question_textclassChoice(models.Model):# ...def__str__(self):returnself.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.
Let’s also add a custom method to this model:
importdatetimefromdjango.dbimportmodelsfromdjango.utilsimporttimezoneclassQuestion(models.Model):# ...defwas_published_recently(self):returnself.pub_date>=timezone.now()-datetime.timedelta(days=1)
Note the addition ofimportdatetime
andfromdjango.utilsimporttimezone
, to reference Python’s standarddatetime
module and Django’stime-zone-related utilities indjango.utils.timezone
, respectively. Ifyou aren’t familiar with time zone handling in Python, you can learn more inthetime zone support docs.
Save these changes and start a new Python interactive shell by runningpythonmanage.pyshell
again:
>>>frompolls.modelsimportChoice,Question# Make sure our __str__() addition worked.>>>Question.objects.all()<QuerySet [<Question: What's up?>]># Django provides a rich database lookup API that's entirely driven by# keyword arguments.>>>Question.objects.filter(id=1)<QuerySet [<Question: What's up?>]>>>>Question.objects.filter(question_text__startswith='What')<QuerySet [<Question: What's up?>]># Get the question that was published this year.>>>fromdjango.utilsimporttimezone>>>current_year=timezone.now().year>>>Question.objects.get(pub_date__year=current_year)<Question: What's up?># Request an ID that doesn't exist, this will raise an exception.>>>Question.objects.get(id=2)Traceback (most recent call last):...DoesNotExist:Question matching query does not exist.# Lookup by a primary key is the most common case, so Django provides a# shortcut for primary-key exact lookups.# The following is identical to Question.objects.get(id=1).>>>Question.objects.get(pk=1)<Question: What's up?># Make sure our custom method worked.>>>q=Question.objects.get(pk=1)>>>q.was_published_recently()True# Give the Question a couple of Choices. The create call constructs a new# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates# a set to hold the "other side" of a ForeignKey relation# (e.g. a question's choice) which can be accessed via the API.>>>q=Question.objects.get(pk=1)# Display any choices from the related object set -- none so far.>>>q.choice_set.all()<QuerySet []># Create three choices.>>>q.choice_set.create(choice_text='Not much',votes=0)<Choice: Not much>>>>q.choice_set.create(choice_text='The sky',votes=0)<Choice: The sky>>>>c=q.choice_set.create(choice_text='Just hacking again',votes=0)# Choice objects have API access to their related Question objects.>>>c.question<Question: What's up?># And vice versa: Question objects get access to Choice objects.>>>q.choice_set.all()<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>>>>q.choice_set.count()3# The API automatically follows relationships as far as you need.# Use double underscores to separate relationships.# This works as many levels deep as you want; there's no limit.# Find all Choices for any question whose pub_date is in this year# (reusing the 'current_year' variable we created above).>>>Choice.objects.filter(question__pub_date__year=current_year)<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]># Let's delete one of the choices. Use delete() for that.>>>c=q.choice_set.filter(choice_text__startswith='Just hacking')>>>c.delete()
For more information on model relations, seeAccessing related objects. For more on how to use double underscores to performfield lookups via the API, seeField lookups. Forfull details on the database API, see ourDatabase 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:
$python manage.py createsuperuser
...\> py manage.py createsuperuser
Enter your desired username and press enter.
Username: admin
You will then be prompted for your desired email address:
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.
Password: **********Password (again): *********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:
$python manage.py runserver
...\> 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:

Sincetranslation is turned on by default, ifyou setLANGUAGE_CODE
, the login screen will be displayed in thegiven language (if Django has appropriate translations).
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:

You should see a few types of editable content: groups and users. They areprovided bydjango.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 thatQuestion
objectshave an admin interface. To do this, open thepolls/admin.py
file, andedit it to look like this:
fromdjango.contribimportadminfrom.modelsimportQuestionadmin.site.register(Question)
Explore the free admin functionality¶
Now that we’ve registeredQuestion
, Django knows that it should be displayed onthe admin index page:

Click “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:

Click the “What’s up?” question to edit it:

Things 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 inTutorial 1, it probablymeans you forgot to set the correct value for theTIME_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:

When you’re comfortable with the models API and have familiarized yourself withthe admin site, readpart 3 of this tutorial to learnabout how to add more views to our polls app.