[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~

Series list (will be updated when all articles are completed)

Create a model

Django has an ORM (Object-Relational Mapping). ORM refers to the ability to convert between program source code and database data. In the case of Django, describe it in modele.py with Pythn.

Now, let's write the Post model.

/crud/blog/models.py


from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class Post(models.Model):
    #Title CHAR up to 100 characters
    title = models.CharField(max_length=100)
    #Content text
    content = models.TextField()
    #Author foreign key constraint(One-to-many relation)Delete child data as well as user parent data
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    #Post date Date type Current time
    date_posted = models.DateTimeField(default=timezone.now)

    #Display setting of management screen Display title
    def __str__(self):
        return self.title

migration

(crud-_w5mSGH2) C:\django\crud>python manage.py makemigrations
Migrations for 'blog':
  blog\migrations\0001_initial.py
    - Create model Post

(crud-_w5mSGH2) C:\django\crud>

The following files are automatically generated. You don't have to edit it.

/crud/blog/migrations/0001_initial.py


# Generated by Django 3.1.1 on 2020-10-12 12:32

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    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=100)),
                ('content', models.TextField()),
                ('date_posted', models.DateTimeField(default=django.utils.timezone.now)),
                ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]

My Great

(crud-_w5mSGH2) C:\django\crud>python manage.py migrate
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

(crud-_w5mSGH2) C:\django\crud>

Register data

If it is an original blog, I will post an article from the posting screen, but I have not implemented it yet. Django has an admin screen from which you can register your data. Therefore, I would like to register the article data from the management screen once.

Display Post on the management screen

You have to tell Django what you want to see on the admin screen. Let's modify the following files.

crud/blog/admin.py


from django.contrib import admin
from .models import Post

admin.site.register(Post)

Create an admin user

Create an admin user to log in to the admin screen. User: admin Password: pass

(crud-_w5mSGH2) C:\django\crud>python manage.py createsuperuser
username(leave blank to use 'wmgoz'): admin
mail address: ***@***.com #← Please use your own email address
Password:
Password (again):
This password is too short. At least 8 characters are required.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

(crud-_w5mSGH2) C:\django\crud>

Log in to the management screen

Let's start the development server and log in to the management screen.

python manage.py runserver

Next, let's access the management screen "http://127.0.0.1:8000/admin/". image.png The following management screen was displayed. image.png

Try to register the data!

Click "+ Add" next to "Posts" on the management screen to proceed to data entry.

Registration of data ①: image.png

Registration of data ②: image.png

Two articles have been posted. image.png

That's all for today. Thank you very much.

Recommended Posts

[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
Create a Todo app with the Django REST framework
Create a python GUI using tkinter
Create a Python general-purpose decorator framework
Install Python framework django using pip
Create a CRUD API using FastAPI
Try using the Python web framework Django (2) --Look at setting.py
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Create a graph using the Sympy module
[Python] Create a Batch environment using AWS-CDK
[Ev3dev] Create a program that captures the LCD (screen) using python
Create a REST API to operate dynamodb with the Django REST Framework
Create a shogi game record management app using Django 3 ~ Django default management site settings ~
Try using the Python web framework Django (1)-From installation to server startup
Create a record with attachments in KINTONE using the Python requests module
Create a GIF file using Pillow in Python
Try using the Python web framework Tornado Part 1
Create a web map using Python and GDAL
Run a Python file from html using Django
Create a Mac app using py2app and Python3! !!
Try using the Python web framework Tornado Part 2
Create a MIDI file in Python using pretty_midi
Create a GUI on the terminal using curses
Django python web framework
Create a Python module
Create a Python environment
Create a Python image in Django without a dummy image file and test the image upload
Create a simple reception system with the Python serverless framework Chalice and Twilio
Create a Django project and application in a Python virtual environment and start the server
Create a data collection bot in Python using Selenium
Create a Todo app with Django REST Framework + Angular
Cut a part of the string using a Python slice
(Python) Try to develop a web application using Django
[Python] Create a ValueObject with a complete constructor using dataclasses
DJango Note: From the beginning (using a generic view)
Build a Python virtual environment using venv (Django + MySQL ①)
[Django Rest Framework] Customize the filter function using Django-Filter
[Python] Mask the image into a circle using Pillow
Create a company name extractor with python using JCLdic
A little bit from Python using the Jenkins API
Create a dictionary by searching the table using sqlalchemy
[Python] Let's change the URL of the Django administrator site
Create a Wox plugin (Python)
Create a function in Python
Create a dictionary in Python
[S3] CRUD with S3 using Python [Python]
Create ToDo List [Python Django]
Create a homepage with django
Create JIRA tickets using Python
Create a python numpy array
Create a Django login screen
Create a directory with python
Create a shogi game record management app using Django 4 ~ Create View ~
Create a local scope in Python without polluting the namespace
Probably the easiest way to create a pdf with Python3
Try a similar search for Image Search using the Python SDK [Search]
Create a real-time auto-reply bot using the Twitter Streaming API