Shorter Django Class-based Views Using Lambda Functions
A frequent pattern in Django Class-based Views, specifically when using it for forms, is the need to specify a success_url, like this:
from django.views.generic.edit import FormView
class MyView(FormView):
form_class = forms.MyForm
success_url = '/accounts/success/'
However, you don't want to hardcode the URL like that, because that violates DRY and is the whole reason we can give every url pattern an unique name in Django. Ideally, you'd like to make use of the reverse function that Django provides. But that means you have to override the get_success_url function:
from django.views.generic.edit import FormView
from django.core.urlresolvers import reverse
class MyView(FormView):
form_class = forms.MyForm
def get_success_url(self):
return reverse('accounts.success')
That's fine in most cases, but it gets awfully repetitive if you have to do that everywhere in your code just to reverse an URL. My solution to this is simple and would come as obvious to any seasoned python programmer, but maybe you haven't thought of this, shorter form using a lambda function:
from django.views.generic.edit import FormView
from django.core.urlresolvers import reverse
class MyView(FormView):
form_class = forms.MyForm
get_success_url = lambda x: reverse('accounts.success')
This makes your code slightly more compact and readable. It's a matter of opinion, really, but I feel if a function is only one line long, it can be better represented (in the case of Django Class-based views) as a lambda function.
If you found this post interesting, you might also like our blog post, Django: It's DRY, but you can sink your teeth into it
