Sunday, May 29, 2011

Django and processing JSON

Django ships with the JSON processing library simplejson. Although there is talk that it may be removed in the future, I see no disadvantage in using it; if it is removed then just install it manually.

This tutorial will explain how to create a form that allows the user to upload a file, then processes the json contained within it.

First, define your model (models.py)

class Import(models.Model): 
        file = models.FileField(upload_to='tmp') 
 
        def __unicode__(self): 
                return self.file 


Then define the form (forms.py)

class ImportForm(forms.Form): 
 
 file =  forms.FileField() 
 class Meta: 
  model = ImportModel 


Create your template, making sure you include enctype="multipart/form-data" in your html form declaration.

Now, the actual processing of the file goes into your form's view.

# other standard django imports here.. 
from django.utils import simplejson 
 
def import_form(request): 
    
    
    if request.method == 'POST': 
        form = ImportForm(request.user, request.FILES) 
        
        if form.is_valid(): 
            file = request.FILES['file'] # get reference to the file here 
            my_data = simplejson.loads(file.read()) 
            
            # now you can process  
            items =  my_data['items'] 
 
            for item in items: 
                # do your processing here... 
                print "item is: " + item['attribute'] 
 
            return HttpResponseRedirect('/somewhere') 
        else: 
            print "form invalid!" 
    
    else: 
        form = ImportForm() 
            
    return render_to_response('your_template.html', {'form': form}, context_instance=RequestContext(request)) 

0 comments: