Opened 9 years ago

Last modified 9 years ago

#24660 closed Cleanup/optimization

In gCBVs, decouple get_context_data() and get_template_names() from get() and post() — at Version 1

Reported by: andrei kulakov Owned by: andrei kulakov
Component: Generic views Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by andrei kulakov)

Currently there are a few gCBVs where get_context_data and get_template_names methods are closely coupled with get() and post() methods: if self.object or self.object_list are not created in get() or post(), get_context_data and get_template_names will fail.

The reason for that is probably because respective attrs were meant to be set always in get()/post() to make them available for use in all subsequent methods.

However, this creates unnecessary need to override methods in order to set these attrs when customizing or mixing gCBVs.

It would be tempting to simply init object=None and object_list=None at class level but unfortunately object=None has the special meaning in CreateView - "object is to be created on form submission and so should not be added to context when form is rendered".

I propose the following behaviour:

  • get_context_data() should not depend on get() and set() and should get the object or list from respective methods
  • get_template_names() should not error out if the object or object_list are unset.

Here are some examples of customized gCBVs where this change leads to a simpler design:

# ContextCreateView is implementation of CreateView according to 
# https://github.com/django/django/pull/4512

# note that no methods need to be overridden
class BooksCreateView(ContextCreateView, ListView):
    model         = Book
    paginate_by   = 10
    fields        = ["name", "author"]
    success_url   = reverse_lazy("list-books-create")
    template_name = "books.html"

class AuthorDetail2(DetailView, ContextFormView):
    model = Author
    form_class = AuthorInterestForm
    template_name = "author2.html"

    def form_valid(self, form):
        # Here, we would have some logic based on user's form inputs
        return redirect('author2', pk=self.get_object().pk)

PR: https://github.com/django/django/pull/4526

Change History (1)

comment:1 by andrei kulakov, 9 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top