@@ -2,3 +2,71 @@ Demystifying mixins with Django
2
2
===============================
3
3
4
4
Ana Balica
5
+ @anabalica
6
+
7
+ - mixins controlled way to add to your classes
8
+ - NOT a special python construct - just ordinary python class
9
+ - inherit from object
10
+
11
+ - single responsibility
12
+ - not meant to be extended to another Mixin
13
+ - not meant to be instantiated
14
+ - implemented using multiple inheritance
15
+ - order matters (method resolution order)
16
+
17
+ Say copy/paste a feature between classes that are otherwise different
18
+
19
+ .. code-block :: python
20
+
21
+ class MyMixin (object ):
22
+ def mymethod (self ):
23
+ pass
24
+
25
+ class Foo (BaseFoo , MyMixin ):
26
+ # read as MyMixin is the base class, extended by BaseFoo, extended by Foo
27
+ # so this is bad
28
+ pass
29
+
30
+ class Foo (MyMixin , BaseFoo ):
31
+ # better
32
+ pass
33
+
34
+ extensions goes from right to left
35
+
36
+ Class Based Views example
37
+
38
+ .. code-block :: python
39
+
40
+ class LoginRequiredMixin (object ):
41
+ def dispatch (self , request , * args , ** kwargs ):
42
+ if not request.user.is_authenticated():
43
+ raise PermissionDenied
44
+ return super (LoginRequiredMixin, self ).dispatch(request, * args, ** kwargs)
45
+
46
+ class AboutView (LoginRequiredMixin , TemplateView ):
47
+ template_name = " about.html"
48
+
49
+ - alternative - TemplateView <- LoginRequiredTemplateView <- AboutView
50
+ - but then DetailView needs LoginRequiredDetailView, UpdateView ... - duplicated code
51
+ - so Mixin approach reduces duplication
52
+
53
+ Useful methods in class based views
54
+
55
+ - dispatch() - check permissions
56
+ - get_context_data() - add more data to the context
57
+ - get_template_names() - more flexible selection of template
58
+
59
+ How to learn
60
+
61
+ - Just read the source code
62
+ - https://docs.djangoproject.com/en/1.8/topics/class-based-views/mixins/
63
+ - http://ccbv.co.uk/
64
+
65
+ - django-braces is a package with lots of useful mixins
66
+ - don't do too much chaining of mixins - hard to understand execution flow
67
+
68
+ Summary
69
+
70
+ - single responsibility
71
+ - plug-in functionality
72
+ - isn't creating a subtyping relation (so not SOLID, breaks Liskov)
0 commit comments