A super introduction to Django by Python beginners! Part 1 I tried to display an HTML page that only says "Hello World"

background purpose

I learned Django in an online course called Udemy. This article is an output page that also serves as a memorandum. I will try to write it in an easy-to-understand manner from a beginner's point of view. The following two courses were used as reference. Both were very good courses that were difficult to attach.

Safe for beginners in programming, Python / Django introductory course [Python 3 x Django 2.0] Learn while making Django

What is Django? Why Django?

Quite simply, it's like a toolbox that brings together what Python genius programmers need so that even novice programmers like themselves can easily build a website. To put it coolly, it's called a web framework.

In addition to Django, there are web frameworks made with JavaScript, Ruby, etc., and it seems that they are better as of 2020 in terms of share rate. However, in my case, I use Python as a hobby, and the cost of learning basic knowledge is low, so I chose Django.

Try to create a virtual environment (for Windows 10 machine)

First, create a virtual environment. If you create this, it will be an independent environment, so by adding the library later, you will not have the foolish situation that "it worked before, but it worked". Machine learning libraries often fall into this situation, so let's do it properly. You can easily switch back.

Start PowerShell or a command prompt. The virtual environment is created with "virtualenv". If it is not installed, install it with the following command.

> py -m pip install virtualenv

Once installed, let's build a virtual environment. Build with an environment name named venv.

> py -m virtualenv venv

Let's log in to the created virtual environment. After moving to the venv folder, type the following command to enter the virtual environment.

> \Scripts\activate

Django installation and initialization

After entering the virtual environment, install Django.

> pip install django

Once Django is installed, create a project.

A project is a toolbox created by the genius Python programmers mentioned earlier. It's packed with everything you need to build a web server.

Thank you very much, but until you get used to this folder structure, it's quite esoteric and confusing. I will write in detail which file you are editing as carefully as possible.

Let's create a project named "first".

> django-admin startproject first

A folder called first will be created, so go to the first folder. After moving, create a web application.

> py manage.py startapp myapp

This will create a new folder called myapp. I think it has the following tree structure. Under the first project folder, there is another first folder, You might think, "Huh?", But if this happens, it's a success. image.png Next, there is settings.py directly under first \ first. Let's open it.

first\fisrt\settings.py


INSTALLED_APPS = [
    "...",
    "first", # <-Postscript
]

Now I can tell Django that there is an app called first. Scroll down further and modify LANGUAGE_CODE and TIME_ZONE as follows:

first\fisrt\settings.py


LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'

LANGUAGE_CODE means Japanese and TIME_ZONE means Japanese time. This completes the settings in settings.py. Overwrite and save and close.

Editing urls.py

Then edit urls.py. As the name suggests, it is a file for name resolution of the URL entered from the browser. Open first \ first \ urls.py ↓ image.png

After opening the file, write as follows.

first\first\urls.py


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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')) # <-Postscript
]

This will tell you to go to urls.py directly under myapp if you see myapp in the URL. By doing this, even if the number of apps in the same project increases in the future, it will be easier to understand because the URLs will not be scattered in the url patterns.

Next, open the myapp folder and create a new urls.py.

first\myapp\urls.py


from django.urls import path
from . import views

app_name = 'myapp'

urlpatterns = [
    path('', views.index, name='index'),
    path('test/', views.test_index, name='testindex')
]

Import views.py with from .import views. `ʻapp_name ='myapp'means name resolution for the URL of myapp. In urlpatterns, describe the processing for the URL that follows myapp. path ('', views.index, name ='index') is the processing when the URL myapp / comes. path ('test /', views.test_index, name ='testindex') is the processing when the URL myapp / test`` comes.

I haven't edited views.py yet, so I think the image is hard to understand, but When the URL myapp / comes in, the function ```indexin views.py is executed. When the URL myapp / testcomes, the function of test_index`` is executed.

This function name is arbitrary. This completes the editing of urls.py. Next, let's edit views.py.

Edit views.py

Let's create the index and test_index functions specified in urls.py earlier. views.py is stored below. image.png Open views.py and write as follows.

first\myapp\views.py


from django.http import HttpResponse

def index(request):
    return HttpResponse("hello world")

def test_index(request):
    return HttpResponse("test")

def index is a function that just returns "hello world" when views.index receives a request. def test_index is a function that just returns "test" when views.test_index receives a request.

This completes editing views.py. Let's finally start the development server.

Start the development server

The development server is started with PowerShell. Please move to directly under the project folder you created first. Make sure that manage.py is directly below it. image.png Then execute the following command.

py manage.py runserber

When started, the following result will be displayed. If you get an error, there may be something wrong with the procedure so far. image.png

http://127.0.0.1:8000/myapp and <a href="http://127.0.0.1:" in your internet browser Make sure you can successfully access 8000 / myapp / test "> http://127.0.0.1:8000/myapp/test .

I think that hello world is displayed safely. image.png

Next article

The next article is below. https://qiita.com/sw1394/items/903397960d7164ff31ac

Recommended Posts

A super introduction to Django by Python beginners! Part 1 I tried to display an HTML page that only says "Hello World"
A super introduction to Django by Python beginners! Part 3 I tried using the template file inheritance function
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
A super introduction to Django by Python beginners! Part 5 I made a super simple diary application with a class-based general-purpose view
A super introduction to Django by Python beginners! Part 4 I made a super-simple diary application (created only with functions without using a class-based general-purpose view)
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 5/22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part7 / 22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 4/22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part3 / 22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 1/22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 6/22]
A story that I wanted to display the division result (%) on HTML with an application using django [Beginner learns python with a reference book in one hand]
An introduction to Python that even monkeys can understand (Part 3)
An introduction to Python that even monkeys can understand (Part 1)
An introduction to Python that even monkeys can understand (Part 2)
[Python] I tried to explain words that are difficult for beginners to understand in an easy-to-understand manner.
I tried to make a system that fetches only deleted tweets
[Introduction to simulation] I tried playing by simulating corona infection ♬ Part 2
[Python] A memo that I tried to get started with asyncio
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
Python #Hello World for super beginners
Introduction to Ansible Part 1'Hello World !!'
I tried to communicate with a remote server by Socket communication with Python.
I made a web application in Python that converts Markdown to HTML
I tried to develop a Formatter that outputs Python logs in JSON
I want to color a part of an Excel string in Python
A super introduction to Python bit operations
How to display Hello world in python
Introduction to AI creation with Python! Part 3 I tried to classify and predict images with a convolutional neural network (CNN)
Introduction to AI creation with Python! Part 2 I tried to predict the house price in Boston with a neural network
I tried to create a class that can easily serialize Json in Python
[Python] I tried to make a Shiritori AI that enhances vocabulary through battles
[Introduction to Docker] I tried to summarize various Docker knowledge obtained by studying (Windows / Python)
An introduction to object-oriented programming for beginners by beginners
I tried to get an image by scraping
To myself as a Django beginner (3)-Hello world! ---
[Python + Bottle] I tried to release a web service that visualizes Twitter's positioned tweets.
I wrote a class that makes it easier to divide by specifying part of speech when using Mecab in python
Steps from installing Django to displaying an html page
I tried to draw a route map with Python
I tried to implement a pseudo pachislot in Python
I tried to implement an artificial perceptron with python
I tried to automatically generate a password with Python3
Python: I tried a liar and an honest tribe
[Python] I tried to make an application that calculates salary according to working hours with tkinter
[1 hour challenge] I tried to make a fortune-telling site that is too suitable with Python
I tried to create a RESTful API by connecting the explosive Python framework FastAPI to MySQL.
I tried to make a generator that generates a C # container class from CSV with Python
I tried to summarize the languages that beginners should learn from now on by purpose