To myself as a Django beginner (4) --Create a memo app--

** Tutorial list **

No. title
1 To myself as a Django beginner (1)-Project app-
2 To myself as a Django beginner (2)-What is MTV-
3 To myself as a Django beginner (3)-Hello world!-
4 To myself as a Django beginner (4)-Memo app creation-

** Last review **

Last time has verified "Hello World!" With Django. This time, we will create a simple memo app using all ** MTV **!

** Let's Django -Create Memo App-**

The goal this time is to deepen the understanding of ** Model ** and ** Template ** that were not used last time by creating a memo app. Also, based on what I've learned so far, I'd be very happy if I could understand the flow of creating a web application with Django!

We will create it according to the following flow.

  1. Model definition
  2. Reflection in database (usual event: migrate)
  3. Admin page
  4. View settings
  5. Template settings
  6. URL settings

** Definition of Model **

** Model ** describes the definition of the data to be stored in the database. Let's write it.

app1/models.py

from django.db import models

# Create your models here.

class Memo(models.Model):

title = models.CharField (verbose_name ='title', max_length = 100) text = models.TextField (verbose_name ='content') created_date = models.DateTimeField (verbose_name ='created date', auto_now_add = True)

    def __str__(self):
        return self.title

Let's look at each one.

--Memo is the name of the model. Model names are capitalized. --title, text, created_date are fields to be registered in the database. --When defining a field, you need to determine the type of field, such as whether it is text, a date, or a number. --models.CharField: A field that defines the length of the text. It is max_length = 100 in (). That's right, that is, please write the title within 100 characters. --models.TextField: This is also text, but no length is specified. --models.DateTimeField: This is a date and time field. By setting ʻauto_now_add = True, the time when the data was created is automatically entered. --verbose_name` specifies the display on the management screen. The management screen will be described later.

This is the end of Model definition. There are many other types of model fields, so if you're curious, take a look at the Official Documentation. ..

** Reflection in database (usual event: migrate) **

After defining the Model, you have to do ** migrate ** in order to reflect that information in the database. This is a customary event or a traditional event, and it must be done whenever there is a model addition or change.

To reflect the Model definition to the database, perform the following processing.

--Add / Change Model --Make migrations --Migrate

Creating a migration file

Execute the following command at the command prompt.

C:\Users\User_name\myapp>python manage.py makemigrations

Then you will see the following output. At this point, a file for migrating has been created, but it has not yet been reflected in the database.

Migrations for 'app1':
  app1\migrations\0001_initial.py
    - Create model Memo

My Great

Continue with the following command:

C:\Users\User_name\myapp>python manage.py migrate

Then you should see the following output.

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

My Great is complete with just this! The Memo model has been successfully reflected in the database! ... but it's hard to imagine what actually happened. In order to solve such a problem, we have prepared a special item today.

** Administrator page **

Django comes with an admin page by default. Here I would like to store the data in the database from the admin page and see what happened with the previous migration.

Start the server immediately and access the administrator page!

C:\Users\User_name\myapp>python manage.py runserver

After verifying that the server has started, go to http://127.0.0.1:8000/admin. Then you will end up with the following page. django_admin.PNG

Hmm? Oh, Password for Username? I don't have such a thing. That's right, but don't worry. This can also be easily created from the command prompt. Disconnect the server once, or prepare a new console and execute the following command.

C:\Users\User_name\myapp>python manage.py createsuperuser
Username (leave blank to use 'User_name'): memo_user
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.    

It will be displayed line by line from the top. If you press Enter without entering any Username, your'User_name' will be registered. User registration is complete when you have entered the email and password correctly. Start the server again and log in at the / admin page. django_admin_page.PNG This is the admin page that comes with Django by default. It's simple and sophisticated, isn't it? Hmm, I like it. To check the Model on the administrator page, you need to set it in ʻapp1 / admin.py`.

app1/admin.py

from django.contrib import admin

from .models import Memo # Import Memo

# Register your models here.

admin.site.register (Memo) # Add

After writing these, please go back to the administrator page and refresh the page. django_admin_add_model.PNG I have confirmed the model of my Memo app! Now go to the Memo page and create a note from ADD MEMO in the upper right! add_memo.PNG What kind of memo did you write? No, I didn't care about that (laughs) If you go back to the memo page, you can see that the memo was added. In this way, Django allows you to add data to the database and check its contents via the admin page. Apparently, this seems to be a ridiculously useful feature, and it would normally be necessary to write and operate the database language from the console, or create an administrator page from scratch. To be honest, I'm still developing a database, so it's very helpful to be able to manipulate data visually like this. Thank you very much, Django.

** View settings **

From here, we will set ** View **. View fetches data from the database on request and decides how to display it on the screen!

app1/views.py

from django.shortcuts import render

from .models import Memo # Import Memo

# Create your views here.

def memo_list(request):
    memos = Memo.objects.all()

    context = {'memos': memos}
    return render(request, 'app1/memo_list.html', context)

This time, I will display the list of memos on the screen. To do this, we need to get the data for the Memo model.

--memos = Memo.objects.all (): Get all the objects (title, content, creation date) of Memo. --context = {'memos': memos}: Make the necessary information into a dictionary and pass it to Template. --render (request,'app1 / memo_list.html', context): Pass context to ʻapp1 / memo_list.html. The memo_list.html mentioned here is the Template. (Memo_list.html` will be created later)

This completes the View settings. It is possible to narrow down the conditions when acquiring data, but this time we will acquire all with Simple is Best. Official document will be helpful for how to get the data.

** Template settings **

It's finally over. Template is not provided by default, so you need to prepare it yourself. Prepare a directory called templates under the app, and prepare a directory called app1 in it. Then put the html file in app1. Please refer to this article by narito blog for the reason for making such a composition.

myapp/templates/app1/memo_list.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Memo</title>
</head>

<style>
    .app-name {
        text-align: center;
    }
    .contents {
        margin-left: 300px;
        margin-right: 300px;
    }
</style>


<div class='app-name'>

My memo

<!-Content of memo-> {% for memo in memos %}


Title: {{memo.title}}

Creation date: {{memo.created_date}}

{{ memo.text | linebreaks }}

{% endfor %}

I will not touch on HTML / CSS here, but focus on how to display the memos received from View earlier in Template.

--Enclose the if, for syntax in {%%}. --memo.title gets the title of the memo, memo.created_date gets the creation date of the memo, and memo.text gets the contents of the memo. You must enclose it in {{}} to see these data. --linebreaks will convert line breaks in text to HTML tags as appropriate.

At this point, the goal is just around the corner! All you have to do is set the URL!

** URL settings **

Set the URL memo_list / to direct the processing to views.memo_list. app1/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.hello),

path ('memo_list /', views.memo_list), # Add ]

Now start the server as usual and go to http://127.0.0.1:8000/memo_list! memo_app.PNG You've finally done it! ** Model - Template - View ** have joined hands firmly to complete the memo app! Congratulations! Of course, this is just the beginning of the beginning, and it is no wonder that it feels unsatisfactory. Speaking of memo app

--Post / Edit / Delete --List display

It would be more convenient if there was such a function. Rest assured, everything I've listed here can be implemented in Django! You see, you want to know more about Django, right? You can also learn HTML / CSS and decorate it to create well-designed web applications!

Finally

How was it? This time around, I've written a total of four Django tutorials. I hope you've achieved the goal of this tutorial, "Understanding how Django works, and making Django feel like it's not scary and interesting." At the beginning of my studies, I'm sure I'm saying "Django isn't scary! It's funny!"

** References **

-Official Document -Django Girls Tutorial (Japanese) -narito blog

Recommended Posts

To myself as a Django beginner (4) --Create a memo app--
To myself as a Django beginner (1) --Create a project app--
To myself as a Django beginner (3)-Hello world! ---
To myself as a Django beginner (2) --What is MTV?
A memo to create a virtual environment (venv) before Django
Steps to create a Django project
How to develop a cart app with Django
How to create a multi-platform app with kivy
How to create a Rest Api in Django
Until you create a new app in Django
I want to upload a Django app to heroku
Create a Django schedule
Create a Todo app with the Django REST framework
Steps from installing Python 3 to creating a Django app
Create a Todo app with Django ③ Create a task list page
Create a Todo app with Django ⑤ Create a task editing function
Create a homepage with django
Shell to create django project
Create a Django login screen
Create a shogi game record management app using Django 4 ~ Create View ~
Create a Todo app with Django ① Build an environment with Docker
[Django] Memo to create an environment of Django + MySQL + Vue.js [Python]
Create a shogi game record management app using Django 2-Database settings-
Deploy Django + React from scratch to GKE (3) Create a GCP project
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Create a shogi game record management app using Django 6 ~ Template division ~
How to create a Conda package
Rails users try to create a simple blog engine with Django
How to create a virtual bridge
Create and deploy a Django (PTVS) app using Azure Table storage
Implement a Django app on Hy
How to create a Dockerfile (basic)
5 Ways to Create a Python Chatbot
How to create a config file
Create a REST API to operate dynamodb with the Django REST Framework
Create a file uploader with Django
Create a LINE Bot in Django
Web App Development Practice: Create a Shift Creation Page with Django! (Introduction)
A story about a beginner trying hard to set up CentOS 8 (procedure memo)
Create a Todo app with Django ④ Implement folder and task creation functions
I tried to create a linebot (implementation)
How to create a clone from Github
Create a bot to retweet coronavirus information
How to create a git clone folder
I tried to create a linebot (preparation)
Create a model for your Django schedule
Create a simple GUI app in Python
Create a GUI app with Python's Tkinter
Create a simple web app with flask
Create a Python-GUI app in Docker (PySimpleGUI)
[Django] A memo when log was not
Create your first app with Django startproject
Various ways to create a dictionary (memories)
How to create a repository from media
Script to create a Mac dictionary file
Go beginner tried to create a cloud native web application using Datastore / GAE
Try to create a Todo management site using WebSocket with Django (Swamp Dragon)
A machine learning beginner tried to create a sheltie judgment AI in one day
Edit Excel from Python to create a PivotTable
How to disguise a ZIP file as a PNG file
I want to easily create a Noise Model