Use this code to generate downloadable vCard objects. See the VObject docs for more details on the API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | """
Functions for generating individual and group vCards from Django
The functions assume a "Person" object with the following fields:
firstname
lastname
email
phone
id (automatically created by Django)
This code uses VObject: http://vobject.skyhouseconsulting.com/
"""
import vobject
def _vcard_string(person):
"""
Helper function for vcard views. Accepts a 'person' object
with certain attributes (firstname, lastname, email, phone, id)
and returns a string containing serialized vCard data.
"""
# vobject API is a bit verbose...
v = vobject.vCard()
v.add('n')
v.n.value = vobject.vcard.Name(family=person.lastname, given=person.firstname)
v.add('fn')
v.fn.value = "%s %s" % (person.firstname, person.lastname)
v.add('email')
v.email.value = person.email
v.add('tel')
v.tel.value = person.phone
v.tel.type_param = 'WORK'
v.add('url')
v.url.value = "http://example.org/people/%s/" % person.id
output = v.serialize()
return output
def vcard(request, person_id):
"""
View function for returning single vcard
"""
person = Person.objects.get(pk=person_id)
output = _vcard_string(person)
filename = "%s%s.vcf" % (person.firstname, person.lastname)
response = HttpResponse(output, mimetype="text/x-vCard")
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
def group_vcard(request):
"""
View function for returning group vcard
"""
all = Person.objects.order_by('lastname', 'firstname')
output = '\n'.join(_vcard_string(one) for one in all)
response = HttpResponse(output, mimetype="text/x-vCard")
response['Content-Disposition'] = 'attachment; filename=example_org_people.vcf'
return response
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 4 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
This turns out to be a case where a "time saving" library could cost you a lot more time than it saves. It's trivial to generate vcards with standard Django templates, using an existing card as a starter template. No external lib needed. This library is a verbose black box with no benefit that I can see (well, it's good for .ics output, but not helpful for vcard output).
Not only that, but it completely falls down when you try to output multiple phone numbers into a single vcard (at least I couldn't figure it out from the snippet provided).
#
Please login first before commenting.