An ultra simple blog made with Django

Twitter and Facebook Connect

— Monday, December 5th 2011

This is my show-off bit. I'm pretty used to setting up OAuth workflows so I thought this would be a good way to push the boat out a bit. I knew it'd be too much to write the entire integration myself and besides why bother when there's pre-existing solutions out there, I went for flashingpumpkin's django-socialregistration.

First thing I had to do here was sort out some dependencies; namely the Facebook SDK, OAuth and a recent version of httplib2 (to fix a bug in Facebook's SDK method of HTTP requests). Next thing was to extend the User model to allow a avatar field, now this was pretty tricky for me, cos it meant getting pretty involved in Django's model layer. Basically, you can't just add a new field to the User model, you have to create a new model that relates (by a foreign key) to the user model, I called mine UserProfile. Then you can tell Django to use this new model with; AUTH_PROFILE_MODULE = "blog.UserProfile" So the trickiest bit is how you get these two models to play nicely in terms of creating one model when the other is created. For that I used this; User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) which I don't fully understand, but makes sure that a UserProfile object is created whenever a User object is created. Ultimately this means that I can use things like; user.profile.avatar = "http://coolpic.com/avatar.jpg"

So then to actually add the user's avatar to the User object I took advantage of socialregistration's SOCIALREGISTRATION_GENERATE_USERNAME_FUNCTION callback (asserted in settings.py), which lets you do cool stuff before a new user is added to the DB. You're passed a user, profile and api object to play with, so you can just make the relevant API calls and persist the extra user details.

Comments ""


Login to post a comment