Views
- The logic is executed for different different urls.
- Prepare and return response data (eg. HTML).
1. HTTP Response
- It is a response to the user. It can be a string, a file, an image, etc.
views.py
# HttpResponse give the response to the user
from django.http import HttpResponse
def index(request):
# write your business logic
return HttpResponse("Hello, World!")
request
: It is the first parameter.HttpResponse
: It is a response to the user.
These are the basic views in Django. You can also use render
to render the template.
2. Rendering Template
from django.shortcuts import render # It import the templates file like index.html and renders it to the user.
def index(request):
params = {'name': 'Harry', 'place': 'Mars'}
# pass the dictionary as a third variable
return render(request, 'index.html', params)
request
: It is the first parameter.index.html
: An html file that you want to render.params
: It takes the dictionary as a third parameter.
- You can access key value pairs in
html
file by -
Dictionary can be access in template :
# Variables params accessing from view.py
<p>My name is {{ name }} and I'm from {{ place }}.</p>