[PYTHON] (For myself) Django_1 (Basic / Hello World / Template)

item

  1. Create a Django project
  2. Specifying the server address
  3. Try running Django
  4. Hello World
  5. Template (html) call
  6. Data transfer from py side to template

1. Make a project

--Project = Unit that organizes applications ――I think it's better to create an application for each function of APP and finally put it together in a stupid project. --As for environment construction, it may or may not be written at a later date even though it looks like Django_environment construction.

Terminal


#Check only the Django version once
$ python -m django --version

#Create a project called myapp, and put in startproject to prepare the contents of the project to some extent
$ django-admin startproject myapp

――This creates a directory called myapp in the directory you were in. --Contents of myapp --manage.py: Name as it is used to run and manage this project --myapp (There is another myapp in myapp) --__init__.py: Declare to use Python in this directory --ʻAsgi.py: It seems to be the starting point when connecting to an ASGI compatible server, I'm not sure --settings.py: You can play with the project settings by editing here. --ʻUrls.py: Decide which def to run when connecting here -- wsgi.py: I have no idea what the starting point is when connecting to a WSGI compatible server. --You can make the stupid big project mentioned above by start project

2. Specifying the server address

--I will tell you which address to connect to from the server

settings.py


#Find out here and enter the address of your page

# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = True

ALLOWED_HOSTS = ["My address"]

3. Try running Django

Terminal


#Go to myapp
$ cd myapp

#Run Django's server
$ python manage.py runserver

--Success if you access https: // localhost: 8000 / and the rocket comes out --Needless to say, the end of execution is Ctrl + c

4.Hello World --Project = A collection of many applications

Terminal


#Myapp made above(Stupid big project)Move to
$ cd myapp

#Declare to create an application in myapp and create an application with startapp
#It is prepared to some extent in the application created without exception
$ python manage.py startapp hello

myapp


myapp
┣━ hello
┣━ manage.py
┗━ myapp

――A directory like this is created --The contents of hello are OK if you are only aware of views.py for the time being --views.py is the same place to write backend movements, Flask's py file

views.py


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

def index(request):
    return HttpResponse('Hello World')

--ʻIndex (request) returns the value contained in HttpResponse () when this function is requested --It's OK if you remember to return the contents of HttpResponse when request method` is done

myapp/myapp/urls.py


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

urlpatterns = [
    path('hello/', include('hello.urls')),
    path('admin/', admin.site.urls),
]

-** Project routing ** --Set which application to run at this pass --Here, when the end of the link is / hello, it says to run the hello application. --Django's flow --Project routing-> App routing (specify the function to run)-> The specified operation is executed --Create a file called ʻurls.pyinhello`

myapp/hello/urls.py


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

-** Application Routing ** --path ('', views.index, name ='index'), indicates which function in which file works in which case. --'' specifies the address, this time there is nothing, so it works with / hello.
If you put something in it, it will work with an address like / hello / ~~. I sometimes put something like <int: question_id> / here, but it's a little difficult so I'll omit it. --Declared in views.index to run the function ʻindex of views ――For the time being, attribute the movement withname ='index'`.

myapp/myapp/settings.py


#Find here and add!
INSTALLED_APPS = [
    'hello.apps.HelloConfig', #Add this!
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

--Set which class to refer to --If the application name is bbs, write it like bbs.apps.BbsConfig --For this BbsConfig, paste the part that says class ~~ Config from ʻapps.py` of the application.

Terminal


#Go back to your project directory...
$ cd myapp

#Launch Django!
$ python manage.py runserver

--It's unpleasantly complicated compared to Flask ...

5. Template (html) call

--Call template (html) from views.py and use --For templates, create a directory called templates directly under the application, create an application name directory in it, and place the template in it. --Like Flask, it seems to react only to the contents of templates

myapp/hello/views.py


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

def index(request):
    return render(request, 'hello/index.html')

--html can be specified by putting PATH in return render () --Since this PATH must be in the templates directory described later, omit up to templates and specify ʻindex.html in hellointemplate`.

index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <p>Hello WoWWoW</p>
</body>
</html>

--ʻIndex.htmlmay be written normally for the time being --Complete ifHello WoWWoW` is displayed in the execution result

6. Data transfer from py side to template

views.py


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

def index(request):
    context = {
        'message': 'Hello World',
        'players': ['Brave', 'Warrior', 'Wizard', 'Ninja']
    }
    enemy = "Slime"
    return render(request, 'hello/index.html', context ,enemy)

--Put what you want to pass like this in return render () --There is a trick to put what you pass in like context = {~~} and put only one context in the place of return.

(templates)/hello/index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <p>{{ message }}</p>
        {% for player in players %}
            <p>{{ player }}Fought a monster</p>
        {% endfor %}
    <p>{{ enemy }}</p>
</body>
</html>

--By putting the variable name in {{~~}}, you can pass the contents written on the py side. --I wrote it in Flask, but when I want to use python on the html side, I write it in {% ~~%} --For For and if statements, you must close with {% endfor%} -↑ For detailed explanation here, the template items around Flask_2,3 may be detailed.

7. At the end

――It's too much trouble compared to Flask!

Recommended Posts

(For myself) Django_1 (Basic / Hello World / Template)
Hello World on Django
To myself as a Django beginner (3)-Hello world! ---
Hello World (beginners) on Django
[Note] [For myself] Django command
Python #Hello World for super beginners
Django # 2 (template)
Hello world
Hello world instead of localhost in Django
Write a short if-else for Django Template
python [for myself]
Django HTML Template # 2
Pymacs hello world
Django 1.9 for internationalization
Django Template notes
Django Template Tips
Create a one-file hello world application with django
cython hello world
Django template file organization
web2py memo: Hello World
FX_tool for Hython Basic02
hello world with ctypes
RabbitMQ Tutorial 1 ("Hello World!")
[Django series] Basic commands
heroku memo (for myself)
Hello, World with Docker
Django's first Hello World
Hello world with flask
FX_tool for Hython Basic01
Freecad memorandum (for myself)
(For myself) Flask_6 (Open db from python, Mysql basic (phpMyAdmin))