[PYTHON] Steps from installing Django to displaying an html page

What to write here:

In this article, I'm writing about "Installing Django-> Steps to display the html page".

Also, the writing environment is OS: macOS Catalina version 10.15.4 Python:3.7.6 Django:3.0.3 It has become.

What is Django in the first place?

Django is one of the web application frameworks using Python, and you can create various web applications. One of the features is that it has abundant functions, and you can reduce the burden of developing web applications by using the components included in Django. For example, user authentication and administrator screens can be implemented using Django. You can also execute the processing of the web application in Python.

Django installation

It depends on the environment, but basically any OS

$ pip install django

I think you can install it with. I won't explain the detailed installation method here, so please see other people's pages such as Install Django with Python3 and display HelloWold. I hope you can refer to it.

Create a project and run it

After the installation is complete, try creating a project. After moving to any directory,

$ django-admin startproject <Project name>

You can create a django project in that directory with. You can set any name you like for the part, but you can only use letters, numbers, and underscores.

Once the project is created, go to that project and

$ python manage.py migrate
$ python manage.py runserver

I think that the server will be started by executing. The first line

python manage.py migrate


 Is a command to apply the contents of the migration file to the model, and the command to start the server is the second line.

#### **`python manage.py runserver`**
```py runserver

 is.
 I think that the address http: // ~~~ will be displayed on the terminal, so if you access that address with a browser and the following image is displayed, it is working properly.
 <img width="1008" alt="スクリーンショット 2020-05-29 23.47.32.png " src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/515612/ae2d0607-770d-8f65-28a2-e7a2cc6a72d3.png ">
 You can stop the server by typing Ctrl + C on the terminal.

# Display html page
 Next, let's move on to how to display your own html page using Django.
### Directory preparation
 Currently, the structure of the created project is

- db.sqlite3 - manage.py - - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - __pycashe__ - (.Multiple pyc files) ``` I think it is. In this state, first create folders named ``` templates``` and `` `static` ``. The templates folder is for html files, and the static folder is for css and js files. Then at the terminal
$ django-admin startapp <app name>

Please execute to create an app (the part can be any name). At this time, if a file named urls.py has not been created in the folder, create a python file named urls.py manually. The directory is

<Project name>
- db.sqlite3
- manage.py
- <Project name>
  - __init__.py
  - asgi.py
  - settings.py
  - urls.py
  - wsgi.py
  - __pycashe__
    - (.Multiple pyc files)
- <app name>
  - __init__.py
  - admin.py
  - apps.py
  - models.py
  - tests.py
  - urls.py
  - views.py
  - migrations
    - __init__.py
- templates
- static

If it is, it is OK.

Preparation of each file

When the directory is ready, put the html, css, js files. Place the html file in the templates folder and the css and js files in the static folder. If you have already prepared the file, leave it in the specified location, if you do not have the file, the html file named index.html as shown below, and the contents can be empty, so it is called style.css and script.js Create each file with a name and put the created file in the same location.

index.html


{% load static %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>HTML</title>
    <link rel='stylesheet' type='text/css' href="{% static 'style.css' %}"/>
    <script type="text/javascript" src="{% static 'script.js' %}"></script>
  </head>
    
  <body>
    Hello!!
  </body>
</html>

As a caveat here -Write `{% load static%}` at the top of the html file -When reading a css or js file with html, specify the file as `{% static'<name of the file you want to read>'%}" ` Please note in particular. This is a description for accessing the files in the static folder. If you prepared your own html file, please change this part as well.

Editing python files

When the file is ready, edit each python file and set it so that the html file can be read. To edit

<Project name>/settings.py



#### **`<Project name>/urls.py`**
```py


#### **`<app name>/urls.py`**
```py


#### **`<app name>/views.py`**
```py

 There are four.

 ** <project name> /settings.py**


#### **`Project name/settings.py`**
```py

...
#ALLOWED to remove access restrictions_Make HOSTS as follows.
#However, it is not good to make it fully open from the viewpoint of security, so specify the IP address in detail according to the purpose.
ALLOWED_HOSTS = ["*"]

...

INSTALLED_APPS = [
    ...,
   '<app name>'  # INSTALLED_To APPS'<app name>'Is added.
]
...

TEMPLATES = [
  {
    ...
    #Change the DIRS part of TEMPLATES as follows.
    'DIRS': [
      os.path.join(BASE_DIR, 'templates'),
    ],
    ...
]
...

# LANGUAGE_CODE and TIME_Change ZONE as follows.
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'

...

#Add the following
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

** /urls.py **

Project name/urls.py


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

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'', include('<app name>.urls')), #Add here
]

** /urls.py **

app name/urls.py


from django.urls import path
from . import views

app_name = '<app name>'
urlpatterns = [
    path(r'', views.index, name='index'),
]

** /views.py **

app name/views.py


from django.shortcuts import render

# Create your views here.
#Add the following
def index(req):
    return render(req, 'index.html')

Display html

After completing the above preparations, you should be able to display the prepared html file by starting the server.

$ python manage.py runserver

Is executed on the terminal, access the displayed address from the browser, and it is OK if the contents of index.html are displayed.

The page that I used as a reference

Django Girls Tutorial Install Django with Python3 and view HelloWold

Recommended Posts