Now we’ll setup the database, create our
first model, and get a quick introduction to Django’s automatically-generated
admin site.
If you open up pollsite/settings.py you’ll
notice that by default, the configuration uses SQLite. SQLite is included in
Python, so you won’t need to install anything else to support your database.
When starting your first real project, however, you may want to use a more
scalable database like PostgreSQL, to avoid database-switching headaches down
the road.
Also, note the INSTALLED_APPS setting at
the top of the file. That holds the names of all Django applications that are
activated in this Django instance. Apps can be used in multiple projects, and
you can package and distribute them for use by others in their projects.
By default, INSTALLED_APPS contains the
following apps, all of which come 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 managing static 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 do that, run the following command:
python manage.py
migrate
(pollapp_env)
C:\Application_django>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
(pollapp_env) C:\Application_django>
The migrate command looks at the
INSTALLED_APPS setting and creates any necessary database tables according to
the database settings in your pollsite/settings.py file and the database
migrations shipped with the app. You’ll see a message for each migration it
applies.
It’s time now to create models. In our
poll app, we’ll create two models: 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. Edit the
polls/models.py file and add the following code to it:
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)
Each model is represented by a class
that subclasses django.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 Field class – e.g., CharField for character fields and DateTimeField for
datetimes. This tells Django what type 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-friendly format.
You’ll use this value in your Python code, and your database will use it as the
column name.
You can use an optional first positional
argument to a Field to designate a human-readable name. That’s used in 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 this
example, 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 will suffice
as its human-readable name.
Some Field classes have required
arguments. 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.
A Field can also have various optional
arguments; in this case, we’ve set the default value of votes to 0.
Finally, note a relationship is defined,
using ForeignKey. That tells Django each Choice is related to a single
Question. Django supports all the common database relationships: many-to-one,
many-to-many, and one-to-one.
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 pollsite/settings.py file and add that
dotted path to the INSTALLED_APPS setting. It’ll look like this:
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 the polls
app. Let’s run another command:
python manage.py makemigrations polls
You should see something similar to the
following:
(pollapp_env)
C:\Application_django>python manage.py makemigrations polls
Migrations for 'polls':
polls\migrations\0001_initial.py
- Create model Question
- Create model Choice
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) - they’re files on disk. You can
read the migration for your new model if you like; it’s the file
polls/migrations/0001_initial.py.
Now, run migrate again to create those model tables in your
database:
(pollapp_env)
C:\Application_django>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0001_initial... OK
The migrate command takes all the
migrations that haven’t been applied (Django tracks which ones are applied
using a special table in your database called django_migrations) and runs them
against your database - essentially, synchronizing the changes you made to your
models with the schema in the database.
Migrations are very powerful and let you
change your models over time, as you develop your project, without the need to
delete your database or tables and make new ones - it specializes in upgrading
your database live, without losing data.
Django Admin
Django entirely automates creation of
admin interfaces for models. First, we’ll need to create a user who can login
to the admin site. Run the following command:
python manage.py createsuperuser
(pollapp_env)
C:\Application_django>python manage.py createsuperuser
Username (leave blank to use 'vswam'):
admin
Email address: admin@swami.com
Password:
Password (again):
Superuser created successfully.
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:
Now log in with the
superuser account that was created:
Now we need to tell the admin that
Question objects have an admin interface. To do this, open the polls/admin.py
file, and edit it to look like this:
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)
Now that we’ve registered Question,
Django knows that it should be displayed on the admin index page:
Click “Questions”. Now you’re at the
“change list” page for questions. This page displays all the questions in the
database and lets you choose one to change it.
I’ve created Which is better framework
for wed development as an example question.
There is a typo in Which is better
framework for wed development, it should be web and not wed. This can be done
by editing the question.
Create some questions on your own and
see if are able to.
0 comments:
Post a Comment