官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 宣威市| 海宁市| 无极县| 焉耆| 喀喇| 永昌县| 图木舒克市| 高安市| 瑞昌市| 唐河县| 龙井市| 武义县| 唐海县| 大冶市| 汪清县| 隆子县| 肇东市| 奎屯市| 澄迈县| 双峰县| 永济市| 兰考县| 兴安盟| 织金县| 抚州市| 德兴市| 石渠县| 临猗县| 彰武县| 海阳市| 南岸区| 安多县| 民和| 汝南县| 密云县| 井陉县| 察雅县| 南川市| 陕西省| 威远县| 平武县|