Getting Started with Django 2

Try to display "Hello World" on the Web

Create a web application called Hello World App and display "Hello World".

Initial setting

First, move to an arbitrary directory, create a directory named helloworld (anything is fine), and move to that directory. Then enter the virtual environment and execute the following command to create a new Django project.

$ django-admin startproject helloworld_project .
# django-admin.py:Script to create the directories and files needed for a new project
# helloworld_progect:Anything is fine as it is a project name

The helloworld_project directory is created. The following files exist in the directory.

├── helloworld
    ├── manage.py          #A command line utility for performing various operations on your Django project.
    ├── helloworld_project
        ├── __init__.py    #An empty file to let Python know that this directory is a Python package
        ├── asgi.py        #The entry point of the ASGI compatible web server that provides the project
        ├── settings.py    #Control project settings
        ├── urls.py        #urlresolver(Mechanism to find the view corresponding to the url received in the request)Contains a list of patterns used in.
        └── wsgi.py        #wsgi:A definition of a common interface that connects a server and a web application

Creating an app

Add and create app (function) to a new project called helloworld_project. When you hear the word app, you tend to think of something like LINE, Twitter, or Instagram, but in Django, app refers to a function. Many functions cooperate with each other to create LINE. A Django project contains one or more apps and works together to provide services. For example, on an e-commerce site --User authentication --Payment --Product display

New app

First, if the server is running, stop it with Control + c. Run the following command to create an app named "pages".

$ python manage.py startapp pages

This will create the / helloworld / pages directory.

├── pages
    ├── __init__.py      
    ├── admin.py        #Configuration file in admin
    ├── apps.py         #The configuration file of the app itself called pages
    ├── migrations      #model.Save the change history of the py file, database and models.Directory for storing files to keep py in sync
    │   └── __init__.py
    ├── models.py       #Model file of app. A file that defines a database model.
    ├── tests.py        #app test file
    └── views.py        #View file of app. A file that processes requests and responses to the app.

I created an app called pages in a Django project (hello world), but Django still doesn't know if pages are apps or what. I have to tell Django to use an app called pages. If you open helloworld_project / settings.py, you will find the following parts.

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

These are the Django apps that exist by default. You can only add your own app to your Django project by adding pages here. Add the following line.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pages.apps.PagesConfig', # new
]

You should always add your own app at the bottom. This is because Django runs the INSTALLED_APPS settings from top to bottom. You have to load the admin app first, then auth, then .... The reason is that most of the self-made apps depend on functions such as admi.

Edit view

Next, add the code to display the character string in views.py.

pages/views.py


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

def homePageView(request):
    return HttpResponse('Hello, World!')
    #When a function called homePgeView receives a request, it calls a function called HttpResponse and returns the obtained value.
    #This time'Hello, World!'It returns a response that displays the character string.

In the first place, a view requests information such as data from a model (model.py). The model then passes the requested data to the view to the template. In other words, the view (view.py) is a Python function that receives a request and returns a response.

--Response: Can be HTML content for web pages, redirects, 404 errors, XML documents, whatever

** Note that the view (view.py) basically has to return an HttpResponse object. (There are exceptions) **

Django uses request and response objects to pass processing state throughout the system. When you receive a request for a page, Django creates an HttpRequest object. This object contains the request metadata. Django then loads the appropriate view and passes HttpRequest as the first argument to the view function. Each view must return an HttpResponse object. https://djangoproject.jp/doc/ja/1.0/ref/request-response.html

URL settings

Next is the URL setting. From now on, you will be touching two (①, ②) urls.py files, so let's do our best while being aware of the differences.

① Create a file called pages / urls.py. (** Note the current directory. In the pages directory. **) Please add the following code.

pages/urls.py


from django.urls import path
from .views import homePageView

urlpatterns = [
    path('', homePageView, name='home')
]
#Django is the domain name of the URL(http://127.0.0.1:8000/Part of)Is ignored, so this URL pattern is an empty string('')Matches

The code above means that if you access the address 127.0.0.1:8000 (the address of the first page), you should call the view function homePageView. name ='home' is the name of the URL used to identify the view. You will have the opportunity to use the name of this URL in the future, so if you give it a unique name that is easy to remember, you will not be confused.

② A file called helloworld_progect / urls.py should be created by default. Add the following code here.

helloworld_project/urls.py


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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('pages.urls')), #new
]
#Similar to ①, the URL pattern is an empty string('')Specify in http://127.0.0.1:8000/The address of only the domain is used as the entrance page.

Import the include function to import pages.urls. In path () that specifies'admin /', when the URL is "admin /", the management screen (admin.site.urls) is returned (displayed in the browser). The management screen is a page where you can operate the app with a browser. Django will redirect requests that come to the entry page to pages.urls. In other words, when the entrance page is accessed, the homePageView function of pages.urls is automatically executed.

Hello World completed

Now you are ready to display Hello, World! On your website. All you have to do is start the server.

$ python manage.py runserver
Screen Shot 2020-03-26 at 10.45.38.png

Next time, I'll do more about Pages App.

Reference material

Django for Beginners 3.0

Recommended Posts

Getting Started with Django 2
Getting Started with Python Django (1)
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Getting Started with Django with PyCharm
Getting Started with Python Django (5)
Django 1.11 started with Python3.6
Getting started with Android!
1.1 Getting Started with Python
Getting Started with Golang 2
Getting started with apache2
Getting Started with Golang 1
Getting Started with Python
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Python
Getting Started with Pydantic
Getting Started with Golang 4
Translate Getting Started With TensorFlow
Getting Started with Python Functions
Getting Started with Tkinter 2: Buttons
Get started with Django! ~ Tutorial ⑤ ~
Getting Started with Go Assembly
Getting Started with PKI with Golang ―― 4
Django Getting Started: 2_ Project Creation
Django Getting Started: 4_MySQL Integration
Django Getting Started: 3_Apache integration
Get started with Django! ~ Tutorial ④ ~
Django Getting Started Part 2 with eclipse Plugin (PyDev)
Python3 | Getting Started with numpy
Getting Started with Python responder v2
Getting Started with Git (1) History Storage
Getting Started with Python Web Applications
Getting Started with Python for PHPer-Classes
Getting Started with Sparse Matrix with scipy.sparse
Getting Started with Julia for Pythonista
Getting Started with Python Basics of Python
Getting Started with Cisco Spark REST-API
Getting started with USD on Windows
Getting Started with Python Genetic Algorithms
Getting Started with Python for PHPer-Functions
Getting Started with CPU Steal Time
Internationalization with django
Grails getting started
Step notes to get started with django
Getting Started with python3 # 1 Learn Basic Knowledge
Getting Started with Flask with Azure Web Apps
Getting Started with Python Web Scraping Practice
Getting Started with Python for PHPer-Super Basics
Getting Started with Python Web Scraping Practice
Getting started with Dynamo from Python boto
Getting Started with Lisp for Pythonista: Supplement
Getting Started with Heroku, Deploying Flask App
Getting Started with TDD with Cyber-dojo at MobPro
Getting Started with Heroku-Viewing Hello World in Python Django with Raspberry PI 3
Authenticate Google with Django
Getting started with Python with 100 knocks on language processing
Upload files with Django
Development digest with Django