kpsul/gestioncof/csv_views.py
Ludovic Stephan 198658f5f9 Misc fixes
- on vire un commentaire obsolète, et on en remet un à jour
- un peu de doc sur les converters
2019-05-21 15:30:51 +02:00

76 lines
2.3 KiB
Python

import csv
from django.apps import apps
from django.http import HttpResponse, HttpResponseForbidden
from django.template.defaultfilters import slugify
def export(qs, fields=None):
model = qs.model
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = "attachment; filename=%s.csv" % slugify(
model.__name__
)
writer = csv.writer(response)
# Write headers to CSV file
if fields:
headers = fields
else:
headers = []
for field in model._meta.fields:
headers.append(field.name)
writer.writerow(headers)
# Write data to CSV file
for obj in qs:
row = []
for field in headers:
if field in headers:
val = getattr(obj, field)
if callable(val):
val = val()
row.append(val)
writer.writerow(row)
# Return CSV file to browser as download
return response
def admin_list_export(
request, model_name, app_label, queryset=None, fields=None, list_display=True
):
"""
Put the following line in your urls.py BEFORE your admin include:
path(
"admin/<slug:app_label>/<slug:model_name>/csv/",
csv_views.admin_list_export,
{"fields": ["username"]},
),
"""
if not request.user.is_staff:
return HttpResponseForbidden()
if not queryset:
model = apps.get_model(app_label, model_name)
queryset = model.objects.all()
queryset = queryset.filter(profile__is_cof=True)
if not fields:
if list_display and len(queryset.model._meta.admin.list_display) > 1:
fields = queryset.model._meta.admin.list_display
else:
fields = None
return export(queryset, fields)
"""
Create your own change_list.html for your admin view and put something
like this in it:
{% block object-tools %}
<ul class="object-tools">
<li><a href="csv/{%if request.GET%}?{{request.GET.urlencode}}
{%endif%}" class="addlink">Export to CSV</a></li>
{% if has_add_permission %}
<li><a href="add/{% if is_popup %}?_popup=1{% endif %}"
class="addlink">
{% blocktrans with cl.opts.verbose_name|escape as name %}
Add {{ name }}{% endblocktrans %}</a></li>
{% endif %}
</ul>
{% endblock %}
"""