Create a web application called Hello World App and display "Hello World".
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
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
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.
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
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.
Now you are ready to display Hello, World! On your website. All you have to do is start the server.
$ python manage.py runserver
Next time, I'll do more about Pages App.
Django for Beginners 3.0
Recommended Posts