Login

Gravatar support in model save override

Author:
JoeLinux
Posted:
February 18, 2013
Language:
Python
Version:
1.4
Score:
2 (after 2 ratings)

Overridden save() method that adds Gravatar support for a user with a profile photo field (and presumably an email field). Checks to see if user has provided a photo. If not, then query Gravatar for a possible photo. Finally, if Gravatar does not have an appropriate photo for this user, then use whatever default photo is available (in this case, 'users/photos/default_profile_photo.png'... change as necessary).

 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
from urllib import urlencode
from urllib2 import urlopen, HTTPError
from hashlib import md5

from django.db import models
from django.conf import settings
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile


class CustomUser(...):  # however you choose to subclass the user
    ...
    email = models.EmailField(max_length=254, unique=True)
    photo = models.ImageField(upload_to='users/photos', blank=True)
    slug = models.SlugField(unique=True, blank=True)
    ...

    def save(CustomUser, self).save(*args, **kwargs)
        """
        Overrides CustomUser's save() method. Assumes that CustomUser has
        self.photo, self.email, and self.slug fields. Adjust code as
        necessary for your model.
        """
        if not self.photo:
            base_url = 'http://{0}'.format(Site.objects.get_current().domain)
            default_photo = 'users/photos/generic_profile_photo.png'  # use your own
            default_photo_url = base_url + settings.MEDIA_URL + default_photo  # alternatively you can just use 'mm' here
            gravatar_base = 'http://www.gravatar.com/avatar/'
            gravatar_email = md5(self.email.lower()).hexdigest()
            gravatar_default = urlencode({'d': default_photo_url})
            gravatar_query = '{0}{1}?{2}'.format(gravatar_base, gravatar_email, gravatar_default)
    
            try:
                tmp_photo = NamedTemporaryFile(delete=True)
                retr_photo = urlopen(gravatar_query)
                content_type = retr_photo.headers.getheader('Content-Type', None)
                file_type = None
                if content_type:
                    if content_type == 'image/jpeg':
                        file_type = 'jpg'
                    elif content_type == 'image/png':
                        file_type = 'png'
                    elif content_type == 'image/bmp':
                        file_type = 'bmp'
                    elif content_type == 'image/gif':
                        file_type = 'gif'
                    elif content_type == 'image/tiff':
                        file_type = 'tiff'
                tmp_photo.write(retr_photo.read())
                tmp_photo.flush()
                # I'm using self.slug here to name the file, but it's not necessary
                self.photo.save('users/photos/{0}.{1}'.format(self.slug, file_type if file_type else 'png'),
                                File(tmp_photo), save=True)
            except HTTPError:  # as little can go wrong with users, so any HTTPError should just default
                self.photo = default_photo
        super(DJ, self).save(*args, **kwargs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.