TL;DR Continuation of Amateur infrastructure engineer touching Django with Docker series ②: Creating a model. If you want to read from 1, ↓ here. Amateur infrastructure engineer touches Django with Docker (1): Make Django with Docker This time as well, I will play with django while making a sample of Django Girls. Since I created a model last time, I would like to go to View and Template this time, but first I will learn the administration site (admin) for managing Django models. In order to execute up to user creation of the management site with docker-compose, it is necessary to create an extended command so that the create command createsuperuser can be executed with one liner, so that is also described.
Django admin By default, Django has a page called admin to manage your model with a GUI. This time we will look at its activation and usage.
admin.py Edit as follows.
blog/admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Since the first line is included from the beginning, the other lines are added.
from django.contrib import admin
The application module for the admin site. I didn't mention it last time, but django.contrib.admin
is also listed by default in INSTALLED_APPS
in settings.py
where I added my own application so that it can be used from the beginning. It has become.
from .models import Post
The Post model is called from models.py stored in the same directory.
admin.site.register(Post)
You can add a Model under the control of the admin site with ʻadmin.site.register (Model)`.
Now, let's take a look at the admin site in the running container.
(docker-compose up
doesn't need people who have been running since the last time.)
docker-compose up
The following is executed from another terminal. Last time, I executed python manage.py migrate blog
to migrate only migrations under the blog directory, but this time I also migrate the admin model by executing it without giving any arguments.
docker-compose exec web bash
python manage.py migrate
exit
Access http: // IPADDRESS: 8000 / admin
The login screen opens. The login user to enter here needs to be created by executing the command with migrate.py
in the same way as DB migration.
docker-compose exec web bash
python manage.py createsuperuser
exit
When I run createsuperuser
, I get a prompt. When you enter the user name, email address, and password, the output "Superuser created successfully.`" will be output. Enter the information entered here on the login screen.
I was able to log in.
Click on Posts. Since the POST model was defined last time and the table was created, it is naturally displayed as 0 posts. It seems that you can insert data with the button called ADD POST, so try pressing it. As defined in models.py last time, there are text boxes and pull-down lists for input. I will post one as a trial. I was able to add the data safely. Go into the db container and see if it actually contains the record.
docker-compose exec db bash
psql -U postgres
SELECT * FROM blog_post;
SELECT execution result
id | title | text | created_date | published_date | author_id
----+-------+--------------------+------------------------+------------------------+-----------
1 | TEST | This is test post. | 2020-05-02 07:47:14+00 | 2020-05-02 07:47:26+00 | 2
(1 row)
I was able to confirm that the records were stored properly. You can create, update, and delete records on the same screen.
So far, I have logged in to the container using docker-compose exec
for verification purposes only, but if possible, it would be smarter to build up to this point with docker-compose up at once.
①DB migrate
As for migrate, you only need to type a command, so you can process it by rewriting command:
in docker-compose.yaml as shown below. (Make migration only creates a migration file, so you don't need it if you already have one.)
docker-compose.yaml
command: sh -c "sleep 5; python manage.py migrate; python manage.py runserver 0.0.0.0:8000"
I slept for 5 seconds before executing migrate, but I added it because an error sometimes occurs due to a problem with Postgres startup timing.
②createsuperuser
Since createsuperuser processes interactively at runtime, docker-compose cannot handle it unless it can be executed with one liner.
When I googled, manage.py seems to be able to extend the commands by creating a folder called management / commands
and adding a python file.
https://stackoverflow.com/questions/6244382/how-to-automate-createsuperuser-on-django
https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/
Use it to optionally receive a username and password to create a one-liner custom command that can be executed.
cd blog
mkdir -p management/commands
touch management/__init__.py
touch management/commands/__init__.py
createcustomsuperuser.py
management/commands/createcustomsuperuser.py
from django.contrib.auth.management.commands import createsuperuser
from django.core.management import CommandError
class Command(createsuperuser.Command):
help = 'Crate a superuser, and allow password to be provided'
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
'--password', dest='password', default=None,
help='Specifies the password for the superuser.',
)
def handle(self, *args, **options):
password = options.get('password')
username = options.get('username')
database = options.get('database')
if password and not username:
raise CommandError("--username is required if specifying --password")
super().handle(*args, **options)
if password:
user = self.UserModel._default_manager.db_manager(database).get(username=username)
user.set_password(password)
user.save()
from django.contrib.auth.management.commands import createsuperuser
This time, import to extend the command of createsuperuser.
from django.core.management import CommandError
The command error that django has. This time it is used to return an error when there are not enough arguments.
class Command(createsuperuser.Command):
help = 'Crate a superuser, and allow password to be provided'
Added the wording that is displayed when calling help with --help
or -h
.
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
'--password', dest='password', default=None,
help='Specifies the password for the superuser.',
)
A function that adds command arguments. super (). Add_arguments (parser)
is running to also add the arguments of the original createsuperuser
. Added an argument called password that was not accepted by the original createsuperuser.
def handle(self, *args, **options):
password = options.get('password')
username = options.get('username')
database = options.get('database')
if password and not username:
raise CommandError("--username is required if specifying --password")
super().handle(*args, **options)
if password:
user = self.UserModel._default_manager.db_manager(database).get(username=username)
user.set_password(password)
user.save()
The actual processing part. The user created by the conventional createsuperuser process is searched from the db, and the password is set and saved.
After creating this file, rewrite docker-compose.yaml as follows.
docker-compose.yaml
command: sh -c "sleep 5; python manage.py migrate; python manage.py createcustomsuperuser --username root --password 123456 --noinput --email '[email protected]'; python manage.py runserver 0.0.0.0:8000"
(Password is an example) In this way, being able to write in docker-compose.yaml seems to be good if you specify it in Secret in the manifest even when migrating to Kubernetes.
Please make sure that the process up to this point is completed in one line, docker-compose up
.
docker-compose up
Next time, I will learn how to write urls.py. (When will you write a View?)
Recommended Posts