W
W
WebDeveloper20162016-11-22 12:24:33
Django
WebDeveloper2016, 2016-11-22 12:24:33

How to understand CBV and GV?

Well, it doesn’t reach me in any way ... Although I seem to understand that CBV is a stupid analogue of ordinary views declared through a function with a call to render. And then the class. But I do not understand in the first place what is the advantage of such an announcement? More code comes out, but I don’t see any advantages ... Moreover, it’s not clear what is the difference between all these generic.ListView, generic.DetailView, etc. It seems like one garbage ... Or is there some kind of difference? Another TemplateView, which can generally be used without prescribing a derived class ...
P.S. Still interested in the topic of such forms . I also can’t figure out how to use them ... Do they generate html code? Or what?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly Scherbakov, 2016-11-22
@Altaisoft

The difference appears when the number of views becomes somehow significant. In our projects, we use almost exclusively CBV and try to get away from view functions as far as possible. Have a look at the library: https://github.com/brack3t/django-braces
Suppose you have 30 different views and 10 of them should be accessible only to the superuser, 15 to only registered users with different permissions, and 5 to anonymous and bots. To do this on FBV, you will need to write a new check in each function or make some special functions like check_superuser (), which throw 403 in case of failure. But you must admit that this is ugly. Is it the case with CBV:

class ReactorCreateView(PermissionRequiredMixin, CreateView):
    permission = 'myapp.create_reactor'
    model = AtomicReactor

and actually everything. You can easily change one for the other.
If you have hundreds of these views in the system, then it may turn out that a good half use the same templates, access levels, default filters on the queryset, and therefore you can create your own mixins and use them in many views at once.
So CBV is a wildly useful thing; I advise you to immediately use them only, so that later it would not be excruciatingly painful to rewrite the overgrown pile of procedural noodles.

S
sim3x, 2016-11-22
@sim3x

No one will explain why each class in CBV is needed - read the manual, read the code
If you don't understand - write view functions
In general, CBV is better suited when there is nothing in the project and you need to get a workable site skeleton. Editing, adding, deleting in three lines is convenient
Functions are easier to write, from the point of view of a novice programmer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question