| 1 |
===================================== |
| 2 |
Writing your first Django app, part 2 |
| 3 |
===================================== |
| 4 |
|
| 5 |
This tutorial begins where :doc:`Tutorial 1 </intro/tutorial01>` left off. |
| 6 |
We'll set up the database, create your first model, and get a quick |
| 7 |
introduction to Django's automatically-generated admin site. |
| 8 |
|
| 9 |
.. admonition:: Where to get help: |
| 10 |
|
| 11 |
If you're having trouble going through this tutorial, please head over to |
| 12 |
the :doc:`Getting Help</faq/help>` section of the FAQ. |
| 13 |
|
| 14 |
Database setup |
| 15 |
============== |
| 16 |
|
| 17 |
Now, open up :file:`mysite/settings.py`. It's a normal Python module with |
| 18 |
module-level variables representing Django settings. |
| 19 |
|
| 20 |
By default, the :setting:`DATABASES` configuration uses SQLite. If you're new |
| 21 |
to databases, or you're just interested in trying Django, this is the easiest |
| 22 |
choice. SQLite is included in Python, so you won't need to install anything |
| 23 |
else to support your database. When starting your first real project, however, |
| 24 |
you may want to use a more scalable database like PostgreSQL, to avoid |
| 25 |
database-switching headaches down the road. |
| 26 |
|
| 27 |
If you wish to use another database, see :ref:`details to customize and get |
| 28 |
your database running <database-installation>`. |
| 29 |
|
| 30 |
While you're editing :file:`mysite/settings.py`, set :setting:`TIME_ZONE` to |
| 31 |
your time zone. |
| 32 |
|
| 33 |
Also, note the :setting:`INSTALLED_APPS` setting at the top of the file. That |
| 34 |
holds the names of all Django applications that are activated in this Django |
| 35 |
instance. Apps can be used in multiple projects, and you can package and |
| 36 |
distribute them for use by others in their projects. |
| 37 |
|
| 38 |
By default, :setting:`INSTALLED_APPS` contains the following apps, all of which |
| 39 |
come with Django: |
| 40 |
|
| 41 |
* :mod:`django.contrib.admin` -- The admin site. You'll use it shortly. |
| 42 |
|
| 43 |
* :mod:`django.contrib.auth` -- An authentication system. |
| 44 |
|
| 45 |
* :mod:`django.contrib.contenttypes` -- A framework for content types. |
| 46 |
|
| 47 |
* :mod:`django.contrib.sessions` -- A session framework. |
| 48 |
|
| 49 |
* :mod:`django.contrib.messages` -- A messaging framework. |
| 50 |
|
| 51 |
* :mod:`django.contrib.staticfiles` -- A framework for managing |
| 52 |
static files. |
| 53 |
|
| 54 |
These applications are included by default as a convenience for the common case. |
| 55 |
|
| 56 |
Some of these applications make use of at least one database table, though, |
| 57 |
so we need to create the tables in the database before we can use them. To do |
| 58 |
that, run the following command: |
| 59 |
|
| 60 |
.. console:: |
| 61 |
|
| 62 |
$ python manage.py migrate |
| 63 |
|
| 64 |
The :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting |
| 65 |
and creates any necessary database tables according to the database settings |
| 66 |
in your :file:`mysite/settings.py` file and the database migrations shipped |
| 67 |
with the app (we'll cover those later). You'll see a message for each |
| 68 |
migration it applies. If you're interested, run the command-line client for your |
| 69 |
database and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL), |
| 70 |
``.tables`` (SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to |
| 71 |
display the tables Django created. |
| 72 |
|
| 73 |
.. admonition:: For the minimalists |
| 74 |
|
| 75 |
Like we said above, the default applications are included for the common |
| 76 |
case, but not everybody needs them. If you don't need any or all of them, |
| 77 |
feel free to comment-out or delete the appropriate line(s) from |
| 78 |
:setting:`INSTALLED_APPS` before running :djadmin:`migrate`. The |
| 79 |
:djadmin:`migrate` command will only run migrations for apps in |
| 80 |
:setting:`INSTALLED_APPS`. |
| 81 |
|
| 82 |
.. _creating-models: |
| 83 |
|
| 84 |
Creating models |
| 85 |
=============== |
| 86 |
|
| 87 |
Now we'll define your models -- essentially, your database layout, with |
| 88 |
additional metadata. |
| 89 |
|
| 90 |
.. admonition:: Philosophy |
| 91 |
|
| 92 |
A model is the single, definitive source of information about your data. It |
| 93 |
contains the essential fields and behaviors of the data you're storing. |
| 94 |
Django follows the :ref:`DRY Principle <dry>`. The goal is to define your |
| 95 |
data model in one place and automatically derive things from it. |
| 96 |
|
| 97 |
This includes the migrations - unlike in Ruby On Rails, for example, migrations |
| 98 |
are entirely derived from your models file, and are essentially a |
| 99 |
history that Django can roll through to update your database schema to |
| 100 |
match your current models. |
| 101 |
|
| 102 |
In our poll app, we'll create two models: ``Question`` and ``Choice``. A |
| 103 |
``Question`` has a question and a publication date. A ``Choice`` has two |
| 104 |
fields: the text of the choice and a vote tally. Each ``Choice`` is associated |
| 105 |
with a ``Question``. |
| 106 |
|
| 107 |
These concepts are represented by Python classes. Edit the |
| 108 |
:file:`polls/models.py` file so it looks like this: |
| 109 |
|
| 110 |
.. code-block:: python |
| 111 |
:caption: ``polls/models.py`` |
| 112 |
|
| 113 |
from django.db import models |
| 114 |
|
| 115 |
|
| 116 |
class Question(models.Model): |
| 117 |
question_text = models.CharField(max_length=200) |
| 118 |
pub_date = models.DateTimeField("date published") |
| 119 |
|
| 120 |
|
| 121 |
class Choice(models.Model): |
| 122 |
question = models.ForeignKey(Question, on_delete=models.CASCADE) |
| 123 |
choice_text = models.CharField(max_length=200) |
| 124 |
votes = models.IntegerField(default=0) |
| 125 |
|
| 126 |
Here, each model is represented by a class that subclasses |
| 127 |
:class:`django.db.models.Model`. Each model has a number of class variables, |
| 128 |
each of which represents a database field in the model. |
| 129 |
|
| 130 |
Each field is represented by an instance of a :class:`~django.db.models.Field` |
| 131 |
class -- e.g., :class:`~django.db.models.CharField` for character fields and |
| 132 |
:class:`~django.db.models.DateTimeField` for datetimes. This tells Django what |
| 133 |
type of data each field holds. |
| 134 |
|
| 135 |
The name of each :class:`~django.db.models.Field` instance (e.g. |
| 136 |
``question_text`` or ``pub_date``) is the field's name, in machine-friendly |
| 137 |
format. You'll use this value in your Python code, and your database will use |
| 138 |
it as the column name. |
| 139 |
|
| 140 |
You can use an optional first positional argument to a |
| 141 |
:class:`~django.db.models.Field` to designate a human-readable name. That's used |
| 142 |
in a couple of introspective parts of Django, and it doubles as documentation. |
| 143 |
If this field isn't provided, Django will use the machine-readable name. In this |
| 144 |
example, we've only defined a human-readable name for ``Question.pub_date``. |
| 145 |
For all other fields in this model, the field's machine-readable name will |
| 146 |
suffice as its human-readable name. |
| 147 |
|
| 148 |
Some :class:`~django.db.models.Field` classes have required arguments. |
| 149 |
:class:`~django.db.models.CharField`, for example, requires that you give it a |
| 150 |
:attr:`~django.db.models.CharField.max_length`. That's used not only in the |
| 151 |
database schema, but in validation, as we'll soon see. |
| 152 |
|
| 153 |
A :class:`~django.db.models.Field` can also have various optional arguments; in |
| 154 |
this case, we've set the :attr:`~django.db.models.Field.default` value of |
| 155 |
``votes`` to 0. |
| 156 |
|
| 157 |
Finally, note a relationship is defined, using |
| 158 |
:class:`~django.db.models.ForeignKey`. That tells Django each ``Choice`` is |
| 159 |
related to a single ``Question``. Django supports all the common database |
| 160 |
relationships: many-to-one, many-to-many, and one-to-one. |
| 161 |
|
| 162 |
Activating models |
| 163 |
================= |
| 164 |
|
| 165 |
That small bit of model code gives Django a lot of information. With it, Django |
| 166 |
is able to: |
| 167 |
|
| 168 |
* Create a database schema (``CREATE TABLE`` statements) for this app. |
| 169 |
* Create a Python database-access API for accessing ``Question`` and ``Choice`` objects. |
| 170 |
|
| 171 |
But first we need to tell our project that the ``polls`` app is installed. |
| 172 |
|
| 173 |
.. admonition:: Philosophy |
| 174 |
|
| 175 |
Django apps are "pluggable": You can use an app in multiple projects, and |
| 176 |
you can distribute apps, because they don't have to be tied to a given |
| 177 |
Django installation. |
| 178 |
|
| 179 |
To include the app in our project, we need to add a reference to its |
| 180 |
configuration class in the :setting:`INSTALLED_APPS` setting. The |
| 181 |
``PollsConfig`` class is in the :file:`polls/apps.py` file, so its dotted path |
| 182 |
is ``'polls.apps.PollsConfig'``. Edit the :file:`mysite/settings.py` file and |
| 183 |
add that dotted path to the :setting:`INSTALLED_APPS` setting. It'll look like |
| 184 |
this: |
| 185 |
|
| 186 |
.. code-block:: python |
| 187 |
:caption: ``mysite/settings.py`` |
| 188 |
|
| 189 |
INSTALLED_APPS = [ |
| 190 |
"polls.apps.PollsConfig", |
| 191 |
"django.contrib.admin", |
| 192 |
"django.contrib.auth", |
| 193 |
"django.contrib.contenttypes", |
| 194 |
"django.contrib.sessions", |
| 195 |
"django.contrib.messages", |
| 196 |
"django.contrib.staticfiles", |
| 197 |
] |
| 198 |
|
| 199 |
Now Django knows to include the ``polls`` app. Let's run another command: |
| 200 |
|
| 201 |
.. console:: |
| 202 |
|
| 203 |
$ python manage.py makemigrations polls |
| 204 |
|
| 205 |
You should see something similar to the following: |
| 206 |
|
| 207 |
.. code-block:: text |
| 208 |
|
| 209 |
Migrations for 'polls': |
| 210 |
polls/migrations/0001_initial.py |
| 211 |
+ Create model Question |
| 212 |
+ Create model Choice |
| 213 |
|
| 214 |
By running ``makemigrations``, you're telling Django that you've made |
| 215 |
some changes to your models (in this case, you've made new ones) and that |
| 216 |
you'd like the changes to be stored as a *migration*. |
| 217 |
|
| 218 |
Migrations are how Django stores changes to your models (and thus your |
| 219 |
database schema) - they're files on disk. You can read the migration for your |
| 220 |
new model if you like; it's the file ``polls/migrations/0001_initial.py``. |
| 221 |
Don't worry, you're not expected to read them every time Django makes one, but |
| 222 |
they're designed to be human-editable in case you want to manually tweak how |
| 223 |
Django changes things. |
| 224 |
|
| 225 |
There's a command that will run the migrations for you and manage your database |
| 226 |
schema automatically - that's called :djadmin:`migrate`, and we'll come to it in a |
| 227 |
moment - but first, let's see what SQL that migration would run. The |
| 228 |
:djadmin:`sqlmigrate` command takes migration names and returns their SQL: |
| 229 |
|
| 230 |
.. console:: |
| 231 |
|
| 232 |
$ python manage.py sqlmigrate polls 0001 |
| 233 |
|
| 234 |
You should see something similar to the following (we've reformatted it for |
| 235 |
readability): |
| 236 |
|
| 237 |
.. code-block:: sql |
| 238 |
|
| 239 |
BEGIN; |
| 240 |
-- |
| 241 |
-- Create model Question |
| 242 |
-- |
| 243 |
CREATE TABLE "polls_question" ( |
| 244 |
"id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, |
| 245 |
"question_text" varchar(200) NOT NULL, |
| 246 |
"pub_date" timestamp with time zone NOT NULL |
| 247 |
); |
| 248 |
-- |
| 249 |
-- Create model Choice |
| 250 |
-- |
| 251 |
CREATE TABLE "polls_choice" ( |
| 252 |
"id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, |
| 253 |
"choice_text" varchar(200) NOT NULL, |
| 254 |
"votes" integer NOT NULL, |
| 255 |
"question_id" bigint NOT NULL |
| 256 |
); |
| 257 |
ALTER TABLE "polls_choice" |
| 258 |
ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id" |
| 259 |
FOREIGN KEY ("question_id") |
| 260 |
REFERENCES "polls_question" ("id") |
| 261 |
DEFERRABLE INITIALLY DEFERRED; |
| 262 |
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id"); |
| 263 |
|
| 264 |
COMMIT; |
| 265 |
|
| 266 |
Note the following: |
| 267 |
|
| 268 |
* The exact output will vary depending on the database you are using. The |
| 269 |
example above is generated for PostgreSQL. |
| 270 |
|
| 271 |
* Table names are automatically generated by combining the name of the app |
| 272 |
(``polls``) and the lowercase name of the model -- ``question`` and |
| 273 |
``choice``. (You can override this behavior.) |
| 274 |
|
| 275 |
* Primary keys (IDs) are added automatically. (You can override this, too.) |
| 276 |
|
| 277 |
* By convention, Django appends ``"_id"`` to the foreign key field name. |
| 278 |
(Yes, you can override this, as well.) |
| 279 |
|
| 280 |
* The foreign key relationship is made explicit by a ``FOREIGN KEY`` |
| 281 |
constraint. Don't worry about the ``DEFERRABLE`` parts; it's telling |
| 282 |
PostgreSQL to not enforce the foreign key until the end of the transaction. |
| 283 |
|
| 284 |
* It's tailored to the database you're using, so database-specific field types |
| 285 |
such as ``auto_increment`` (MySQL), ``bigint PRIMARY KEY GENERATED BY DEFAULT |
| 286 |
AS IDENTITY`` (PostgreSQL), or ``integer primary key autoincrement`` (SQLite) |
| 287 |
are handled for you automatically. Same goes for the quoting of field names |
| 288 |
-- e.g., using double quotes or single quotes. |
| 289 |
|
| 290 |
* The :djadmin:`sqlmigrate` command doesn't actually run the migration on your |
| 291 |
database - instead, it prints it to the screen so that you can see what SQL |
| 292 |
Django thinks is required. It's useful for checking what Django is going to |
| 293 |
do or if you have database administrators who require SQL scripts for |
| 294 |
changes. |
| 295 |
|
| 296 |
If you're interested, you can also run |
| 297 |
:djadmin:`python manage.py check <check>`; this checks for any problems in |
| 298 |
your project without making migrations or touching the database. |
| 299 |
|
| 300 |
Now, run :djadmin:`migrate` again to create those model tables in your database: |
| 301 |
|
| 302 |
.. console:: |
| 303 |
|
| 304 |
$ python manage.py migrate |
| 305 |
Operations to perform: |
| 306 |
Apply all migrations: admin, auth, contenttypes, polls, sessions |
| 307 |
Running migrations: |
| 308 |
Rendering model states... DONE |
| 309 |
Applying polls.0001_initial... OK |
| 310 |
|
| 311 |
The :djadmin:`migrate` command takes all the migrations that haven't been |
| 312 |
applied (Django tracks which ones are applied using a special table in your |
| 313 |
database called ``django_migrations``) and runs them against your database - |
| 314 |
essentially, synchronizing the changes you made to your models with the schema |
| 315 |
in the database. |
| 316 |
|
| 317 |
Migrations are very powerful and let you change your models over time, as you |
| 318 |
develop your project, without the need to delete your database or tables and |
| 319 |
make new ones - it specializes in upgrading your database live, without |
| 320 |
losing data. We'll cover them in more depth in a later part of the tutorial, |
| 321 |
but for now, remember the three-step guide to making model changes: |
| 322 |
|
| 323 |
* Change your models (in ``models.py``). |
| 324 |
* Run :djadmin:`python manage.py makemigrations <makemigrations>` to create |
| 325 |
migrations for those changes |
| 326 |
* Run :djadmin:`python manage.py migrate <migrate>` to apply those changes to |
| 327 |
the database. |
| 328 |
|
| 329 |
The reason that there are separate commands to make and apply migrations is |
| 330 |
because you'll commit migrations to your version control system and ship them |
| 331 |
with your app; they not only make your development easier, they're also |
| 332 |
usable by other developers and in production. |
| 333 |
|
| 334 |
Read the :doc:`django-admin documentation </ref/django-admin>` for full |
| 335 |
information on what the ``manage.py`` utility can do. |
| 336 |
|
| 337 |
Playing with the API |
| 338 |
==================== |
| 339 |
|
| 340 |
Now, let's hop into the interactive Python shell and play around with the free |
| 341 |
API Django gives you. To invoke the Python shell, use this command: |
| 342 |
|
| 343 |
.. console:: |
| 344 |
|
| 345 |
$ python manage.py shell |
| 346 |
|
| 347 |
We're using this instead of simply typing "python", because :file:`manage.py` |
| 348 |
sets the :envvar:`DJANGO_SETTINGS_MODULE` environment variable, which gives |
| 349 |
Django the Python import path to your :file:`mysite/settings.py` file. |
| 350 |
By default, the :djadmin:`shell` command automatically imports the models from |
| 351 |
your :setting:`INSTALLED_APPS`. |
| 352 |
|
| 353 |
Once you're in the shell, explore the :doc:`database API </topics/db/queries>`: |
| 354 |
|
| 355 |
.. code-block:: pycon |
| 356 |
|
| 357 |
# No questions are in the system yet. |
| 358 |
>>> Question.objects.all() |
| 359 |
<QuerySet []> |
| 360 |
|
| 361 |
# Create a new Question. |
| 362 |
# Support for time zones is enabled in the default settings file, so |
| 363 |
# Django expects a datetime with tzinfo for pub_date. Use timezone.now() |
| 364 |
# instead of datetime.datetime.now() and it will do the right thing. |
| 365 |
>>> from django.utils import timezone |
| 366 |
>>> q = Question(question_text="What's new?", pub_date=timezone.now()) |
| 367 |
|
| 368 |
# Save the object into the database. You have to call save() explicitly. |
| 369 |
>>> q.save() |
| 370 |
|
| 371 |
# Now it has an ID. |
| 372 |
>>> q.id |
| 373 |
1 |
| 374 |
|
| 375 |
# Access model field values via Python attributes. |
| 376 |
>>> q.question_text |
| 377 |
"What's new?" |
| 378 |
>>> q.pub_date |
| 379 |
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=datetime.timezone.utc) |
| 380 |
|
| 381 |
# Change values by changing the attributes, then calling save(). |
| 382 |
>>> q.question_text = "What's up?" |
| 383 |
>>> q.save() |
| 384 |
|
| 385 |
# objects.all() displays all the questions in the database. |
| 386 |
>>> Question.objects.all() |
| 387 |
<QuerySet [<Question: Question object (1)>]> |
| 388 |
|
| 389 |
Wait a minute. ``<Question: Question object (1)>`` isn't a helpful |
| 390 |
representation of this object. Let's fix that by editing the ``Question`` model |
| 391 |
(in the ``polls/models.py`` file) and adding a |
| 392 |
:meth:`~django.db.models.Model.__str__` method to both ``Question`` and |
| 393 |
``Choice``: |
| 394 |
|
| 395 |
.. code-block:: python |
| 396 |
:caption: ``polls/models.py`` |
| 397 |
|
| 398 |
from django.db import models |
| 399 |
|
| 400 |
|
| 401 |
class Question(models.Model): |
| 402 |
# ... |
| 403 |
def __str__(self): |
| 404 |
return self.question_text |
| 405 |
|
| 406 |
|
| 407 |
class Choice(models.Model): |
| 408 |
# ... |
| 409 |
def __str__(self): |
| 410 |
return self.choice_text |
| 411 |
|
| 412 |
It's important to add :meth:`~django.db.models.Model.__str__` methods to your |
| 413 |
models, not only for your own convenience when dealing with the interactive |
| 414 |
prompt, but also because objects' representations are used throughout Django's |
| 415 |
automatically-generated admin. |
| 416 |
|
| 417 |
.. _tutorial02-import-timezone: |
| 418 |
|
| 419 |
Let's also add a custom method to this model: |
| 420 |
|
| 421 |
.. code-block:: python |
| 422 |
:caption: ``polls/models.py`` |
| 423 |
|
| 424 |
import datetime |
| 425 |
|
| 426 |
from django.db import models |
| 427 |
from django.utils import timezone |
| 428 |
|
| 429 |
|
| 430 |
class Question(models.Model): |
| 431 |
# ... |
| 432 |
def was_published_recently(self): |
| 433 |
return self.pub_date >= timezone.now() - datetime.timedelta(days=1) |
| 434 |
|
| 435 |
Note the addition of ``import datetime`` and ``from django.utils import |
| 436 |
timezone``, to reference Python's standard :mod:`datetime` module and Django's |
| 437 |
time-zone-related utilities in :mod:`django.utils.timezone`, respectively. If |
| 438 |
you aren't familiar with time zone handling in Python, you can learn more in |
| 439 |
the :doc:`time zone support docs </topics/i18n/timezones>`. |
| 440 |
|
| 441 |
Save these changes and start a new Python interactive shell. (If a |
| 442 |
three-chevron prompt (>>>) indicates you are still in the shell, you need to |
| 443 |
exit first using ``exit()``). Run ``python manage.py shell`` again to reload |
| 444 |
the models. |
| 445 |
|
| 446 |
.. RemovedInDjango70Warning: When Python 3.12 is no longer supported, |
| 447 |
``exit()`` can be replaced with ``exit``. |
| 448 |
|
| 449 |
.. code-block:: pycon |
| 450 |
|
| 451 |
# Make sure our __str__() addition worked. |
| 452 |
>>> Question.objects.all() |
| 453 |
<QuerySet [<Question: What's up?>]> |
| 454 |
|
| 455 |
# Django provides a rich database lookup API that's entirely driven by |
| 456 |
# keyword arguments. |
| 457 |
>>> Question.objects.filter(id=1) |
| 458 |
<QuerySet [<Question: What's up?>]> |
| 459 |
>>> Question.objects.filter(question_text__startswith="What") |
| 460 |
<QuerySet [<Question: What's up?>]> |
| 461 |
|
| 462 |
# Get the question that was published this year. |
| 463 |
>>> from django.utils import timezone |
| 464 |
>>> current_year = timezone.now().year |
| 465 |
>>> Question.objects.get(pub_date__year=current_year) |
| 466 |
<Question: What's up?> |
| 467 |
|
| 468 |
# Request an ID that doesn't exist, this will raise an exception. |
| 469 |
>>> Question.objects.get(id=2) |
| 470 |
Traceback (most recent call last): |
| 471 |
... |
| 472 |
DoesNotExist: Question matching query does not exist. |
| 473 |
|
| 474 |
# Lookup by a primary key is the most common case, so Django provides a |
| 475 |
# shortcut for primary-key exact lookups. |
| 476 |
# The following is identical to Question.objects.get(id=1). |
| 477 |
>>> Question.objects.get(pk=1) |
| 478 |
<Question: What's up?> |
| 479 |
|
| 480 |
# Make sure our custom method worked. |
| 481 |
>>> q = Question.objects.get(pk=1) |
| 482 |
>>> q.was_published_recently() |
| 483 |
True |
| 484 |
|
| 485 |
# Give the Question a couple of Choices. The create call constructs a new |
| 486 |
# Choice object, does the INSERT statement, adds the choice to the set |
| 487 |
# of available choices and returns the new Choice object. Django creates |
| 488 |
# a set (defined as "choice_set") to hold the "other side" of a ForeignKey |
| 489 |
# relation (e.g. a question's choice) which can be accessed via the API. |
| 490 |
>>> q = Question.objects.get(pk=1) |
| 491 |
|
| 492 |
# Display any choices from the related object set -- none so far. |
| 493 |
>>> q.choice_set.all() |
| 494 |
<QuerySet []> |
| 495 |
|
| 496 |
# Create three choices. |
| 497 |
>>> q.choice_set.create(choice_text="Not much", votes=0) |
| 498 |
<Choice: Not much> |
| 499 |
>>> q.choice_set.create(choice_text="The sky", votes=0) |
| 500 |
<Choice: The sky> |
| 501 |
>>> c = q.choice_set.create(choice_text="Just hacking again", votes=0) |
| 502 |
|
| 503 |
# Choice objects have API access to their related Question objects. |
| 504 |
>>> c.question |
| 505 |
<Question: What's up?> |
| 506 |
|
| 507 |
# And vice versa: Question objects get access to Choice objects. |
| 508 |
>>> q.choice_set.all() |
| 509 |
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]> |
| 510 |
>>> q.choice_set.count() |
| 511 |
3 |
| 512 |
|
| 513 |
# The API automatically follows relationships as far as you need. |
| 514 |
# Use double underscores to separate relationships. |
| 515 |
# This works as many levels deep as you want; there's no limit. |
| 516 |
# Find all Choices for any question whose pub_date is in this year |
| 517 |
# (reusing the 'current_year' variable we created above). |
| 518 |
>>> Choice.objects.filter(question__pub_date__year=current_year) |
| 519 |
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]> |
| 520 |
|
| 521 |
# Let's delete one of the choices. Use delete() for that. |
| 522 |
>>> c = q.choice_set.filter(choice_text__startswith="Just hacking") |
| 523 |
>>> c.delete() |
| 524 |
|
| 525 |
For more information on model relations, see :doc:`Accessing related objects |
| 526 |
</ref/models/relations>`. For more on how to use double underscores to perform |
| 527 |
field lookups via the API, see :ref:`Field lookups <field-lookups-intro>`. For |
| 528 |
full details on the database API, see our :doc:`Database API reference |
| 529 |
</topics/db/queries>`. |
| 530 |
|
| 531 |
Introducing the Django Admin |
| 532 |
============================ |
| 533 |
|
| 534 |
.. admonition:: Philosophy |
| 535 |
|
| 536 |
Generating admin sites for your staff or clients to add, change, and delete |
| 537 |
content is tedious work that doesn't require much creativity. For that |
| 538 |
reason, Django entirely automates creation of admin interfaces for models. |
| 539 |
|
| 540 |
Django was written in a newsroom environment, with a very clear separation |
| 541 |
between "content publishers" and the "public" site. Site managers use the |
| 542 |
system to add news stories, events, sports scores, etc., and that content is |
| 543 |
displayed on the public site. Django solves the problem of creating a |
| 544 |
unified interface for site administrators to edit content. |
| 545 |
|
| 546 |
The admin isn't intended to be used by site visitors. It's for site |
| 547 |
managers. |
| 548 |
|
| 549 |
Creating an admin user |
| 550 |
---------------------- |
| 551 |
|
| 552 |
First we'll need to create a user who can login to the admin site. Run the |
| 553 |
following command: |
| 554 |
|
| 555 |
.. console:: |
| 556 |
|
| 557 |
$ python manage.py createsuperuser |
| 558 |
|
| 559 |
Enter your desired username and press enter. |
| 560 |
|
| 561 |
.. code-block:: text |
| 562 |
|
| 563 |
Username: admin |
| 564 |
|
| 565 |
You will then be prompted for your desired email address: |
| 566 |
|
| 567 |
.. code-block:: text |
| 568 |
|
| 569 |
Email address: [email protected] |
| 570 |
|
| 571 |
The final step is to enter your password. You will be asked to enter your |
| 572 |
password twice, the second time as a confirmation of the first. |
| 573 |
|
| 574 |
.. code-block:: text |
| 575 |
|
| 576 |
Password: ********** |
| 577 |
Password (again): ********* |
| 578 |
Superuser created successfully. |
| 579 |
|
| 580 |
Start the development server |
| 581 |
---------------------------- |
| 582 |
|
| 583 |
The Django admin site is activated by default. Let's start the development |
| 584 |
server and explore it. |
| 585 |
|
| 586 |
If the server is not running start it like so: |
| 587 |
|
| 588 |
.. console:: |
| 589 |
|
| 590 |
$ python manage.py runserver |
| 591 |
|
| 592 |
Now, open a web browser and go to "/admin/" on your local domain -- e.g., |
| 593 |
http://127.0.0.1:8000/admin/. You should see the admin's login screen: |
| 594 |
|
| 595 |
.. image:: _images/admin01.png |
| 596 |
:alt: Django admin login screen |
| 597 |
|
| 598 |
Since :doc:`translation </topics/i18n/translation>` is turned on by default, if |
| 599 |
you set :setting:`LANGUAGE_CODE`, the login screen will be displayed in the |
| 600 |
given language (if Django has appropriate translations). |
| 601 |
|
| 602 |
Enter the admin site |
| 603 |
-------------------- |
| 604 |
|
| 605 |
Now, try logging in with the superuser account you created in the previous step. |
| 606 |
You should see the Django admin index page: |
| 607 |
|
| 608 |
.. image:: _images/admin02.png |
| 609 |
:alt: Django admin index page |
| 610 |
|
| 611 |
You should see a few types of editable content: groups and users. They are |
| 612 |
provided by :mod:`django.contrib.auth`, the authentication framework shipped |
| 613 |
by Django. |
| 614 |
|
| 615 |
Make the poll app modifiable in the admin |
| 616 |
----------------------------------------- |
| 617 |
|
| 618 |
But where's our poll app? It's not displayed on the admin index page. |
| 619 |
|
| 620 |
Only one more thing to do: we need to tell the admin that ``Question`` objects |
| 621 |
have an admin interface. To do this, open the :file:`polls/admin.py` file, and |
| 622 |
edit it to look like this: |
| 623 |
|
| 624 |
.. code-block:: python |
| 625 |
:caption: ``polls/admin.py`` |
| 626 |
|
| 627 |
from django.contrib import admin |
| 628 |
|
| 629 |
from .models import Question |
| 630 |
|
| 631 |
admin.site.register(Question) |
| 632 |
|
| 633 |
Explore the free admin functionality |
| 634 |
------------------------------------ |
| 635 |
|
| 636 |
Now that we've registered ``Question``, Django knows that it should be displayed on |
| 637 |
the admin index page: |
| 638 |
|
| 639 |
.. image:: _images/admin03t.png |
| 640 |
:alt: Django admin index page, now with polls displayed |
| 641 |
|
| 642 |
Click "Questions". Now you're at the "change list" page for questions. This page |
| 643 |
displays all the questions in the database and lets you choose one to change it. |
| 644 |
There's the "What's up?" question we created earlier: |
| 645 |
|
| 646 |
.. image:: _images/admin04t.png |
| 647 |
:alt: Polls change list page |
| 648 |
|
| 649 |
Click the "What's up?" question to edit it: |
| 650 |
|
| 651 |
.. image:: _images/admin05t.png |
| 652 |
:alt: Editing form for question object |
| 653 |
|
| 654 |
Things to note here: |
| 655 |
|
| 656 |
* The form is automatically generated from the ``Question`` model. |
| 657 |
|
| 658 |
* The different model field types (:class:`~django.db.models.DateTimeField`, |
| 659 |
:class:`~django.db.models.CharField`) correspond to the appropriate HTML |
| 660 |
input widget. Each type of field knows how to display itself in the Django |
| 661 |
admin. |
| 662 |
|
| 663 |
* Each :class:`~django.db.models.DateTimeField` gets free JavaScript |
| 664 |
shortcuts. Dates get a "Today" shortcut and calendar popup, and times get |
| 665 |
a "Now" shortcut and a convenient popup that lists commonly entered times. |
| 666 |
|
| 667 |
The bottom part of the page gives you a couple of options: |
| 668 |
|
| 669 |
* Save -- Saves changes and returns to the change-list page for this type of |
| 670 |
object. |
| 671 |
|
| 672 |
* Save and continue editing -- Saves changes and reloads the admin page for |
| 673 |
this object. |
| 674 |
|
| 675 |
* Save and add another -- Saves changes and loads a new, blank form for this |
| 676 |
type of object. |
| 677 |
|
| 678 |
* Delete -- Displays a delete confirmation page. |
| 679 |
|
| 680 |
If the value of "Date published" doesn't match the time when you created the |
| 681 |
question in :doc:`Tutorial 1</intro/tutorial01>`, it probably |
| 682 |
means you forgot to set the correct value for the :setting:`TIME_ZONE` setting. |
| 683 |
Change it, reload the page and check that the correct value appears. |
| 684 |
|
| 685 |
Change the "Date published" by clicking the "Today" and "Now" shortcuts. Then |
| 686 |
click "Save and continue editing." Then click "History" in the upper right. |
| 687 |
You'll see a page listing all changes made to this object via the Django admin, |
| 688 |
with the timestamp and username of the person who made the change: |
| 689 |
|
| 690 |
.. image:: _images/admin06t.png |
| 691 |
:alt: History page for question object |
| 692 |
|
| 693 |
When you're comfortable with the models API and have familiarized yourself with |
| 694 |
the admin site, read :doc:`part 3 of this tutorial</intro/tutorial03>` to learn |
| 695 |
about how to add more views to our polls app. |