(Python) Try to develop a web application using Django

Introduction

I would like to see the execution result of the API in HTML. So, first I ran the API on localhost and checked if the result could be displayed in HTML in the browser. As a result, I was told to study Django, so I'll try it for the time being.

Django Let's take a quick look at Django.

--A full stack framework written in Python. ――You have everything you need. --The template doesn't bring that, and the DB access doesn't bring that. --There are modules to extend, but the basics are just Django.

--ORM --Object Relational Mapping The object relational mapping is excellent. --Low learning cost --Raw HTML, Javascript, and CSS are the basics, but it's a simple web framework to choose first.

Development flow

Since this is my first development using Django, I will create a book list as a sample application. Development will proceed according to the following flow.

  1. Install Django and create a project.
  2. Set up the database.
  3. Start the development server.
  4. Create an application.
  5. Install Bootstrap.
  6. Create views and URL schemes.
  7. Create HTML.

environment

The execution environment is as follows

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.1
BuildVersion:   19B88

$ python --version
Python 3.7.4

Use venv as a virtual development environment.

1. Install Django and create a project

I want to use the stable version this time, so specify the version and install it.

$ pip install django==2.1.5

Then create a project. This time, create a project called mybook.

$ django-admin.py startproject mybook

A project is created with the following configuration.

mybook/
    manage.py
    mybook/
        __init__.py
        settings.py
        urls.py
        wsgi.py

Now move to the mybook directory.

$ cd mybook

2. Set up the database

Database settings can be made in mybook / settings.py. This time, use the default setting SQlite3.

settings.py


# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    :

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

When you enter the command to migrate the database, a file called db.sqlite3 is created in the directory directly under the project.

$ python manage.py migrate

At the same time, create a super user.

$ python manage.py createsuperuser
Username (leave blank to use 'hoge'): admin
Email address: [email protected]
Password: hogefuga
Password (again): hogefuga
Superuser created successfully.

On the way, answer the following questions.

--Username: admin --Email address: [email protected] * Appropriate --Password: hogefuga --Password (re-enter): hogefuga

3. Start the development server

Start the development server with the command python manage.py runserver and check if the project works.

$ python manage.py runserver

Go to http://127.0.0.1:8000/ with your browser. スクリーンショット 2019-12-29 20.04.26.png Quit the development server with control + c.

4. Create an application

Create an application called cms under the project. Create with the following command.

$ python manage.py startapp cms

The following files are created under the directory of the mybook project.

mybook/
    cms/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py
    manage.py
    mybook/
       :
       :

Define the data model you want to define in the database in cms / models.py.

models.py


from django.db import models


class Book(models.Model):
    """Books"""
    name = models.CharField('Book title', max_length=255)
    publisher = models.CharField('the publisher', max_length=255, blank=True)
    page = models.IntegerField('number of pages', blank=True, default=0)

    def __str__(self):
        return self.name

Add cms to the end of INSTALLED_APPS in mybook / settings.py.

settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cms',  #add to

]

Use the following command to pick up the changes in models.py and create a migrate file.

$ python manage.py sqlmigrate cms 0001

Use the following command to reflect the migrate file that has not been reflected in the database to the database.

python manage.py migrate cms

At this point, the database is ready.

5. Introduce Bootstrap

From here, we will create with Foron. This time, I'll use Bootstrap, a CSS framework. Download it from the following, including the jQuery required by Bootstrap.

Create a directory called mybook / cms / static / cms / and place the downloaded file as follows.

mybook
└── cms
    └── static
        └── cms
            ├── css
            │   ├── bootstrap.min.css
            │   └── bootstrap.min.css.map
            └── js
                ├── bootstrap.bundle.min.js
                ├── bootstrap.bundle.min.js.map
                └── jquery-3.4.1.min.js

6. Create views and URL schemes

We need a list function, so create it in cms / views.py.

views.py


from django.shortcuts import render
from django.http import HttpResponse


def book_list(request):
    """List of books"""
    books = Book.objects.all().order_by('id')
    return render(request,
                  'cms/book_list.html',     #Template to use
                  {'books': books})         #Data to pass to the template

Then create a URL scheme. The file cms / urls.py does not exist, so create a new one. In this, the URL and the function of the view are linked.

cms/urls.py


from django.urls import path
from cms import views

app_name = 'cms'
urlpatterns = [
    #Books
    path('book/', views.book_list, name='book_list'),   #List
]

Then include cms / urls.py in mybook / urls.py for the entire project.

mybook/urls.py


from django.contrib import admin
from django.urls import path, include   # ←,add include

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

The final URL looks like this:

http://127.0.0.1:8000/cms/book/

7. Create HTML

Create a template called book_list.html for use in the cms application of your mybook project. First, create a template called base.html that will be the inheritance source.

mybook/cms/templates/cms/base.html

The contents of base.html are as follows.

base.html


{% load i18n static %}
<!DOCTYPE html>{% get_current_language as LANGUAGE_CODE %}
<html lang="{{ LANGUAGE_CODE|default:"en-us" }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="{% static 'cms/css/bootstrap.min.css' %}">
{% block extra_css %}{% endblock %}
<title>{% block title %}My books{% endblock %}</title>
</head>
<body>
  <div class="container">
    {% block content %}
      {{ content }}
    {% endblock %}
  </div>
<script src="{% static 'cms/js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'cms/js/bootstrap.bundle.min.js' %}"></script>
{% block extra_js %}{% endblock %}
</body>
</html>

Now, create mybook / cms / templates / cms / book_list.html by inheriting this base_html.

book_list.html


{% extends "cms/base.html" %}

{% block title %}List of books{% endblock title %}

{% block content %}
    <h4 class="mt-4 border-bottom">List of books</h4>
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th scope="col">ID</th>
          <th scope="col">Book title</th>
          <th scope="col">the publisher</th>
          <th scope="col">number of pages</th>
        </tr>
      </thead>
      <tbody>
        {% for book in books %}
        <tr>
          <th scope="row">{{ book.id }}</th>
          <td>{{ book.name }}</td>
          <td>{{ book.publisher }}</td>
          <td>{{ book.page }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
{% endblock content %}

Check it with your browser. Since there is no data, only the header.

http://127.0.0.1:8000/cms/book/
スクリーンショット 2019-12-29 21.01.09.png

At the end

For the time being, I was able to display HTML. After that, if you can call and execute the API from views.py, you can achieve the purpose. I'm new to the Python framework, and I've been able to get it to display without stumbling.

Recommended Posts

(Python) Try to develop a web application using Django
Steps to develop a web application in Python
Try using the Python web framework Django (1)-From installation to server startup
I want to make a web application using React and Python flask
[ES Lab] I tried to develop a WEB application with Python and Flask ②
WEB application development using Django [Django startup]
WEB application development using Django [Application addition]
Build a web application with Django
Creating a web application using Flask ①
Creating a web application using Flask ③
Creating a web application using Flask ④
If you know Python, you can make a web application with Django
WEB application development using Django [Model definition]
WEB application development using Django [Initial settings]
Try using the web application framework Flask
WEB application development using Django [Request processing]
Try to operate Excel using Python (Xlwings)
WEB application development using Django [Template addition]
[Python] A quick web application with Bottle!
I tried to make a todo application using bottle with python
Run a Python web application with Docker
I made a WEB application with Django
I made a web application in Python that converts Markdown to HTML
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
How to build an application from the cloud using the Django web framework
Implement a simple application with Python full scratch without using a web framework.
Try to calculate a statistical problem in Python
Try using django-import-export to add csv data to django
How to open a web browser from python
Procedure to use TeamGant's WEB API (using python)
How to develop a cart app with Django
WEB application development using Django [Admin screen creation]
Try to draw a life curve with python
Try to make a "cryptanalysis" cipher with Python
Try using the Python web framework Tornado Part 1
Create a web map using Python and GDAL
Try to make a dihedral group with Python
Run a Python file from html using Django
Try using the Python web framework Tornado Part 2
Try Debian + Python 3.4 + django1.7 ...
Try using Django templates.html
Web application using Bottle (1)
Try using Tweepy [Python2.7]
Go beginner tried to create a cloud native web application using Datastore / GAE
[Raspberry Pi] Publish a web application on https using Apache + WSGI + Python Flask
Try to get a web page and JSON file using Python's Requests library
If you want to make a TODO application (distributed) now using only Python
Try to create a Todo management site using WebSocket with Django (Swamp Dragon)
WEB scraping with python and try to make a word cloud from reviews
Try creating a web application with Vue.js and Django (Mac)-(1) Environment construction, application creation
Deploy a Python 3.6 / Django / Postgres web app on Azure
Try to make a Python module in C language
How to set up a Python environment using pyenv
Try creating a compressed file using Python and zlib
Try to make a command standby tool with python
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 1-
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
How to deploy a Django application on Alibaba Cloud
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 2-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 0-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 5-