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 time has verified "Hello World!" With Django. This time, we will create a simple memo app using all ** MTV **!
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.
** 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. ..
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
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
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.
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.
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. 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. 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! 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.
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.
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'>
<!-Content of memo-> {% for memo in memos %}
Creation date: {{memo.created_date}} p>
{{ memo.text | linebreaks }}