Our custom Django mixins
brack3t.com
brack3t.com
A few months ago I started using a small class-based views library called aino-utkik[1] and haven't looked back.
Instead of this:
class ArtistLogin(FormView):
form_class = ArtistLoginForm
template_name = 'artists/artist_login.html'
def get(self, request, *args, **kwargs):
request.session.set_test_cookie()
return super(ArtistLogin, self).get(request, *args, **kwargs)
def form_valid(self, form):
login(self.request, form.artist)
return HttpResponseRedirect(reverse('artist_mypage'))
def get_form_kwargs(self):
kwargs = super(ArtistLogin, self).get_form_kwargs()
kwargs['request'] = self.request
return kwargs
I can write this: class ArtistLogin(View):
def setup(self):
self.c.form = ArtistLoginForm(
request=self.request, data=self.request.POST or None)
def get(self):
self.request.session.set_test_cookie()
def post(self):
if self.c.form.is_valid():
login(self.request, self.c.form.artist)
return HttpResponseRedirect(reverse('artist_mypage'))
which I find way more elegant.And, yes, our mixins are Django-only (hence the title!)
Also, why the ``set_test_cookie`` on every GET?
BTW, thanks for the nice post. Is the code available on github or bitbucket?
https://github.com/brack3t/django-braces is the Github repo, or you can ``pip install django-braces`` into your project. All the mixins are then imported from the ``braces`` package.
That's similar to expecting people to read the source code to understand ActiveRecord or something.
This isn't a complaint, except at me. I've promised to update those docs for coming up on a whole year. :P
Here it is, although the code is somewhat mixed with the old, function based, generic views: https://github.com/django/django/tree/master/django/views/ge...
The mixin approach is nice and OO, but it's potentially tying two different layers of functionality together. Whereas the decorator is closer to aspect-oriented programming which attempts to isolate core business logic from such modifiers.
I'm actually quite interested in the challenge of applying design patterns for large systems (inversion-of-control, AOP etc) to Django, which has some stubborn behaviours that get in the way.
I'll have to give it another look later, maybe I'll change my mind.