- Django Design Patterns and Best Practices
- Arun Ravindran
- 341字
- 2021-06-25 21:32:11
View mixins
Mixins are the essence of DRY code in class-based views. Like model mixins, a view mixin takes advantage of Python's multiple inheritance to easily reuse chunks of functionality. They are often parent-less classes in Python 3 (or derived from object in Python 2 since they are new-style classes).
Mixins intercept the processing of views at well-defined places. For example, most generic views use get_context_data to set the context dictionary. A derived class or mixin can insert an additional context variable, such as feed that contains a user's feed of posts. Here is how that mixin would look like:
class FeedMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["feed"] = models.Post.objects.viewable_posts(
self.request.user) return context
The get_context_data method first populates the context by calling its namesake in all the base classes. Next, it updates the context dictionary with the feed variable.
Now, this mixin can be easily used to add the user's feed by including it in the list of base classes. Say, if SuperBook needs a typical social network home page with a form to create a new post followed by your feed, then you can use this mixin as follows:
class MyFeed(FeedMixin, generic.CreateView): model = models.Post template_name = "myfeed.html" success_url = reverse_lazy("my_feed")
A well-written mixin imposes very little requirements. It should be flexible to be useful in most situations. In the previous example, FeedMixin will overwrite the feed context variable in a derived class. If a parent class uses feed as a context variable, then it can be affected by the inclusion of this mixin. Hence, it would be more useful to make the context variable name customizable, as follows:
class FeedMixin(object): feed_context_name = "feed" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[self.feed_context_name] = models.Post.objects.viewable_posts( self.request.user) return context
The ability of mixins to combine with other classes is both their biggest advantage and disadvantage. Using the wrong combination can lead to bizarre results. So, before using a mixin, you need to check the source code of the mixin and other classes to ensure that there are no method or context-variable clashes.
- 玩轉Scratch少兒趣味編程
- Java系統分析與架構設計
- Linux C/C++服務器開發實踐
- Python自動化運維快速入門(第2版)
- PHP 編程從入門到實踐
- Python機器學習經典實例
- Windows Forensics Cookbook
- H5頁面設計:Mugeda版(微課版)
- Learning Raspbian
- R Data Science Essentials
- 微課學人工智能Python編程
- Qlik Sense? Cookbook
- Spring Boot學習指南:構建云原生Java和Kotlin應用程序
- Python全棧開發:數據分析
- Expert Cube Development with SSAS Multidimensional Models