I was recently figured out what was the best way to include tiny pieces of templates that can be repetitive and that we can find on many pages. I call them "widget" not in a Django way (a widget being a representation of an input element, if I quote the documentation) but in a way that they can be docked to any page of a website. I think about : a list of comments relative to an article, a chat box in a right menu, a comment form or others...
The problem is that I see only two solutions to my issue, one is better than the other but does not entirely satisfy me.
- Class-Based Views : the best way to go I think, using mixins.
- Advantages : handling forms in an efficient way, the logic remains intact (the form handling, the databases queries are done where they have to be done). And we truly create the existing relation between an article and its comments as we inherits from a CommentListMixin for instance.
- Disadvantages : we have to explicitly inherits from the corresponding mixin. We can not do all what we want as inheriting from both mixins and views can overrides the attributes of one.
- Custom Tags : I think that is the worse way to go. Tags does not exist to render a part of a template (using database queries, creating forms), but to "manipulate" the data, to render it in a specific way.
- Advantages : do not need explicit call in the view, "all" is in the template (and should not be).
- Disadvantages : handling form is tricky, the logic is broken as I use them to make a job that a view should have been done.
And now, I hear you say : "So, you should go with class-based views and mixins". In fact no, it's not a problem when I use them for a "widget" (implemented as a mixin) to display a list of comments related to the current article, I just have to add the related mixin to the current view. But it becomes a problem when I want to put a "widget" on all the pages of a my website. For instance, a chat box is not related to a specific article, and I don't want to add a ChatBoxMixin on all my views (what if I decide to remove it from my website ?). So in this example, I should go with a custom tag, as I believe it is the best way to do it easily.
Someone could lighten me on this ?