Tuesday, March 4, 2014

Django Form - A shorter way to work with form

I've just found a shorter way to work with Django form in a view with POST request. Instead of:

def home(request):
if request.method == 'POST':
myform = MyForm(request.POST, request.FILES)
if myform.is_valid():
myform.save()
return redirect('home')
else:
myform = MyForm()

return render_to_response('home.html', locals(), context_instance=RequestContext(request))


I can do something like this:

def home(request):
myform = MyForm(request.POST or None)

if myform.is_valid():
myform.save()
return redirect('home')

return render_to_response('home.html', locals(), context_instance=RequestContext(request))