Skip to content

Instantly share code, notes, and snippets.

@hwshim0810
Created September 6, 2017 00:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hwshim0810/5ed853bae4129e4e330057214c7cb9fb to your computer and use it in GitHub Desktop.
Django custom csv action
def export_as_csv_action(
description="CSV 파일로 출력", fields=None, exclude=None, header=True, force_fields=None):
"""
CSV 출력을 하는 Django Admin Action Function \n
:param description: Action 에 표시할 문구
:param fields: 출력 할 Model Field(Column)
:param exclude: 출력에서 제외할 Model Field
:param header: Field(Column) 이름을 첫번째 행으로 출력할지 여부
:param force_fields: Django admin 의 list_display 의 Custom field (문자열) 을 사용할 지 여부 False 인 경우 Model 에 없는 필드는 제외한다.
"""
def export_as_csv(modeladmin, request, queryset):
opts = modeladmin.model._meta
if not force_fields:
field_names = set([field.name for field in opts.fields])
if fields:
field_set = set(fields)
field_names = field_names & field_set
elif fields:
field_names = set(fields)
else:
raise ValueError('올바른 옵션을 넣어주세요.')
if exclude:
exclude_set = set(exclude)
field_names = field_names - exclude_set
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
writer = csv.writer(response)
if header:
writer.writerow(list(field_names))
for obj in queryset:
row = []
for field in field_names:
try:
if callable(getattr(obj, field)):
row.append(str(getattr(obj, field)()))
else:
row.append(str(getattr(obj, field)))
except AttributeError:
row.append(str((getattr(modeladmin, field)(obj))))
except:
raise
writer.writerow(row)
return response
export_as_csv.short_description = description
return export_as_csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment