Setting for the time being. Edit the following file.
--App /views.py --Call the template file from the function (view function) defined in views.py and return the HTTP response.
Contents corresponding to hello for the time being.
python/app_name/views.py
from django.shortcuts import render # render(request, 'hello.html', context)
from django.http import HttpResponse # HttpResponse('Hello, World !!')
from django.shortcuts import render
from django.views import View
class HelloView(View):
def get(self, request, *args, **kwargs):
context = {
'message': "Hello World! from View!!",
}
return render(request, 'hello.html', context)
hello = HelloView.as_view()
A function in which the render function calls a template to generate HTML.
--Write the request of the first argument for the time being. --Specify the template file with the second argument'hello.html'. Specify a relative path under templates / folder. --The third argument context is a dictionary of variables to pass to the template. --You can refer to the value by using the key as the variable name in the template file. --Since flexible variables cannot be added or changed with the template file name, all of them are packed in the basic context.
The last hello = HelloView.as_view ()
is an operation that associates the HelloView class as a hello view function.
This function name corresponds to the function name set in urls.py.
Set the base location for the template file.
The following is set in project folder / templates /
.
config/settings.py
57c58
< 'DIRS': [],
---
> 'DIRS': [os.path.join(BASE_DIR, 'templates')],
Create the directory described in config / settings.py
above
Create a template file in it.
$ mkdir templates
$ vi templates/hello.html
The contents of the template file. This time just display the variable message
.
The detailed writing method is as follows.
The Django Template Language |Django documentation| Django
templates/hello.html
{{ message }}
With a web browser at http: // IP address: 8000 / app_name /
OK if Hello World! From View !!
is displayed
Recommended Posts