Jun 20, 2011

Class-based views

class SomeFormView(TemplateResponseMixin, View):
    template_name = 'some_form.html'
 
    def get(self, request):
        form = SomeForm()
 
        return self.render_to_response({
            'form': form,
        })
 
    def post(self, request):
        form = SomeForm(request.POST)
 
        if form.is_valid():
            form.save()
            messages.success(request, 'Your form has been saved!')
 
        return self.render_to_response({
            'form': form,
        })
 
 
class AjaxThingView(View):
    # Note that I don't subclass the TemplateResponseMixin here!
 
    def get(self, request):
        return HttpResponse(status=404)
 
    def post(self, request):
        id = request.POST.get('id')
 
        # Do something with the id
        return HttpResponse('some data')

No comments: