Tutorial by Examples

Class based views let you focus on what make your views special. A static about page might have nothing special, except the template used. Use a TemplateView! All you have to do is set a template name. Job done. Next. views.py from django.views.generic import TemplateView class AboutView(Tem...
Sometimes, your template need a bit more of information. For example, we would like to have the user in the header of the page, with a link to their profile next to the logout link. In these cases, use the get_context_data method. views.py class BookView(DetailView): template_name = "boo...
Template views are fine for static page and you could use them for everything with get_context_data but it would be barely better than using function as views. Enter ListView and DetailView app/models.py from django.db import models class Pokemon(models.Model): name = models.CharField(max...
Writing a view to create object can be quite boring. You have to display a form, you have to validate it, you have to save the item or return the form with an error. Unless you use one of the generic editing views. app/views.py from django.core.urlresolvers import reverse_lazy from django.views.g...
views.py: from django.http import HttpResponse from django.views.generic import View class MyView(View): def get(self, request): # <view logic> return HttpResponse('result') urls.py: from django.conf.urls import url from myapp.views import MyView urlpatterns...
With the Class Based generic Views, it is very simple and easy to create the CRUD views from our models. Often, the built in Django admin is not enough or not preferred and we need to roll our own CRUD views. The CBVs can be very handy in such cases. The CreateView class needs 3 things - a model, t...
Here is a quick example of using multiple forms in one Django view. from django.contrib import messages from django.views.generic import TemplateView from .forms import AddPostForm, AddCommentForm from .models import Comment class AddCommentView(TemplateView): post_form_class = AddPo...

Page 1 of 1