Creating the superuser for Django

Now, we will run the necessary command to create the superuser for Django that will allow us to authenticate our requests. We will create other users later.

Make sure you are in the restful01 folder that includes the manage.py file in the activated virtual environment. Execute the following command that executes the createsuperuser subcommand for the manage.py script to allow us to create the superuser:

    python manage.py createsuperuser

The command will ask you for the username you want to use for the superuser. Enter the desired username and press Enter. We will use djangosuper as the username for this example. You will see a line similar to the following one:

    Username (leave blank to use 'gaston'):

Then, the command will ask you for the email address. Enter an email address and press Enter. You can enter [email protected]:

    Email address:

Finally, the command will ask you for the password for the new superuser. Enter your desired password and press Enter. We will use passwordforsuper as an example in our tests. Of course, this password is not the best example of a strong password. However, the password is easy to type and read in our tests:

    Password:

The command will ask you to enter the password again. Enter it and press Enter. If both entered passwords match, the superuser will be created:

    Password (again): 
    Superuser created successfully.

Our database has many rows in the drones_drone table. We added a new owner field for the Drone model and this required field will be added to the drones_drone table after we execute migrations. We have to assign a default owner for all the existing drones to make it possible to add this new required field without having to delete all these drones. We will use one of the features included in Django to solve the issue.

First, we have to know the id value for the superuser we have created to use it as the default owner for the existing drones. Then, we will use this value to let Django know which is the default owner for the existing drones.

We created the first user, and therefore, the id will be equal to 1. However, we will check the procedure to determine the id value in case you create other users and you want to assign any other user as the default owner.

You can check the row in the auth_user table whose username field matches 'djangosuper' in any tool that works with PostgreSQL. Another option is to run the following commands to retrieve the ID from the auth_user table for the row whose username is equal to 'djangosuper'. In case you specified a different name, make sure you use the appropriate one. In addition, replace the username in the command with the username you used to create the PostgreSQL database and password with your chosen password for this database user.

The command assumes that you are running PostgreSQL on the same computer in which you are executing the command:

    psql --username=username --dbname=drones --command="SELECT id FROM 
auth_user WHERE username = 'djangosuper';"

The following lines show the output with the value for the id field: 1:

    id 
    ----
      1
    (1 row)

Now, run the following Python script to generate the migrations that will allow us to synchronize the database with the new field we added to the Drone model:

    python manage.py makemigrations drones

Django will explain to us that we cannot add a non-nullable field without a default and will ask us to select an option with the following message:

 You are trying to add a non-nullable field 'owner' to drone without a   
default; we can't do that (the database needs something to populate
existing rows).
Please select a fix: 1) Provide a one-off default now (will be set on all existing rows
with a null value for this column)
2) Quit, and let me add a default in models.py Select an option:

Enter 1 and press Enter. This way, we will select the first option to provide the one-off default that will be set on all the existing drones_drone rows.

Django will ask us to provide the default value we want to set for the owner field of the drones_drone table:

    Please enter the default value now, as valid Python
    The datetime and django.utils.timezone modules are available, so 
you can do e.g. timezone.now
Type 'exit' to exit this prompt >>>

Enter the value for the previously retrieved id: 1. Then, press Enter. The following lines show the output generated after running the previous command:

    Migrations for 'drones':
      drones/migrations/0003_drone_owner.py
        - Add field owner to drone

The output indicates that the restful01/drones/migrations/0003_drone_owner.py file includes the code to add the field named owner to the drone table. The following lines show the code for this file that was automatically generated by Django. The code file for the sample is included in the hillar_django_restful_08_01 folder, in the restful01/drones/migrations/0003_drone_owner.py file:

# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-09 22:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('drones', '0002_auto_20171104_0246'),
]

operations = [
migrations.AddField(
model_name='drone',
name='owner',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='drones', to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]

The code declares the Migration class as a subclass of the django.db.migrations.Migration class. The Migration class defines an operations list with a migrations.AddField instance that will add the owner field to the table related to the drone model.

Now, run the following Python script to apply all the generated migrations and execute the changes in the database tables:

    python manage.py migrate

The following lines show the output generated after running the previous command:

Operations to perform:
Apply all migrations: admin, auth, contenttypes, drones, sessions
Running migrations:
Applying drones.0003_drone_owner... OK

After we run the previous command, we will have a new owner_id field in the drones_drone table in the PostgreSQL database. The existing rows in the drones_drone table will use the default value we instructed Django to use for the new owner_id field: 1. This way, the superuser named 'djangosuper' will be the owner for all the existing drones.

We can use the PostgreSQL command line or any other application that allows us to easily check the contents of the PostreSQL database to browse the drones_drone table that Django updated.

The following screenshot shows the new structure for the drones_drone table at the left-hand side and all its rows at the right-hand side:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.115.195