Skip to content

Commit

Permalink
export_as_xls now accept dictionaries as queryset and callable as col…
Browse files Browse the repository at this point in the history
…umns
  • Loading branch information
saxix committed Aug 30, 2013
1 parent 7f1f840 commit eded0d0
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 13 deletions.
20 changes: 11 additions & 9 deletions adminactions/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import xlwt
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.db.models.fields import FieldDoesNotExist
from django.db.models.fields.related import ManyToManyField, OneToOneField
from django.http import HttpResponse
from adminactions.templatetags.actions import get_field_value
Expand All @@ -13,7 +14,7 @@
import csv
from django.utils.encoding import smart_str
from django.utils import dateformat
from adminactions.utils import clone_instance, get_field_by_path, get_copy_of_instance # NOQA
from adminactions.utils import clone_instance, get_field_by_path, get_copy_of_instance, getattr_or_item # NOQA

csv_options_default = {'date_format': 'd/m/Y',
'datetime_format': 'N j, Y, P',
Expand Down Expand Up @@ -213,9 +214,12 @@ def _get_qs_formats(queryset):
formats = {}
if hasattr(queryset, 'model'):
for i, fieldname in enumerate(fields):
f, __,__, __, = queryset.model._meta.get_field_by_name(fieldname)
fmt = xls_options_default.get(f.name, xls_options_default.get(f.__class__.__name__, 'general'))
formats[i] = fmt
try:
f, __,__, __, = queryset.model._meta.get_field_by_name(fieldname)
fmt = xls_options_default.get(f.name, xls_options_default.get(f.__class__.__name__, 'general'))
formats[i] = fmt
except FieldDoesNotExist:
pass
# styles[i] = xlwt.easyxf(num_format_str=xls_options_default.get(col_class, 'general'))
# styles[i] = xls_options_default.get(col_class, 'general')

Expand All @@ -229,10 +233,8 @@ def _get_qs_formats(queryset):
else:
response = out

if options is None:
config = xls_options_default
else:
config = xls_options_default.copy()
config = xls_options_default.copy()
if options:
config.update(options)

if fields is None:
Expand Down Expand Up @@ -262,7 +264,7 @@ def _get_qs_formats(queryset):
for idx, fieldname in enumerate(fields):
fmt = formats.get(idx, 'general')
try:
value = getattr(row, fieldname)
value = get_field_value(row, fieldname, usedisplay=False, raw_callable=False)
if callable(fmt):
value = xlwt.Formula(fmt(value))
style = xlwt.easyxf(num_format_str='formula')
Expand Down
2 changes: 1 addition & 1 deletion adminactions/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from .exports import * # NOQA
from .merge import MergeTest, MergeTestApi # NOQA
from .graph import TestGraph # NOQA
from .api import TestExportAsCsv, TestExportAsExcel, TestExportQuerySetAsCsv
from .api import TestExportAsCsv, TestExportAsExcel, TestExportQuerySetAsCsv, TestExportQuerySetAsExcel

if getattr(settings, 'ENABLE_SELENIUM', True):
try:
Expand Down
25 changes: 25 additions & 0 deletions adminactions/tests/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,28 @@ def test_export_as_xls(self):
self.assertEqual(xls_sheet.row_values(1)[:], [1.0, 111.0, 222.0])
self.assertEqual(xls_sheet.row_values(2)[:], [2.0, 333.0, 444.0])
self.assertEqual(xls_sheet.row_values(3)[:], [3.0, 555.0, u'ӼӳӬԖԊ'])


class TestExportQuerySetAsExcel(TestCase):
def test_queryset_values(self):
fields = ['codename', 'content_type__app_label']
header = ['Name', 'Application']
qs = Permission.objects.filter(codename='add_user').values('codename', 'content_type__app_label')
mem = StringIO.StringIO()
export_as_xls(queryset=qs, fields=fields, header=header, out=mem)
mem.seek(0)
w = xlrd.open_workbook(file_contents=mem.read())
sheet = w.sheet_by_index(0)
self.assertEquals(sheet.cell_value(1,1), u'add_user')
self.assertEquals(sheet.cell_value(1,2), u'auth')

def test_callable_method(self):
fields = ['codename', 'natural_key']
qs = Permission.objects.filter(codename='add_user')
mem = StringIO.StringIO()
export_as_xls(queryset=qs, fields=fields, out=mem)
mem.seek(0)
w = xlrd.open_workbook(file_contents=mem.read())
sheet = w.sheet_by_index(0)
self.assertEquals(sheet.cell_value(1,1), u'add_user')
self.assertEquals(sheet.cell_value(1,2), u'add_userauthuser')
6 changes: 3 additions & 3 deletions adminactions/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def getattr_or_item(obj, name):
raise AttributeError("%s object has no attribute/item '%s'" % (obj.__class__.__name__, name))


def get_field_value(obj, field, usedisplay=True):
def get_field_value(obj, field, usedisplay=True, raw_callable=False):
"""
returns the field value or field representation if get_FIELD_display exists
Expand All @@ -55,12 +55,12 @@ def get_field_value(obj, field, usedisplay=True):
else:
raise ValueError('Invalid value for parameter `field`: Should be a field name or a Field instance ')

if hasattr(obj, 'get_%s_display' % fieldname) and usedisplay:
if usedisplay and hasattr(obj, 'get_%s_display' % fieldname):
value = getattr(obj, 'get_%s_display' % fieldname)()
else:
value = getattr_or_item(obj, fieldname)

if callable(value):
if not raw_callable and callable(value):
return value()

return value
Expand Down

0 comments on commit eded0d0

Please sign in to comment.