[PYTHON] Build a bulletin board app from scratch with Django. (Part 2)

Part 1 https://qiita.com/TuruMaru/items/4df41577fb9f722c7864

Creating a database

I'm going to create a database, but to do that, I first need to write the contents to the table in models.py.

posts/models.py



from django.db import models
#Import to use timezone
from django.utils import timezone

# Create your models here.

#models.It is a rule to write a model
class Posts(models.Model):

    #Meta and object are not magic
    class Meta(object):
        #Specify the name of the table to be created
        db_table = 'posts'

    #Column name=Data format(The name displayed on the management screen,Other constraints)
    text = models.CharField(verbose_name='Text', max_length=255)
    created_at = models.DateField(verbose_name='Created date', default=timezone.now)

    #Set to be displayed on the management screen(Magic)
    def __str__(self):
        return self.text, self.created_at

Now you are ready to create a table called posts. Based on these, we will operate in the terminal.

$ python manage.py makemigrations posts
Migrations for 'posts':
  posts/migrations/0001_initial.py
    - Create model Posts

You have now created the 0001_initial.py file. This file contains the contents of the database to be created. However, this command has not yet created the database. I'm ready.

$ python manage.py sqlmigrate posts 0001
BEGIN;
--
-- Create model Posts
--
CREATE TABLE "posts" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "text" varchar(255) NOT NULL, "created_at" date NOT NULL);
COMMIT;

You can see the SQL code when the table is created with this command.

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, posts, sessions
Running migrations:
  Applying posts.0001_initial... OK

Yes, this is done. Thank you very much.

A little operation is required to check on the management screen, but I will omit it here.

Pass through

If you do not pass the path, the code you wrote will not be displayed in the browser. There are other settings as well, so let's do it first.

mysite/setting.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #Additional part from here
    'posts',
    'templates',
]

After creating the application, add it to ʻINSTALLED_APPS`.

settings.py


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        #↓ Add one line here
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Tell python that you created the templates directory.

Also, I will write a little views.py and html to check the operation.

posts/views.py


from django.shortcuts import render

# Create your views here.
from django.views.generic import View


class IndexView(View):
    def get(self,request, *args, **kwargs):
        return render(request, 'posts/post.html')


index = IndexView.as_view()

templates/base.html


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{% block page_title %}{% endblock %}</title>
</head>
<body>
<hr>
<h1>{% block title %}{% endblock %}</h1>
<hr>
{% block content%}{% endblock %}
<hr>
</body>
</html>

templates/posts/post.html


{% extends "base.html" %}
{% block page_title %}post{% endblock %}
{% block title %}post{% endblock %}
{% block content %}
    <h1>Posts</h1>
{% endblock %}

Usually, base.html is used as the base of all pages, and post.html and others fill in the contents. Next, I will finally write ʻurls.py`.

mysite/urls.py


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('posts.urls')),
]

posts/urls.py


from django.urls import path
from . import views

app_name = 'posts'
urlpatterns = [
    path('', views.index, name='index'),
]

If you make a call like this, start a local server and check it.

$python manage.py runserver 3000

Then type localhost: 3000 on Google or something.

スクリーンショット 2019-11-04 21.39.07.png

If it comes out like this, the pass relationship is complete. Let's write the code of the bulletin board application from the next.

Recommended Posts

Build a bulletin board app from scratch with Django. (Part 2)
Build a bulletin board app from scratch with Django. (Part 3)
Django starting from scratch (part: 2)
Django starting from scratch (part: 1)
Build a web application with Django
Create a Todo app with Django ① Build an environment with Docker
How to develop a cart app with Django
Create a game UI from scratch with pygame2!
[Python] Build a Django development environment with Docker
Build a Django environment with Vagrant in 5 minutes
Create a bulletin board with Heroku, Flask, SQLAlchemy
Build a Django development environment with Doker Toolbox
Quickly build a Python Django environment with IntelliJ
Let's make a nervous breakdown app with Vue.js and Django-Rest-Framework [Part 1] ~ Django setup ~
Django memo # 1 from scratch
Create a Todo app with Django REST Framework + Angular
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
Deploy a Django app made with PTVS on Azure
Create a Todo app with Django ⑤ Create a task editing function
Build a development environment with Poetry Django Docker Pycharm
Build a Django environment for Win10 (with virtual space)
Create a machine learning environment from scratch with Winsows 10
Try to build a deep learning / neural network with scratch
Build a Django development environment with Docker! (Docker-compose / Django / postgreSQL / nginx)
[Memo] Build a development environment for Django + Nuxt.js with Docker
Create a homepage with django
[Django] Build a Django container (Docker) development environment quickly with PyCharm
Deploy Django + React from scratch to GKE (3) Create a GCP project
# 3 Build a Python (Django) environment on AWS EC2 instance (ubuntu18.04) part2
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Make a scraping app with Python + Django + AWS and change jobs
[DynamoDB] [Docker] Build a development environment for DynamoDB and Django with docker-compose
Test Driven Development with Django Part 4
Play with a turtle with turtle graphics (Part 1)
Test Driven Development with Django Part 6
Deploy a Django application with Docker
Test Driven Development with Django Part 2
Implement a Django app on Hy
App installed from Windows10 32-bit scratch
Creating a simple app with flask
Make a filter with a django template
Test Driven Development with Django Part 1
Post bulletin board creation with flask
Test Driven Development with Django Part 5
Create a file uploader with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
Throw GQL with a numeric ID from the App Engine management screen
Web App Development Practice: Create a Shift Creation Page with Django! (Introduction)
I tried to send a registration completion email from Gmail with django.
Create a Todo app with Django ④ Implement folder and task creation functions
Build a "Deep learning from scratch" learning environment on Cloud9 (jupyter miniconda python3)
I made a webAPI! Build environment from Django Rest Framework 1 on EC2
Steps to build a Django environment with Win10 WSL Ubuntu18.04 + Anaconda + Apache2
A simple RSS reader made with Django
Easily build a development environment with Laragon
Build a blockchain with Python ① Create a class
Play like a web app with ipywidgets
Build a Tensorflow environment with Raspberry Pi [2020]