L10-Django Forms & Class-Based Views
L10-Django Forms & Class-Based Views
Convention for large projects: create a views directory and put each
view in a separate file
● Add __init__.py and import each view
● In urls.py, each class-based view must call the as_view() method
Comparison between views
Function-based views Class-based views
def simple_view(request, id): from django.views import View
if request.method == "GET": class SimpleView(View):
return HttpResponse(f"My ID is {id}") def get(self, request, id):
elif request.method == "POST": return HttpResponse(f"My ID is {id}")
return redirect("accounts:login") def post(self, request, *a, **k):
else: return redirect("accounts:login")
return HttpResponseNotAllowed()
List View
A page that displays a list of objects
View Template
from django.views.generic.list import ListView {% extends 'base.html' %}
from .models import Store {% block content %}
<ol>
class StoresList(ListView): {% for store in stores %}
model = Store <li><a href="{{ store.url }}">
context_object_name = 'stores' {{ store.name }}</a></li>
template_name = 'stores/list.html' {% endfor %}
</ol>
{% endblock %}
Specify template to
render
https://docs.djangoproject.com/en/5.0/ref/class-based-views/generic-display/#detailview
Detail View
A page that displays a single object
View Template
from django.views.generic.detail import DetailView {% extends 'base.html' %}
from .models import Store {% block content %}
<h1>{{ store.name }}</h1>
class StoresDetail(DetailView): <dl>
model = Store <dt>Website:</dt>
context_object_name = 'store' <dd>{{ store.url }}</dt>
template_name = 'stores/detail.html' <dt>E-mail:</dt>
<dd>{{ store.email }}</dt>
...
</dl>
Specify template to {% endblock %}
render
Display View Attributes
model: The model of the generic view, assumes Store.objects.all()
class SignupView(CreateView):
form_class = SignupForm
template_name = 'accounts/signup.html'
success_url = reverse_lazy('accounts:welcome')
Reproduction and/or sharing of course materials is prohibited. Course materials include lecture slides, course notes,
assignments, data and documents provided by the instructors. Course materials created by the instructors of this course
are their intellectual properties. They may not be shared, posted, rehosted, sold, or otherwise distributed and/or
modified without expressed permission from the authors. All such reproduction or dissemination is an infringement of
copyright and is prohibited. All rights are reserved by the instructors.