The Path to Django Mastery: 16 Generic Views to Maximize Web Development Efficiency

Hello, passionate Django Hey developers, we've got a really exciting topic for you today. We're going to take a deep dive into "16 Generic Views".

As you know, web development with Django can sometimes be frustrating because of the repetition of code, but don't worry, once you master Django's generic views, that will melt away.

In this post, we'll dive into each of Django's 16 generic views and see how they can be utilized with real-world code examples. We'll keep it simple enough for beginners and intermediates alike to understand, so stick with us!

제네릭 뷰 16가지
(16 Django Generic Views)

The magic of Django's generic views: 16 views to master

Generic views in Django are magical tools that abstract commonly used patterns in web development, greatly increasing developer productivity. Mastering these 16 generic views will take your Django development skills to the next level. Let's take a look at them one by one.

This table summarizes Django's 16 generic views at a glance, with a brief description of each view's categorization, name, and key features to help you understand the overall structure and purpose of generic views.

Categorizing Generic ViewsGeneric view nameFunctions (roles) in the view
Base ViewViewDefault view class, processing based on HTTP methods
Base ViewTemplateViewRender the specified template
Base ViewRedirectViewRedirect to a different URL
Generic Display ViewListViewDisplaying a list of objects
Generic Display ViewDetailViewShow details of a single object
Generic Edit ViewFormViewForm handling
Generic Edit ViewCreateViewCreate a new object
Generic Edit ViewUpdateViewModify an existing object
Generic Edit ViewDeleteViewDeleting objects
Generic Date ViewArchiveIndexViewShow a list of the latest objects by date
Generic Date ViewYearArchiveViewDisplay a list of objects from a specific year
Generic Date ViewMonthArchiveViewDisplay a list of objects from a specific month
Generic Date ViewWeekArchiveViewShow a list of objects in a specific attention
Generic Date ViewDayArchiveViewDisplay a list of objects on a specific day
Generic Date ViewTodayArchiveViewShow a list of objects from today's date
Generic Date ViewDateDetailViewShow object details for a specific date

1. View: Where it all starts

View is the base class for all class-based views. All other generic views are created by inheriting from this View class. Let's see how to use View with a simple example.

from django.views import View
from django.http import HttpResponse

class MyView(View):
    View. def get(self, request):
        return HttpResponse('Hello, Django world!')

    def post(self, request):
        return HttpResponse('POST Request.')

Code commentary:

  1. Import the View class from django.views.
  2. Import an HttpResponse to enable the HTTP response to be returned.
  3. Define a MyView class and inherit from the View class.
  4. Define a get method to handle GET requests.
  5. Define a post method to handle POST requests.

You can see the power of the View class in this simple example, right? You can easily implement other logic based on HTTP methods.

2. TemplateView: The Powerhouse of Static Pages

TemplateView is used to simply render a template. It's very useful for creating static pages that don't require dynamic data processing.

from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['welcome_message'] = "Welcome to Django."
        return context

Code commentary:

  1. Import TemplateView from django.views.generic.
  2. Define a HomePageView class and inherit from TemplateView.
  3. Set the template_name property to specify the template to use.
  4. Override the get_context_data method to pass additional context data.
  5. Call super() to get the default context data.
  6. Add a welcome message to the context with the 'welcome_message' key.

This will make the 'home.html' template use the {{ welcome_message }}to display a welcome message. Pretty simple, right?

3. RedirectView: Wizard for Moving URLs

RedirectView is used to redirect the user to a different URL. It's very useful for shortening URLs or redirecting old URLs to new ones.

from django.views.generic import RedirectView

class OldUrlRedirectView(RedirectView):
    url = '/new-awesome-page/'
    permanent = True

Code commentary:

  1. Import RedirectView from django.views.generic.
  2. Define the OldUrlRedirectView class and inherit from RedirectView.
  3. Set the url attribute to specify the destination URL to redirect to.
  4. Set permanent to True to use a permanent redirect (301).

With this view, you can automatically direct users who access an outdated URL to a new page. It's good for SEO, and it improves the user experience!

4. ListView: the champion of list displays

ListView is a generic view used to display a list of objects. It's very useful for creating things like a list of blog posts or a product catalog.

from django.views.generic import ListView
from .models import Book

class BookListView(ListView):
    model = Book
    template_name = 'book_list.html'
    context_object_name = 'books'
    paginate_by = 10

    def get_queryset(self):
        return Book.objects.filter(is_published=True).order_by('-publication_date')

Code commentary:

  1. Import a ListView from django.views.generic.
  2. Import the model (Book) you want to use.
  3. Define a BookListView class and inherit from ListView.
  4. Set the model property to specify the model to use.
  5. Specify the template to use as template_name.
  6. Specify the name of the list of objects to use in the template with context_object_name.
  7. Set the number of objects to display per page with paginate_by.
  8. Override the get_queryset method to return a custom queryset.

This view allows you to display a list of your published books, sorted by newest, with pagination. Pretty handy, right?

5. DetailView: The Master of Detail

DetailView is used to display the details of a single object. For example, this is very useful when creating a detail page for a specific blog post or product.

from django.views.generic import DetailView
from .models import Book

class BookDetailView(DetailView):
    model = Book
    template_name = 'book_detail.html'
    context_object_name = 'book'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['related_books'] = Book.objects.filter(author=self.object.author).exclude(pk=self.object.pk)[:3]
        return context

Code commentary:

  1. Import a DetailView from django.views.generic.
  2. Import the model (Book) you want to use.
  3. Define the BookDetailView class and inherit from DetailView.
  4. Set the model, template_name, and context_object_name properties.
  5. Overrides the get_context_data method to provide additional context data.
  6. Add other books by the same author as related books (up to 3).

This view allows you to display the details of a book along with other related books. What a great way to improve the user experience!

6. FormView: The Wizard of Form Processing

FormView is a generic view for handling forms. It's very useful when you need to get data from the user and process it.

from django.views.generic import FormView
from django.urls import reverse_lazy
from .forms import ContactForm

class ContactFormView(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = reverse_lazy('contact_success')

    def form_valid(self, form):
        form.send_email()
        return super().form_valid(form)

Code commentary:

  1. Import FormView from django.views.generic.
  2. Import the reverse_lazy function to lazily evaluate URL dereferences.
  3. Import the form class (ContactForm) that you want to use.
  4. Define the ContactFormView class and inherit from FormView.
  5. Set the template_name, form_class, and success_url properties.
  6. Override the form_valid method to define the behavior when the form is valid.
  7. Call the form's send_email method to send an email.

This view makes it easy to handle contact forms. If the form is valid, we send an email and redirect to a success page.

7. CreateView: Wizard of Object Creation

CreateView is a generic view that you use to create new objects. For example, you might use it to create a new blog post or add a new product.

from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import Book

class BookCreateView(CreateView):
    model = Book
    fields = ['title', 'author', 'description', 'publication_date']
    template_name = 'book_form.html'
    success_url = reverse_lazy('book-list')

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)

Code commentary:

  1. Import CreateView from django.views.generic.
  2. Import the reverse_lazy function and the Book model.
  3. Define the BookCreateView class and inherit from CreateView.
  4. Set the model, fields, template_name, and success_url properties.
  5. Override the form_valid method to define the behavior when the form is valid.
  6. Set the currently logged in user as the creator of the book.

This view allows you to add new books to the database. When the form is submitted, it automatically sets the currently logged in user as the creator of the book and redirects them to the book listing page.

8. UpdateView: Wizard for Modifying Objects

UpdateView is a generic view that you use to modify an existing object. It's great for editing blog posts or updating product information.

from django.views.generic import UpdateView
from django.urls import reverse_lazy
from .models import Book

class BookUpdateView(UpdateView):
    model = Book
    fields = ['title', 'author', 'description', 'publication_date']
    template_name = 'book_update.html'

    def get_success_url(self):
        return reverse_lazy('book-detail', kwargs={'pk': self.object.pk})

    def form_valid(self, form):
        form.instance.updated_by = self.request.user
        return super().form_valid(form)

Code commentary:

  1. Import UpdateView from django.views.generic.
  2. Import the reverse_lazy function and the Book model.
  3. Define the BookUpdateView class and inherit from UpdateView.
  4. Set the model, fields, and template_name properties.
  5. Override the get_success_url method to dynamically generate a success URL.
  6. In the form_valid method, set the current user to the user who updated it.

This view makes it easy to edit existing book information. Once you're done, you'll be redirected to the book's detail page. Convenient, right?

9. DeleteView: Mastering Object Deletion

DeleteView is a generic view used to delete objects. It's very useful for removing unnecessary data.

from django.views.generic import DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import UserPassesTestMixin
from .models import Book

class BookDeleteView(UserPassesTestMixin, DeleteView):
    model = Book
    template_name = 'book_confirm_delete.html'
    success_url = reverse_lazy('book-list')

    def test_func(self):
        return self.request.user.is_staff or self.get_object().created_by == self.request.user

Code commentary:

  1. Import DeleteView from django.views.generic.
  2. Import the UserPassesTestMixin to perform authorization checks.
  3. Define a BookDeleteView class and inherit from UserPassesTestMixin, DeleteView.
  4. Set the model, template_name, and success_url properties.
  5. Override the test_func method to check the delete permission.

This view allows me to delete books securely. I've restricted permissions so that only staff users or the user who created the book can delete them. Security and functionality, two birds with one stone!

10. ArchiveIndexView: Wizard for archives by date

ArchiveIndexView is used to display the most recent list of objects sorted by date. This is very useful when creating blog archive pages.

from django.views.generic.dates import ArchiveIndexView
from .models import BlogPost

class BlogArchiveIndexView(ArchiveIndexView):
    model = BlogPost
    date_field = "published_date"
    template_name = "blog_archive.html"
    context_object_name = "latest_posts"
    allow_future = False
    paginate_by = 10

Code commentary:

  1. Import ArchiveIndexView from django.views.generic.dates.
  2. Import the BlogPost model.
  3. Define the BlogArchiveIndexView class and inherit from ArchiveIndexView.
  4. Set the model, date_field, template_name, and context_object_name properties.
  5. Set allow_future to False to suppress posts from future dates.
  6. Set the number of posts to display per page with paginate_by.

This view allows you to sort your blog posts by date and display them in order of newest to oldest. It even takes care of pagination for you, which is pretty handy, right?

11. YearArchiveView: a master of archives by year

YearArchiveView is used to display a list of objects from a specific year. This is useful for displaying annual reports or blog posts by year.

from django.views.generic.dates import YearArchiveView
from .models import BlogPost

class BlogYearArchiveView(YearArchiveView):
    model = BlogPost
    date_field = "published_date"
    make_object_list = True
    template_name = "blog_year_archive.html"
    year_format = '%Y'

Code commentary:

  1. Import YearArchiveView from django.views.generic.dates.
  2. Import the BlogPost model.
  3. Define the BlogYearArchiveView class and inherit from YearArchiveView.
  4. Set the model, date_field, and template_name properties.
  5. Set make_object_list to True to generate a list of all objects for the year.
  6. Specify the year format with year_format.

This view makes it easy to show blog posts from a specific year - it takes the year from the URL and only shows posts from that year, which is great for implementing archive functionality!

12. MonthArchiveView: Wizard of the Monthly Archive

MonthArchiveView is used to display a list of objects from a specific month. It's perfect for displaying monthly reports or monthly blog posts.

from django.views.generic.dates import MonthArchiveView
from .models import BlogPost

class BlogMonthArchiveView(MonthArchiveView):
    model = BlogPost
    date_field = "published_date"
    template_name = "blog_month_archive.html"
    month_format = '%m'
    allow_future = False

Code commentary:

  1. Import MonthArchiveView from django.views.generic.dates.
  2. Import the BlogPost model.
  3. Define the BlogMonthArchiveView class and inherit from MonthArchiveView.
  4. Set the model, date_field, and template_name properties.
  5. Specify the month format with month_format.
  6. Set allow_future to False to suppress posts from future months.

This view makes it easy to show blog posts from a specific month - it takes the year and month from the URL and only shows posts from that month, which is great for implementing a monthly archive feature!

Okay, that's it for the 12 generic views, let's continue with the remaining 4 views.

13. WeekArchiveView: Mastering the Weekly Archive

WeekArchiveView is used to display a list of objects from a particular week. This is very useful for displaying weekly reports or weekly blog posts.

from django.views.generic.dates import WeekArchiveView
from .models import BlogPost

class BlogWeekArchiveView(WeekArchiveView):
    model = BlogPost
    date_field = "published_date"
    template_name = "blog_week_archive.html"
    week_format = "%W"
    allow_future = False

Code commentary:

  1. Import WeekArchiveView from django.views.generic.dates.
  2. Import the BlogPost model.
  3. Define the BlogWeekArchiveView class and inherit from WeekArchiveView.
  4. Set the model, date_field, and template_name properties.
  5. Specify the week format with week_format (%W indicates what week of the year it is).
  6. Set allow_future to False to suppress future attention posts.

This view makes it easy to display blog posts from a particular week - great for implementing a weekly review or weekly recap!

14. DayArchiveView: Wizard for daily archives

DayArchiveView is used to display a list of objects on a specific day. It's perfect for displaying daily reports or blog posts from a specific day.

from django.views.generic.dates import DayArchiveView
from .models import BlogPost

class BlogDayArchiveView(DayArchiveView):
    model = BlogPost
    date_field = "published_date"
    template_name = "blog_day_archive.html"
    month_format = '%m'
    allow_future = False
    context_object_name = 'posts'

Code commentary:

  1. Import DayArchiveView from django.views.generic.dates.
  2. Import the BlogPost model.
  3. Define the BlogDayArchiveView class and inherit from DayArchiveView.
  4. Set the model, date_field, and template_name properties.
  5. Specify the month format with month_format.
  6. Set allow_future to False to suppress posts from future dates.
  7. Specify the name of the list of objects to use in the template with context_object_name.

This view makes it easy to display blog posts from a specific day - it's great for daily diaries or showing events from a specific day!

15. TodayArchiveView: Today's archive mastery

TodayArchiveView is used to display a list of objects from today's date. It's great for displaying today's news or blog posts published today.

from django.views.generic.dates import TodayArchiveView
from .models import BlogPost

class BlogTodayArchiveView(TodayArchiveView):
    model = BlogPost
    date_field = "published_date"
    template_name = "blog_today_archive.html"
    context_object_name = 'todays_posts'

Code commentary:

  1. Import TodayArchiveView from django.views.generic.dates.
  2. Import the BlogPost model.
  3. Define the BlogTodayArchiveView class and inherit from TodayArchiveView.
  4. Set the model, date_field, and template_name properties.
  5. Specify the name of the list of objects to use in the template with context_object_name.

This view makes it easy to display blog posts published today, which is great for implementing features like "Today's Feature"!

16. DateDetailView: Wizard for date-specific details

DateDetailView is used to display the details of a specific object on a specific date. It's very useful for displaying blog posts with unique URLs by date.

from django.views.generic.dates import DateDetailView
from .models import BlogPost

class BlogDateDetailView(DateDetailView):
    model = BlogPost
    date_field = "published_date"
    month_format = '%m'
    template_name = "blog_detail.html"
    context_object_name = 'post'
    allow_future = False

Code commentary:

  1. Import a DateDetailView from django.views.generic.dates.
  2. Import the BlogPost model.
  3. Define the BlogDateDetailView class and inherit from DateDetailView.
  4. Set the model, date_field, and template_name properties.
  5. Specify the month format with month_format.
  6. Specify the name of the object to use in the template with context_object_name.
  7. Set allow_future to False to suppress posts from future dates.

This view allows you to display the details of a specific blog post published on a specific date. Including the date in the URL is great for SEO, and it's a great way to communicate information clearly to your users!

Finalize

So there you have it, all 16 of Django's generic views, which, when utilized well, can significantly reduce web development time and increase the reusability of your code.

However, there are some caveats to using generic views: sometimes, if too much customization is required, it might be simpler to use a generic function-based view instead. Also, not understanding exactly how generic views work can lead to unexpected results.

Still, in most cases, generic views make Django development much more efficient, especially when implementing CRUD (Create, Read, Update, Delete) operations.

Now that you know all 16 of Django's generic views, you can use this knowledge to build more efficient and powerful Django applications.

# Glossary

  1. Generic Views: Django's ability to provide abstractions of commonly used view patterns.
  2. CRUD: Acronym for Create, Read, Update, and Delete, the four basic functions of data processing.
  3. Context: The set of variables passed to the template
  4. Queryset: A list of objects passed in from the database.
  5. Pagination: the ability to display a large number of objects divided into multiple pages.
  6. URL dereference: The ability to use the name of a URL pattern to generate a corresponding URL.
  7. Middleware: Systems that operate in between request and response processing.
  8. Object-Relational Mapping (ORM): A technology that connects objects to relational databases.
  9. Templates: Django's feature that allows you to use Python variables and tags in HTML files.
  10. Class-Based View (CBV): A view built on a class.
테리 이모티콘
(Happy coding!)

Similar Posts