Django Polls Simplified — Database Setup
This is a continuation of the previous post:
Now, open config/settings.py
. It's a standard Python module containing module-level variables that represent Django settings.
By default, the DATABASES
configuration uses SQLite. This is the simplest choice for database newcomers or those just exploring Django.
SQLite is included with Python, so there’s no need to install extra software to use it as your database.
However, it’s worth considering a more scalable option like PostgreSQL for your first serious project. This can save you the trouble of migrating to a different database in the future.
Documentation on using other databases:
While you’re editing config/settings.py, set TIME_ZONE to your time zone. I will set mine to Africa/Nairobi:
# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Nairobi'
USE_I18N = True
USE_TZ = True
Take note of the INSTALLED_APPS
settings. It lists all the Django applications currently enabled in this instance.
Applications can be reused across multiple projects and even packaged for distribution, allowing others to integrate them into their projects.
By default, INSTALLED_APPS
includes the following applications, which are all bundled with Django:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
django.contrib.admin
– The admin site.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 managing static files.
These applications are included by default as a convenience for the common case.
Some of these applications use at least one database table, so we need to create the tables in the database before using them.
To do that, run the following command:
python manage.py migrate
If you open the db.sqlite3 file, you will see the tables created:
Creating models
In Django, models are Python classes that represent database tables. They make it easier to work with databases by letting you use Python code instead of writing SQL.
Models define the structure of your data (fields), how different pieces of data are connected (relationships), and any actions you want to perform on the data (methods).
We’ll create two models in our poll app: Question
and Choice
. A Question
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 Question
.
Python classes represent these concepts. Edit the polls/models.py
file so it looks like this:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
In the above code, each model is a class that inherits from django.db.models.Model
. These classes define the structure of your database tables using fields.
Fields: Fields are variables that represent columns in the database. For example:
- CharField is for text.
- DateTimeField is for dates and times.
- IntegerField is for numbers.
Field Names: The variable names (e.g., question_text, pub_date) become the column names in the database.
Field Options:
• You can give a field a custom label, like “date published
” for pub_date
. Django will use the variable name as the label if you don't.
• Some fields require extra arguments. For example, CharField
needs max_length
, which defines the maximum number of characters allowed.
• You can set default values for fields, like votes = models.IntegerField(default=0)
.
Relationships: To link models, you can use fields like ForeignKey
. In this example:
• Each Choice is connected to a Question using a ForeignKey. This means many choices can belong to one question.
Django makes it easy to set up and manage these relationships and data types in your database.
Activating models
That small bit of model code gives Django a lot of information. With it, Django can:
- Create a database schema (
CREATE TABLE
statements) for this app. - Create a Python database-access API for accessing
Question
andChoice
objects.
But first, we must tell our project that the polls
app has been installed.
To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS
setting. The PollsConfig
class is in the polls/apps.py
file, so its dotted path is ‘polls.apps.PollsConfig’
. Edit the config/settings.py
file and add that dotted path to the INSTALLED_APPS
setting. It’ll look like this:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig',
]
Now Django knows to include the polls
app. Let’s run another command:
python manage.py makemigrations polls
python manage.py migrate
By running makemigrations
, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.
Migrations are how Django stores changes to your models (and thus your database schema) — files on disk.
You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py
.
# Generated by Django 5.1.2 on 2024-11-04 14:10
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.CreateModel(
name='Choice',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.question')),
],
),
]
Don’t worry; you’re not expected to read them every time Django makes one, but they’re designed to be human-editable if you want to tweak how Django changes things manually.