Monday 11 March 2013

Django ModelForm class based view

This view is used to take a ModelForm, render it out and/or process it and redirect when it’s saved.

 def myform_view(request):     """do something with a form"""          # make the form     form = MyForm(request.POST or None)      if form.is_valid():         obj = form.save()           return HttpResponseRedirect('/success')      return render(             request,             'myform.html',             {'form': form}) 

And now the ClassBasedView version –

 class MyFormView(UpdateView):     """Process our form"""      model = MyModel     form_class = MyForm     template_name = 'myformview.html'      def get_object(self, queryset=None):         obj = MyModel.objects.get(pk=somepkvalue)         return obj      def form_valid(self, form):         obj = form.save()         return HttpResponseRedirect('/success') 

I’m still getting used to Django’s class based views so this post is a little thin on content, but I’ll be posting more about them as I come to use them more. The official documentation isn’t as awesome as it could be so you may want to check out some alternative Django class based views.

Perhaps I’ll get around to writing more documentation for them and getting them into the official docs. Maybe. One day.