OOP in Django

Laj03y_33 report abuse

How can I use object-oriented programming in order to better structure my code in Django? I am interested in an example.

Answers

PavliNa report abuse

The most vivid and common example is the class-based views in Django. Try to use them instead of view functions.

Laj03y_33 report abuse

I know that I can use class-based views, but what is the benefit of them over simple functions?

PavliNa report abuse

You can get all typical benefits that OOP provides (inheritance, encapsulation, etc.)

Laj03y_33 report abuse

Can you give me an example, please?

BoiKo report abuse

With OOP, it is possible to define the base class, and then inherit its data/methods by the subclasses. This makes your code more concise and clear. The example: you may often need to check if the user is logged in or whether he/she has permission to visit the page. It can be done with the UserPassesTestMixin, which you can inherit by all classes where you want to implement such behaviour. Moreover, if the logic is the same for more than one views, you can create a base class where the logic will be coded, and then just inherit this logic in all the needed views.

Laj03y_33 report abuse

Thank you for such a detailed example!

Add Answer

Need support?

Just drop us an email to ... Show more