Upgrade to Pro — share decks privately, control downloads, hide ads and more …

[DjangoCon Europe 2015] Demystifying Mixins wit...

[DjangoCon Europe 2015] Demystifying Mixins with Django

"Demystifying mixins with Django" is a 15 minutes talk I presented at DjangoCon 2015 in Cardiff, UK.

Ana Balica

June 03, 2015

Transcript

39 slides
  1. In fact, mixins are ordinary Python classes. 1 class SomeMixin(object):

    2 """My smart mixin""" 3 4 def test_method(self): 5 pass
  2. 1 # some_app/views.py 2 from django.views.generic import TemplateView 3 4

    5 class AboutView(TemplateView): 6 template_name = "about.html"
  3. 1 # some_app/views.py 2 from django.views.generic import TemplateView 3 4

    5 class AboutView(SomeMixin, TemplateView): 6 template_name = "about.html"
  4. 1 # some_app/views.py 2 3 4 class LoginRequiredMixin(object): 5 6

    def dispatch(self, request, *args, **kwargs): 7
  5. 1 # some_app/views.py 2 from django.core.exceptions import PermissionDenied 3 4

    5 class LoginRequiredMixin(object): 6 7 def dispatch(self, request, *args, **kwargs): 8 if not request.user.is_authenticated(): 9 raise PermissionDenied 10
  6. 1 # some_app/views.py 2 from django.core.exceptions import PermissionDenied 3 4

    5 class LoginRequiredMixin(object): 6 7 def dispatch(self, request, *args, **kwargs): 8 if not request.user.is_authenticated(): 9 raise PermissionDenied 10 11 return super(LoginRequiredMixin, self).\ 12 dispatch(request, *args, **kwargs) 13
  7. 1 # some_app/views.py 2 from django.views.generic import TemplateView 3 4

    5 class AboutView(LoginRequiredMixin, TemplateView): 6 template_name = "about.html"
  8. ListView LoginRequiredListView AboutView CreateView LoginRequiredCreateView AboutView DetailView LoginRequiredDetailView AboutView FormView

    LoginRequiredFormView AboutView MyView LoginRequiredMyView AboutView TemplateView LoginRequiredTemplateView AboutView
  9. dispatch() get_context_data() get_template_names() check if user is logged in, has

    permission add new data to the context add more flexibility to the template names
  10. 1 # some_app/views.py 2 from django.views.generic import TemplateView 3 4

    5 class AboutView(TemplateView): 6 template_name = "about.html"
  11. dispatch() get_context_data() get_template_names() check if user is logged in, has

    permission add new data to the context add more flexibility to the template names

More Decks by Ana Balica

Other Decks in Programming