# Generate CSV files for modelsimportcsvfromdjango.db.models.loadingimportget_model,get_apps,get_modelsfromdjango.db.modelsimportBooleanFieldfromdjango.contrib.admin.views.decoratorsimportstaff_member_requiredfromdjango.httpimportHttp404,HttpResponsefromdjango.shortcutsimportrender_to_responsefromdjango.template.defaultfiltersimportyesno__all__=('spreadsheet',)def_field_extractor_function(field):"""Return a function that extracts a given field from an instance of a model."""iffield.choices:return(lambdao:getattr(o,'get_%s_display'%field.name)())elifisinstance(field,BooleanField):return(lambdao:yesno(getattr(o,field.name),"Yes,No"))else:return(lambdao:str(getattr(o,field.name)))@staff_member_requireddefspreadsheet(request,app_label,model_name):"""Return a CSV file for this table."""# Get the fields of the tablemodel=get_model(app_label,model_name)ifnotmodel:raiseHttp404fields=model._meta.fieldsfield_funcs=[_field_extractor_function(f)forfinfields]# set the HttpResponseresponse=HttpResponse(mimetype='text/csv')response['Content-Disposition']='attachment; filename=%s-%s.csv'%(app_label,model_name)writer=csv.writer(response,quoting=csv.QUOTE_ALL)# Write the header of the CSV filewriter.writerow([f.verbose_nameforfinfields])# Write all rows of the CSV fileforoinmodel.objects.all():writer.writerow([func(o)forfuncinfield_funcs])# All donereturnresponse# The URL for the spreadsheet## urlpatterns += patterns('foo.utils.spreadsheets',# (r"^spreadsheets/(?P<app_label>\w+)/(?P<model_name>\w+)/$", "spreadsheet"), # Return a CSV file for this model# )