[DOCKER] Django tutorial (blog application creation) ② --model creation, management site preparation

Last time created the basic part of the blog application and was able to check the operation. This time, let's prepare for actually registering the article and create the article.

Creating an article model

Create a model to manage articles on your blog. model acts as a bridge between the database and Django, which allows us to register data in the database without being aware of database syntax such as SQL.

In models.py that is set first, what kind of data is to be registered is defined. In an Excel table, it is a place to define the column name of each column of the table and what kind of data (character string, numerical value, etc.) is contained in each column.

This time it is a blog application, and we will modify the article (Post), so we will create a Post model. It's enough to include the title, text, and date.

blog/models.py


from django.db import models
from django.utils import timezone #Module for managing dates in django

class Post(models.Model):
    title = models.CharField('title', max_length=200)
    text = models.TextField('Text')
    date = models.DateTimeField('date', default=timezone.now)

    def __str__(self): #Defines the value to return when the Post model is called directly
        return self.title #Returns the article title

Then make the database reflect the information defined in models.py. We will not process the database as it is, but create a file that will serve as a cushion to reflect the contents of models.py. You can have Django automatically create the file for you, and run the following command to create the file:

python3 manage.py makemigrations

Then a numbered file will be created under / blog / migrations.

.
├── blog
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── 0001_initial.py #This will be added
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── templates
    └── blog
        └── index.html

You won't mess with this file directly when creating a Django app, but it looks like this, which allows Django to do things like column creation all at once.

0001_initial.py


# Generated by Django 3.1 on 2020-10-17 01:13

from django.db import migrations, models
import django.utils.timezone


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Post',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=200, verbose_name='title')),
                ('text', models.TextField(verbose_name='Text')),
                ('date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date')),
            ],
        ),
    ]

Now, you're going to use this migration file to create a table in your database Django will do the reflection for you with a single command. Let's execute the following command.

(blog) bash-3.2$ python3 manage.py migrate

If successful, the first one will return to the normal command line with a lot of OK messages.

Operations to perform:
  Apply all migrations: admin, auth, blog, 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 auth.0012_alter_user_first_name_max_length... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK

Check the table on the management site

You may create an article suddenly, but first of all, I think it is safe to check with the UI whether the table is created properly.

With Django, the UI of the management site is automatically created without any special preparation, and you can check the created table in it, or you can manually create, edit, and delete it. We will prepare for that here.

Reflect model on management site

A file called admin.py is created from the beginning under the blog directory, but by describing the information of the model created earlier here, you can knead it on the management site.

blog/admin.py


from django.contrib import admin
from .models import Post #add to

admin.site.register(Post) #add to

Create an admin user

In order to use the management site, it is necessary to create a user (account) with appropriate authority, that is, superuser. This can also be created quickly with Django commands.

python3 manage.py createsuperuser

When you execute it, you will be asked for your user name, email address, and password, so enter each one.

When the creation is completed, the following display will appear on the command line.

Superuser created successfully.

Log in to the management site

Now, let's actually visit the Django admin site.

First, start the server.

python3 manage.py runserver

Next, enter the address of the management site in the address bar of the browser, Did you notice that the urls.py of the project had the following description?

mysite/ursl.py


urlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls), #here
]

This description exists from the beginning, and by default you can access the admin site with "** 127.0.0.1: 8000 / admin **". (Usually, it is not changed much, but in the production environment, the address may be changed for security reasons.)

Now, access 127.0.0.1:8000 / admin with Chrome etc. image.png If the login screen is displayed like this, it is successful. Enter the information you had when you created the superuser earlier and select Login.

image.png If you log in successfully, the management screen will be displayed. Creating a management site like this requires a lot of preparation with a regular framework, but it's nice to have Django by default.

You can also see that the model called Posts is reflected in the application column called BLOG. (Since there will be multiple Posts, it is also a point that it is written as Posts)

You can also manually create an article here from the ** Add ** button.

image.png

If you choose to save, you can actually create an article. image.png

You can even edit or delete the articles you have created. It's convenient. image.png

Next time, I will try to display the article on the application (display as html).

→ Next time Django Tutorial (Blog App Creation) ③ --Article List Display

Recommended Posts

Django tutorial (blog application creation) ② --model creation, management site preparation
Django Tutorial (Blog App Creation) ① --Preparation, Top Page Creation
Django Tutorial (Blog App Creation) ⑤ --Article Creation Function
Django Tutorial (Blog App Creation) ④ --Unit Test
Django Tutorial (Blog App Creation) ③ --Article List Display
Django Tutorial (Blog App Creation) ⑦ --Front End Complete
Web application creation with Django
Django Tutorial (Blog App Creation) ⑥ --Article Details / Editing / Deleting Functions
WEB application development using Django [Model definition]
WEB application development using Django [Admin screen creation]
Django Tutorial Summary for Beginners by Beginners (Model, Admin)
Until Django application creation by terminal (development environment)
Django tutorial summary for beginners by beginners ① (project creation ~)