2 -Django View
2 -Django View
1
Django View
# create a function
def geeks_view(request):
# fetch date and time
now = datetime.datetime.now()
# convert to string
html = "Time is {}".format(now)
# return response
return HttpResponse(html) 4
Django View Example
5
Django View Example
urlpatterns = [
path('', geeks_view),
]
6
Now, visit http://127.0.0.1:8000/
7
Types of Views
Django views are divided into two major categories :-
8
Function Based Views
9
Function based view Example
Let’s Create a function based view list view to display instances
of a model.
let’s create a model of which we will be creating instances
through our view. In lms/models.py
def list_view(request):
# dictionary for initial data with
# field names as keys
context ={}
# add the dictionary during initialization
context["dataset"] = GeeksModel.objects.all()
return render(request, "list_view.html", context)
10
Function based view Example
Now let’s create some instances of this model using shell, run
form bash
11
Function based view Example
12
Function based view Example
13
Function based view Example
Let’s create a view and template for the same. In lms/views.py
def list_view(request):
# dictionary for initial data with
# field names as keys
context ={}
# add the dictionary during initialization
context["dataset"] = GktcsModel.objects.all()
<div class="main">
{{ data.title }}<br/>
{{ data.description }}<br/>
<hr/>
{% endfor %}
</div>
15
Function based view Example
16
Class Based Views
17
Class based views are simpler and efficient to manage than
function-based views. A function based view with tons of
lines of code can be converted into a class based views with
few lines only. This is where Object Oriented Programming
comes into impact.
18
Class based view Example
In lms/views.py
class GktcsList(ListView):
19
Class based view Example
urlpatterns = [
path('', GktcsList.as_view()),
]
20
Class based view Example
Create a template in templates/lms/gktcsmodel_list.html,
<ul>
<!-- Iterate over object_list -->
{% for object in object_list %}
<!-- Display Objects -->
<li>{{ object.title }}</li>
<li>{{ object.description }}</li>
<hr/>
<!-- If objet_list is empty -->
{% empty %}
<li>No objects yet.</li>
{% endfor %}
</ul>
21
Class based view Example
Let’s check what is there on http://localhost:8000/
22