def create(request): # POST flag discriminates submission from form request if request.method == 'POST': form = CreateForm(request.POST, request.FILES) if form.is_valid(): obj = form.save() return { 'success': True, 'message': "Customer '%s' added" % form.instance.full_name } # Form was invalid return { 'success': False, 'errors': form.errors } else: # Just show the form to the user form = CreateForm() return render_to_response('customer/create.html', {'form': form}, context_instance=RequestContext(request))
def update(request, id=-1): # Find related model -- will raise error if not found try: customer = Customer.objects.get(pk=id) except ObjectDoesNotExist: raise Http404 if request.method == 'POST': form = CreateForm(request.POST, request.FILES, instance=customer) if form.is_valid(): obj = form.save() return { 'success': True, 'message': "Customer '%s' updated" % form.instance.full_name } # Invalid form return { 'success': False, 'errors': form.errors } else: # Create a form based on the instance of the customer found form = CreateForm(instance=customer) return render_to_response('customer/update.html', {'form': form}, context_instance=RequestContext(request))