4 ms·
Very nice snippets, though they're meant to work only with Django's default class views. A few months ago I started using a small class-based views library cal
by rlander 15y ago
Very nice snippets, though they're meant to work only with Django's default class views.
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.
[1] https://github.com/aino/aino-utkik https://github.com/aino/aino-utkik
- kennethlove 15y agoThat is a really nice syntax. I kind of like the specificity of ``form_valid`` (for example), though. And, yes, our mixins are Django-only (hence the title!) Also, why the ``set_test_cookie`` on every GET?
- rlander 15y agoThose snippets were taken from utkik's docs and are probably part of a larger code; but I agree they probably belong somewhere else, maybe in a middleware. BTW, thanks for the nice post. Is the code available on github or bitbucket?
- kennethlove 15y agoYeah, it is actually. https://github.com/brack3t/django-braces 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.
- chrisjones 15y agoI did not know this existed, I'll have to give it a look. The setup method makes sense, not sure I like having to check is_valid() though.