[PYTHON] A series of amateur infrastructure engineers touching Django with Docker ③: Django admin

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.

① Edit admin.py

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.

Well-understood commentary

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 001.png 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.

② Create a super user for the admin site

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.

002.png I was able to log in.

③ Record operation

Click on Posts. 003.png 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. 004.png As defined in models.py last time, there are text boxes and pull-down lists for input. I will post one as a trial. 005.png 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.

Create docker-compose including DB migrate and create superuser processing

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()

Well-understood commentary

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?)

Continued

Recommended Posts

A series of amateur infrastructure engineers touching Django with Docker ③: Django admin
A series of amateur infrastructure engineers touching Django with Docker (2): Creating a model
A series of amateur infrastructure engineers touching Django with Docker ⑤: View, Template, CSS
Deploy a Django application with Docker
[Python] Build a Django development environment with Docker
Impressions of touching Django
A memo about building a Django (Python) application with Docker
Launch Django on a Docker container with docker-compose up
Build a development environment with Poetry Django Docker Pycharm
[Memo] Build a development environment for Django + Nuxt.js with Docker
I want to make a blog editor with django admin
[Django] Build a Django container (Docker) development environment quickly with PyCharm
Create a Todo app with Django ① Build an environment with Docker
Create a homepage with django
Here's a brief summary of how to get started with Django
I made a development environment for Django 3.0 with Docker, Docker-compose, Poetry
[DynamoDB] [Docker] Build a development environment for DynamoDB and Django with docker-compose
Creating a Flask server with Docker
Build a deb file with Docker
Django Tips-Create a ranking site with Django-
Build a web application with Django
Make a filter with a django template
Basics of touching MongoDB with MongoEngine
Create a file uploader with Django