Created
November 23, 2011 18:25
-
-
Save joaodubas/1389457 to your computer and use it in GitHub Desktop.
A simple form to export data from a django model to a csv file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% extends "admin/change_list.html" %} | |
{% load i18n %} | |
{% block object-tools %} | |
<ul class="object-tools" style="margin-right: 150px"> | |
<li> | |
<a href="{{ export_url }}" class="addlink" target="_blank">{% blocktrans with cl.opts.verbose_name as name %}Exportar {{ name }}{% endblocktrans %}</a> | |
</li> | |
</ul> | |
{{ block.super }} | |
{% endblock object-tools %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExportCsvMixin(object): | |
csv_fields = None | |
csv_urlname = None | |
csv_filename = 'export' | |
def __init__(self, *args, **kwargs): | |
if not self.csv_fields or not self.csv_urlname: | |
raise ValueError(_(u'A list of fields for the csv and an urlname for this action must be defined.')) | |
super(ExportCsvMixin, self).__init__(*args, **kwargs) | |
def _get_model_field(self, name, model=None): | |
""" | |
Obtain the field of a model based on its name | |
name -- name of the field | |
model -- model on where to get the field | |
""" | |
if not model: | |
model = self.model | |
try: | |
value = model._meta.get_field(name).verbose_name | |
if not isinstance(value, str) and not isinstance(value, unicode): | |
value = value._proxy____unicode_cast() | |
except FieldDoesNotExist: | |
value = '-' | |
return value | |
def _get_instance_value(self, instance, attr): | |
""" | |
Get the value of an attribute of the instance | |
instance -- an instance of the model | |
attr -- the attribute to which retrieve a value | |
""" | |
value = getattr(instance, attr) | |
if callable(value): | |
value = value() | |
if not value: | |
value = '-' | |
return u'%s' % value | |
def _get_instance_values(self, instance, attrs): | |
""" | |
Get the values of a attributes list of the instance | |
instance -- an instance of the model | |
attrs -- a list of attributes for which to obtain values | |
""" | |
return [self._get_instance_value(instance, attr) for attr in attrs] | |
def export_csv(self, request): | |
""" | |
Create a csv file and return it as a HttResponse | |
request -- a HttpResponse | |
""" | |
objs = self.model.objects.all().select_related() | |
rows = [] | |
for obj in objs: | |
row = [] | |
row.extend(self._get_instance_values(obj, self.csv_fields)) | |
rows.append(','.join(row)) | |
row = [] | |
[row.append(self._get_model_field(attr)) for attr in self.csv_fields] | |
rows.insert(0, ','.join(row)) | |
csv = '\r\n'.join(rows) | |
csv = csv.encode('iso-8859-1') | |
response = HttpResponse(csv, mimetype='text/csv') | |
response['Content-Disposition'] = 'attachment; filename=%s.csv' % self.csv_filename | |
return response | |
def get_urls(self): | |
""" | |
Override the get_urls method from ModelAdmin adding the export_subscriptions url | |
""" | |
original_urls = super(ExportCsvMixin, self).get_urls() | |
new_urls = patterns('', | |
url(r'export/$', self.admin_site.admin_view(self.export_csv), name=self.csv_urlname) | |
) | |
return new_urls + original_urls | |
def changelist_view(self, request, extra_context=None): | |
""" | |
Pass the url for export this csv on the extra_context parameter for the changelist | |
""" | |
if extra_context: | |
extra_context.update({ 'export_url': reverse('admin:%s' % self.csv_urlname) }) | |
else: | |
extra_context = { 'export_url': reverse('admin:%s' % self.csv_urlname) } | |
return super(ExportCsvMixin, self).changelist_view(request, extra_context) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2011 João Paulo Dubas <http://aval.io> | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment