[Django]-What is the advantage of Class-Based views?

49πŸ‘

βœ…

You can subclass a class and refine methods like get_context_data for specific cases, and leave the rest as-is. You can’t do that with functions.

For instance, you might need to create a new view that does everything a previous one does, but you need to include extra variable in the context. Subclass the original view and override the get_context_data method.

Also, separating the steps needed to render the template into separate methods promotes clearer code – the less done in a method, the easier it is to understand. With regular view functions, it’s all dumped into the one processing unit.

πŸ‘€Evan Porter

17πŸ‘

If self.args[0] is bothering you, the alternative is:

urlpatterns = patterns('books.views',
    url(r'^books/(?P<slug>\w+)/$', 'publisher_books_list', name="publisher_books_list"),
)

Then you could use self.kwargs['slug'] instead, making it slightly more readable.

πŸ‘€Alex

10πŸ‘

Your example function and class are not equal in features.

The class based version provide pagination for free and forbid the use of other HTTP verbs than GET.

If you want to add this to your function, it’s going to be much longer.

But it is, indeed, more complicated.

πŸ‘€Bite code

4πŸ‘

This is the first I’m hearing of this β€” and I like it.

The advantage I see here, honestly, is that it makes views more consistent with Django overall. Models are classes and I’ve always felt that views should be too. I know not everything is but views and models are the two heavily used types.

As for the technical advantage? Well, in Python everything is a class (or object?) β€” so is there really a difference? Isn’t it 99% syntactical sugar in the first place?

πŸ‘€Frank V

1πŸ‘

One way to think about class based views, is that they are like a the Django admin with training wheels off and therefore a lot more flexible (but more difficult to understand).

For example the list-display in the admin is clearly based on the generic ListView. The simplest list view you would only define a model or queryset.

class MyExampleView(ListView);
    model = ExampleModel 

You will need to supply your own template, but it will basically be the same as the most basic ModelAdmin. The list_display attribute in the model admin will tell it what fields to display, whereas in the ListView you would do this in the template.

class SpeciesAdmin(admin.ModelAdmin):
    list_display = ['name']
admin.site.register(ExampleModel , ExampleModelAdmin)

With the admin you have a parameter

list_per_page = 100

which defines how many objects per page. List view has

paginate_by = 100

which achieves the same thing. Likewise if you look into customising the admin heavily, you will see a lot of overlap.

This site here should give you a better idea of what they do as well.

http://ccbv.co.uk/

πŸ‘€wobbily_col

Leave a comment