Boston Python Workshop/Saturday/Web app project: Difference between revisions

imported>Paulproteus
imported>Paulproteus
Line 149:
 
A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you're storing. Django follows the DRY ("Don't Repeat Yourself") Principle. The goal is to define your data model in one place and automatically derive things from it.
 
(If you've used SQL before, you might be interested to know that each Django ''model'' corresponds to a SQL ''table''.)
 
In our simple poll app, we'll create two models: polls and choices. A poll has a question and a publication date. A choice has two fields: the text of the choice and a vote tally. Each choice is associated with a poll. (FIXME: Add image to Choice.)
Line 171 ⟶ 173:
The name of each Field instance (e.g. question or pub_date ) is the field's name, in machine-friendly format. You'll use this value in your Python code, and your database will use it as the column name.
 
YouThe can''pub_date'' usefield anhas optionalsomething firstunique positionalabout argument toit: a human-readable name, "date published". One feature of Django Field toclasses designateis that if you pass in a human-readablefirst name.argument That'sfor usedmost fields, Django will use this in a couple of introspective parts of Django, and it doubles as documentation. If thisthe fieldhuman-readable isn't provided, Django will use the machine-readable name. In this example, we've only defined a human-readable name for Poll.pub_date. For all other fields in this model, the field's machine-readable name will suffice as its human-readable name.
 
Some Field classes have required elements. CharField, for example, requires that you give it a max_length. That's used not only in the database schema, but in validation, as we'll soon see.
 
Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Poll. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.
 
Activating models
=== Activating models ===
 
That small bit of model code gives Django a lot of information. With it, Django is able to:
 
* Create a database schema (CREATE TABLE statements) for this app.
* Create a Python database-access API for accessing Poll and Choice objects.
 
But first we need to tell our project that the polls app is installed.
 
=== Django Philosophy ===
 
Django apps are "pluggable": You can use an app in multiple projects, and you can distribute apps, because they don't have to be tied to a given Django installation.
Line 191 ⟶ 194:
Edit the settings.py file again, and change the INSTALLED_APPS setting to include the string 'polls'. So it'll look like this:
 
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'polls'
)
 
Now Django knows to include the polls app. Let's run another command:
 
If you care about SQL, you can try the following command:
python manage.py sql polls
 
* python manage.py sql polls
You should see something similar to the following (the CREATE TABLE SQL statements for the polls app):
 
For now, let's just Django's ''syncdb'' tool to create the database tables for Poll objects:
BEGIN;
CREATE TABLE "polls_poll" (
"id" serial NOT NULL PRIMARY KEY,
"question" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
);
CREATE TABLE "polls_choice" (
"id" serial NOT NULL PRIMARY KEY,
"poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
"choice" varchar(200) NOT NULL,
"votes" integer NOT NULL
);
COMMIT;
 
python manage.py syncdb
Note the following:
 
The syncdb looks for ''apps'' that have not yet been set up. To set them up, it runs the necessary SQL commands against your database. This creates all the tables, initial data and indexes for any apps you have added to your project since the last time you ran syncdb. syncdb can be called as often as you like, and it will only ever create the tables that don't exist.
The exact output will vary depending on the database you are using.
Table names are automatically generated by combining the name of the app (polls) and the lowercase name of the model -- poll and choice. (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 REFERENCES statement.
It's tailored to the database you're using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), or integer primary key (SQLite) are handled for you automatically. Same goes for quoting of field names -- e.g., using double quotes or single quotes. The author of this tutorial runs PostgreSQL, so the example output is in PostgreSQL syntax.
The sql command doesn't actually run the SQL in your database - it just prints it to the screen so that you can see what SQL Django thinks is required. If you wanted to, you could copy and paste this SQL into your database prompt. However, as we will see shortly, Django provides an easier way of committing the SQL to the database.
 
Read the django-admin.py documentation for full information on what the manage.py utility can do.
If you're interested, also run the following commands:
 
=== Playing with the database ===
python manage.py validate -- Checks for any errors in the construction of your models.
python manage.py sqlcustom polls -- Outputs any custom SQL statements (such as table modifications or constraints) that are defined for the application.
python manage.py sqlclear polls -- Outputs the necessary DROP TABLE statements for this app, according to which tables already exist in your database (if any).
python manage.py sqlindexes polls -- Outputs the CREATE INDEX statements for this app.
python manage.py sqlall polls -- A combination of all the SQL from the sql, sqlcustom, and sqlindexes commands.
 
During Friday setup, you installed SQLite Manager into your system's Firefox. Now's a good time to open it up.
Looking at the output of those commands can help you understand what's actually happening under the hood.
 
* FIXME
Now, run syncdb again to create those model tables in your database:
 
=== Playing with the API ===
python manage.py syncdb
 
The syncdb command runs the sql from 'sqlall' on your database for all apps in INSTALLED_APPS that don't already exist in your database. This creates all the tables, initial data and indexes for any apps you have added to your project since the last time you ran syncdb. syncdb can be called as often as you like, and it will only ever create the tables that don't exist.
 
Read the django-admin.py documentation for full information 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 free API Django gives you. To invoke the Python shell, use this command:
 
python manage.py shell
 
We're using this instead of simply typing "python", because manage.py sets up the project's environment for you. "Setting up the environment" involves two things:
Line 260 ⟶ 236:
Setting the DJANGO_SETTINGS_MODULE environment variable, which gives Django the path to your settings.py file.
 
Once you're in the shell, explore the database API:
Bypassing manage.py
 
Let's import the model classes we just wrote:
If you'd rather not use manage.py, no problem. Just make sure mysite and polls are at the root level on the Python path (i.e., import mysite and import polls work) and set the DJANGO_SETTINGS_MODULE environment variable to mysite.settings.
 
>>> from polls.models import Poll, Choice
For more information on all of this, see the django-admin.py documentation.
 
To list all the current Polls:
Once you're in the shell, explore the database API:
 
>>> Poll.objects.all()
>>> from polls.models import Poll, Choice # Import the model classes we just wrote.
[]
 
It is an empty list because there are no polls. Let's add one!
# No polls are in the system yet.
>>> Poll.objects.all()
[]
 
>>> import datetime
# Create a new Poll.
>>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
>>> import datetime
>>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
 
#Then Savewe'll save the object into the database. You have to call save() explicitly.
>>> p.save()
 
>>> p.save()
# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> p.id
1
 
Great. Now, because it's been saved, it has an ID in the database. You can see that by typing this into the Python shell:
# Access database columns via Python attributes.
>>> p.question
"What's up?"
>>> p.pub_date
datetime.datetime(2007, 7, 15, 12, 00, 53)
 
>>> p.id
# Change values by changing the attributes, then calling save().
1
>>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
>>> p.save()
 
You can also access the database columns (Fields, in Django parlance) as Python attributes:
# objects.all() displays all the polls in the database.
>>> Poll.objects.all()
[<Poll: Poll object>]
 
>>> p.question
Wait a minute. <Poll: Poll object> is, utterly, an unhelpful representation of this object. Let's fix that by editing the polls model (in the polls/models.py file) and adding a __unicode__() method to both Poll and Choice:
"What's up?"
>>> p.pub_date
datetime.datetime(2007, 7, 15, 12, 00, 53)
 
We can time travel back in time! Or at least, we can send the Poll back in time:
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
 
# Change values by changing the attributes, then calling save().
class Choice(models.Model):
>>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
# ...
>>> p.save()
def __unicode__(self):
return self.choice
 
Finally, we can also ask Django to show a list of all the Poll objects available:
It's important to add __unicode__() methods to your models, not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin.
 
>>> Poll.objects.all()
Why __unicode__() and not __str__()?
[<Poll: Poll object>]
 
Wait a minute. <Poll: Poll object> is, utterly, an unhelpful representation of this object. Let's fix that by editing the polls model (in the polls/models.py file) and adding a __unicode__() method to both Poll and Choice:
If you're familiar with Python, you might be in the habit of adding __str__() methods to your classes, not __unicode__() methods. We use __unicode__() here because Django models deal with Unicode by default. All data stored in your database is converted to Unicode when it's returned.
 
class Poll(models.Model):
Django models have a default __str__() method that calls __unicode__() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.
# ...
def __unicode__(self):
return self.question
 
class Choice(models.Model):
If all of this is jibberish to you, just remember to add __unicode__() methods to your models. With any luck, things should Just Work for you.
# ...
def __unicode__(self):
return self.choice
 
It's important to add __unicode__() methods to your models, not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin.
 
(If you're using to Python programming from a time in the past, you might have seen __str__(). Django prefers you use __unicode__() instead.)
 
Note these are normal Python methods. Let's add a custom method, just for demonstration:
 
import datetime
# ...
class Poll(models.Model):
# ...
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
 
Note the addition of import datetime to reference Python's standard datetime module.
Line 337 ⟶ 308:
Save these changes and start a new Python interactive shell by running python manage.py shell again:
 
>>> from polls.models import Poll, Choice
 
Check it out: our __unicode__() addition worked:
 
>>> Poll.objects.all()
[<Poll: What's up?>]
 
If you want to search your database, you can do it using the '''filter''' method on the ''objects'' attribute of Poll. For example:
 
>>> p = Poll.objects.filter(question="What's up?")
>>> p
[<Poll: What's up?>]
>>> p.id
1
 
If you try to search for a poll that does not exist, ''filter'' will give you the empty list. The '''get''' method will always return one hit, or raise an exception.
 
>>> Poll.objects.filter(question="What time is it?")
# Make sure our __unicode__() addition worked.
[]
>>> Poll.objects.all()
[<Poll: What's up?>]
 
>>> Poll.objects.get(id=1)
# Django provides a rich database lookup API that's entirely driven by
<Poll: What's up?>
# keyword arguments.
>>> Poll.objects.filterget(id=12)
Traceback (most recent call last):
[<Poll: What's up?>]
...
>>> Poll.objects.filter(question__startswith='What')
DoesNotExist: Poll matching query does not exist.
[<Poll: What's up?>]
 
=== Adding choices ===
# Get the poll whose year is 2007.
>>> Poll.objects.get(pub_date__year=2007)
<Poll: What's up?>
 
Right now, we have a Poll in the database, but it has no Choices. See:
>>> Poll.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Poll matching query does not exist.
 
>>> p = Poll.objects.get(pk=1)
# Lookup by a primary key is the most common case, so Django provides a
>>> p.choice_set.all()
# shortcut for primary-key exact lookups.
[]
# The following is identical to Poll.objects.get(id=1).
>>> Poll.objects.get(pk=1)
<Poll: What's up?>
 
So let's create three choices:
# Make sure our custom method worked.
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_today()
False
 
>>> p.choice_set.create(choice='Not much', votes=0)
# Give the Poll a couple of Choices. The create call constructs a new
<Choice: Not much>
# choice object, does the INSERT statement, adds the choice to the set
>>> p.choice_set.create(choice='The sky', votes=0)
# of available choices and returns the new Choice object. Django creates
<Choice: The sky>
# a set to hold the "other side" of a ForeignKey relation
>>> c = p.choice_set.create(choice='Just hacking again', votes=0)
# (e.g. a poll's choices) which can be accessed via the API.
<Choice: Just hacking again>
>>> p = Poll.objects.get(pk=1)
 
Every Choice can find the Poll that it belongs to:
# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
[]
 
>>> c.poll
# Create three choices.
<Poll: What's up?>
>>> p.choice_set.create(choice='Not much', votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice='The sky', votes=0)
<Choice: The sky>
>>> c = p.choice_set.create(choice='Just hacking again', votes=0)
 
We just used this, but now I'll explain it: Because a Poll can have more than one Choice, Django creates the '''choice_set''' attribute on each Poll. You can use that to look at the list of available Choices, or to create them.
# Choice objects have API access to their related Poll objects.
>>> c.poll
<Poll: What's up?>
 
>>> p.choice_set.all()
# And vice versa: Poll objects get access to Choice objects.
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> p.choice_set.all()
>>> p.choice_set.count()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
3
>>> p.choice_set.count()
3
 
=== Visualize the database in SQLite Manager ===
# 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 poll whose pub_date is in 2007.
>>> Choice.objects.filter(poll__pub_date__year=2007)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
 
* FIXME
# Let's delete one of the choices. Use delete() for that.
>>> c = p.choice_set.filter(choice__startswith='Just hacking')
>>> c.delete()
 
=== Enough databases for now ===
For more information on model relations, see Accessing related objects. For more on how to use double underscores to perform field lookups via the API, see Field lookups. For full details on the database API, see our Database API reference.
 
''Finally'', in the next step, we'll see all this in the Django administration interface. Then we can add an image to these Choices.
When you're comfortable with the API, read part 2 of this tutorial to get Django's automatic admin working.
Anonymous user