from django.http import Http404, HttpResponse
from django.utils import simplejson

def load_temporary_file(request, form_class, form_attrs, widget):
    """ AJAX request for file upload is processed.
    Validates data and save file via form_class and form_attrs, prepares AJAX answer with widget object.
    Returns json with status code, file relative path, info html block or error description
    """
    if not ( request.is_ajax() and request.method=='POST' ):
        raise Http404()
    form = form_class(request, customization = form_attrs, data = request.POST, files = request.FILES)
    if form.is_valid():
        rel_path = form.handle_uploaded_file()
        response = simplejson.dumps({
            'status': True,
            'data': widget.ajax_render(rel_path),
            'file_path': rel_path,
        })
    else:
        response = simplejson.dumps({
            'status': False,
            'errors': form.flatify_errors(),
        })
    
    response = '<textarea>(' + response + ')</textarea>'  # some magic to return JSON after AJAX form with file post
    return HttpResponse(response, mimetype='text/html')
