generic views in python

In some cases, writing views, as we have seen earlier is really heavy. Imagine you need a static page or a listing page. Django offers an easy way to set those simple views that is called generic views.

Unlike classic views, generic views are classes not functions. Django offers a set of classes for generic views in django.views.generic, and every generic view is one of those classes or a class that inherits from one of them.

There are 10+ generic classes −

>>> import django.views.generic
>>> dir(django.views.generic)

['ArchiveIndexView', 'CreateView', 'DateDetailView', 'DayArchiveView', 
   'DeleteView', 'DetailView', 'FormView', 'GenericViewError', 'ListView', 
   'MonthArchiveView', 'RedirectView', 'TemplateView', 'TodayArchiveView', 
   'UpdateView', 'View', 'WeekArchiveView', 'YearArchiveView', '__builtins__', 
   '__doc__', '__file__', '__name__', '__package__', '__path__', 'base', 'dates', 
   'detail', 'edit', 'list']

This you can use for your generic view. Let's look at some example to see how it works.

Static Pages

Let's publish a static page from the “static.html” template.

Our static.html −

<html>
   <body> 
      This is a static page!!! 
   </body>
</html>

If we did that the way we learned before, we would have to change the myapp/views.py to be −

from django.shortcuts import render

def static(request):
   return render(request, 'static.html', {})

and myapp/urls.py to be −

from django.conf.urls import patterns, url

urlpatterns = patterns("myapp.views", url(r'^static/', 'static', name = 'static'),)

The best way is to use generic views. For that, our myapp/views.py will become −

from django.views.generic import TemplateView

class StaticView(TemplateView):
   template_name = "static.html"

And our myapp/urls.py we will be −

from myapp.views import StaticView
from django.conf.urls import patterns

urlpatterns = patterns("myapp.views", (r'^static/$', StaticView.as_view()),)

When accessing /myapp/static you get −

Static Page

For the same result we can also, do the following −

  • No change in the views.py
  • Change the url.py file to be −
from django.views.generic import TemplateView
from django.conf.urls import patterns, url

urlpatterns = patterns("myapp.views",
   url(r'^static/',TemplateView.as_view(template_name = 'static.html')),)

As you can see, you just need to change the url.py file in the second method.

List and Display Data from DB

We are going to list all entries in our Dreamreal model. Doing so is made easy by using the ListView generic view class. Edit the url.py file and update it as −

from django.views.generic import ListView
from django.conf.urls import patterns, url

urlpatterns = patterns(
   "myapp.views", url(r'^dreamreals/', ListView.as_view(model = Dreamreal, 
      template_name = "dreamreal_list.html")),
)

Important to note at this point is that the variable pass by the generic view to the template is object_list. If you want to name it yourself, you will need to add a context_object_name argument to the as_view method. Then the url.py will become −

from django.views.generic import ListView
from django.conf.urls import patterns, url

urlpatterns = patterns("myapp.views",
   url(r'^dreamreals/', ListView.as_view(
      template_name = "dreamreal_list.html")),
      model = Dreamreal, context_object_name = dreamreals_objects ,)

The associated template will then be −

{% extends "main_template.html" %}
{% block content %}
Dreamreals:<p>
{% for dr in object_list %}
{{dr.name}}</p>
{% endfor %}
{% endblock %}

Accessing /myapp/dreamreals/ will produce the following page −

 

 

##################GENRIC Voews###################
  1. myapp/urls.py
from django.views.generic import TemplateView

  re_path(r'^login/', TemplateView.as_view(template_name = 'loggedin.html'), name = 'login2')

2. http://127.0.0.1:8000/myapp/login/





################################


 

Class based views

myapp/urls.py

path('about/', views.MyView.as_view()), # Class based
path('create/', views.RtiCreate.as_view()),
path('list/', views.RtiList.as_view()),
path('<pk>/detail', views.RtiDetailView.as_view()),
path('<pk>/update',views.RtiUpdateView.as_view()),
path('<id>/delete', views.RtiDeleteView,name="id" ),
path('form', views.RtiFormView.as_view()),

myapp/views.py

 

# For the above code equivalent class based code

from django.views import View

class MyView(View): # Class based
def get(self, request):
# <view logic>
return HttpResponse('result')

from django.views.generic.edit import CreateView
from .models import RTI

class RtiCreate(CreateView): # Create view

# specify the model for create view
model =RTI

# specify the fields to be displayed

fields = ['rti_no', 'rti_label','rti_lrg','rti_dif','rti_symptom','rti_status']

success_url = "/rti/about"

from django.views.generic.list import ListView
from .models import RTI
class RtiList(ListView):
# specify the model for list view
model = RTI

from django.views.generic.detail import DetailView
from .models import RTI

class RtiDetailView(DetailView):
# specify the model to use
model = RTI

from django.views.generic.edit import UpdateView

from .models import RTI

class RtiUpdateView(UpdateView):

# specify the model for create view
model =RTI

# specify the fields to be displayed

fields = ['rti_no', 'rti_label','rti_lrg','rti_dif','rti_symptom']

success_url = "/rti/about"

from django.views.generic.edit import FormView
from .forms import RtiForm

class RtiFormView(FormView):

# specify the model for create view
model =RtiForm

# sepcify name of template
template_name = "rti_form.html"

success_url = "/rti/about"

 

 

myapp/templates/myapp

cat rti_detail.py

<head>

<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
</head>

<body>

<ul>

<table class="table">
<thead>

<tr>
<th scope="col">RTI#</th>
<th scope="col">DIF</th>
<th scope="col">LRG</th>
<th scope="col">SYMPTOM</th>
</tr>
</thead>

 

<tbody>
<!-- Iterate over object_list -->

<!-- Display Objects -->
<tr>

<td>{{ object.rti_no }}</td>
<td>{{ object.rti_dif }}</td>
<td>{{ object.rti_lrg }}</td>
<td>{{ object.rti_symptom }}</td>
</tr>

</tbody>
</table>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
</body>

 

myapp/template/myapp/rti_form.html

<head>

<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
</head>

<body>

<form method="POST" enctype="multipart/form-data">

<!-- Security token -->
{% csrf_token %}

<!-- Using the formset -->
{{ form.as_p }}

<input type="submit" value="Submit">
</form>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>

</body>

myapp/template/myapp/rti_list

 

<head>

<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
</head>

<body>

<ul>

<table class="table">
<thead>

<tr>
<th scope="col">RTI#</th>
<th scope="col">DIF</th>
<th scope="col">LRG</th>
<th scope="col">SYMPTOM</th>
</tr>
</thead>

 

<tbody>
<!-- Iterate over object_list -->
{% for object in object_list %}
<!-- Display Objects -->
<tr>

<td>{{ object.rti_no }}</td>
<td>{{ object.rti_dif }}</td>
<td>{{ object.rti_lrg }}</td>
<td>{{ object.rti_symptom }}</td>
</tr>
{% endfor %}
</tbody>
</table>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
</body>

 

 




############################################