Skip to content

Instantly share code, notes, and snippets.

@ChrisLTD
Created March 22, 2013 20:17
Show Gist options
  • Save ChrisLTD/5224404 to your computer and use it in GitHub Desktop.
Save ChrisLTD/5224404 to your computer and use it in GitHub Desktop.
Django Admin export selection as vCard action
from django.http import HttpResponse
from datetime import datetime
def export_as_vcard(modeladmin, request, queryset):
"""
Export vCard admin action
Update source to match your model
Example usage:
from vcard_export_action import export_as_vcard
class YourModelAdmin(admin.ModelAdmin):
list_display = (...)
list_filter = [...]
actions = [export_as_vcard("vCard Export", fields=[...])]
"""
# Prepare vCard
d = datetime.now()
output = ""
for person in queryset.all():
person_output = """BEGIN:VCARD
VERSION:3.0
N:{last_name};{first_name}
FN:{first_name} {last_name}
TEL;TYPE=HOME,VOICE:{phone}
TEL;TYPE=WORK,VOICE:{secondary_phone}
EMAIL:{email}
REV:{rev}
END:VCARD"""
person_output = person_output.format(
first_name = person.first_name,
last_name = person.last_name,
phone = person.phone,
secondary_phone = person.secondary_phone,
email = person.email,
rev = d.strftime('%Y%M%d%H%f'),
)
output += person_output
# Prepare response
response = HttpResponse(output, mimetype='text/vcard')
if queryset.count() == 1:
# Name the file after the person being exported
filename = queryset[0].last_name + '_' + queryset[0].first_name
else:
# Or, if there are more than 1 person, name it after the datetime of the export
filename = d.strftime('%Y%M%d%H%f') + '.vcf'
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
export_as_vcard.short_description = "Export as vCard"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment