Mellow Morning » Django http://www.mellowmorning.com Blogging the world of IT and Business Wed, 04 Dec 2013 13:00:49 +0000 http://wordpress.org/?v=2.9.2 en hourly 1 Django Facebook 5.3 http://www.mellowmorning.com/2013/12/04/django-facebook-5-3/ http://www.mellowmorning.com/2013/12/04/django-facebook-5-3/#comments Wed, 04 Dec 2013 13:00:49 +0000 tschellenbach http://www.mellowmorning.com/?p=823 The 5.3 release makes it a lot easier to get started with Django Facebook.
Documentation has had a major overhaul, many small bugs have been fixed and setting validation will complain if you make mistakes during the install.

Have a look at the new docs. Especially the bit documenting how to use OpenFacebook will be interesting to many people:

Getting an OpenFacebook object
Making calls

The full docs are linked on github.

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2013/12/04/django-facebook-5-3/feed/ 5
Build a scalable feed using Feedly and Django http://www.mellowmorning.com/2013/10/18/scalable-pinterest-tutorial-feedly-redis/ http://www.mellowmorning.com/2013/10/18/scalable-pinterest-tutorial-feedly-redis/#comments Fri, 18 Oct 2013 12:03:44 +0000 tschellenbach http://www.mellowmorning.com/?p=793 About a year ago we open sourced the feed component of Fashiolista called Feedly. At Fashiolista it powers the flat feedaggregated feed and the notification system. In general it allows you to build newsfeed and notification systems using Cassandra and/or Redis. Examples of what you can build are applications like the Facebook newsfeed, your Twitter stream or your Pinterest following page.

The project has come a long way over the past year and we’re really happy with the 0.9 release. In this blogpost I’ll show you how to use Feedly, Django, Celery and Redis to build a scalable Pinterest like newsfeed. (Feedly isn’t tied to Django so feel free to try setting this up using another framework)

What we’re building

You can play around with the end result on Heroku. In case it goes down here is a screenshot:

Now most parts of this app aren’t very polished or scalable. The part we are focusing on is the flat feed. (The page showing all the pins by people you follow). The system works by storing a feed for every user. As soon as someone pins an item it gets stored in the feeds of all their followers. Using this approach it becomes really easy to shard a newsfeed system. If you want to know more about the reasoning behind this solution you’ll find the background articles very interesting.

Building

So let’s get started building this app. You can find the Feedly source code and the example app on Github.

First step, setting up the feeds

Now we need to store those pins somewhere, so let’s create two feeds. One for your own pins and one for the pins of all the people you follow. (example: pin_feed.py)

# the feed containing pins by people you follow
class PinFeed(RedisFeed):
    key_format = 'feed:normal:%(user_id)s'

# the feed containing only your pins
class UserPinFeed(PinFeed):
    key_format = 'feed:user:%(user_id)s'

Second step, connecting the followers

With the feeds setup we need a way to know who follows who. You can hook this up by creating a custom feedly class and implementing get_user_follower_ids as shown below. (example: pin_feedly.py)

class PinFeedly(Feedly):
    feed_classes = dict(
        normal=PinFeed,
    )
    user_feed_class = UserPinFeed

    def add_pin(self, pin):
        # see example core.models.py
        activity = pin.create_activity()
        # add user activity adds it to the user feed, and starts the fanout
        self.add_user_activity(pin.user_id, activity)

    def get_user_follower_ids(self, user_id):
        return Follow.objects.filter(target=user_id).values_list('user_id', flat=True)

feedly = PinFeedly()

Now when you call feedly.add_pin(pin) it will fetch the ids of all your followers and spawn many small tasks using Celery. Each of those tasks will push the pin to a few of your followers. This process is called the fanout.

Third step, the view

In the view you retrieve the feed instance by calling feedly.get_feeds(user_id)['normal']. The feed is slicable so doing feed[:25] gives you the top 25 activities in the feed.

# django example, this part would be different in another framework

@login_required
def feed(request):
    context = RequestContext(request)
    feed = feedly.get_feeds(request.user.id)['normal']
    activities = list(feed[:25])
    context['activities'] = activities
    response = render_to_response('core/feed.html', context)
    return response

That’s pretty much it. These 3 steps together with a bit of boilerplate for setting things up allow you to build the example app.

Concluding

The full docs for Feedly can be found on Github and Read the docs. In addition to the Pinterest newsfeed example you can use Feedly to build:

  • A Twitter like newsfeed
  • A notification system like Facebook’s or Fashiolista’s
  • An activity stream like Wanelo’s stories or Etsy’s activity stream

We’re eager to see what applications you’ll build with this. Be sure to let us know on Github if you run into any issues.

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2013/10/18/scalable-pinterest-tutorial-feedly-redis/feed/ 2
Django Facebook – 1.5 and custom user model support http://www.mellowmorning.com/2013/05/11/django-facebook-1-5-and-custom-user-model-support/ http://www.mellowmorning.com/2013/05/11/django-facebook-1-5-and-custom-user-model-support/#comments Sat, 11 May 2013 12:14:48 +0000 tschellenbach http://www.mellowmorning.com/?p=762 Django Facebook now officially supports Django 1.5 and custom user models! Go try it out and upgrade to pip version 5.1.1. It’s backwards compatible and you can choose if you want to keep on using profiles, or migrate to the new custom user model. Installation instructions can be found on github.

Contributing

Thanks for all the contributions! My startup (Fashiolista) depends on a reliable Facebook integration and maintaining it would not be possible without all the pull requests from the community. Contributions are strongly appreciated. Seriously, give Github a try, fork and get started :)

About Django Facebook

Django Facebook enables your users to easily register using the Facebook API. It converts the Facebook user data and creates regular User and Profile objects. This makes it easy to integrate with your existing Django application.

I’ve built it for my startup Fashiolista.com and it’s currently used in production with thousands of signups per day. For a demo of the signup flow have a look at Fashiolista’s landing page (fashiolista.com)

After registration Django Facebook gives you access to user’s graph. Allowing for applications such as:

  • Open graph/ Timeline functionality
  • Seamless personalization
  • Inviting friends
  • Finding friends
  • Posting to a users profile

Django Facebook helps you quickly develop Facebook applications using Django.
Let me know what features or issues you are encountering!

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2013/05/11/django-facebook-1-5-and-custom-user-model-support/feed/ 5
Django Facebook hotfix, update to 5.0.13 http://www.mellowmorning.com/2013/05/01/django-facebook-hotfix-update-to-5-0-13/ http://www.mellowmorning.com/2013/05/01/django-facebook-hotfix-update-to-5-0-13/#comments Wed, 01 May 2013 10:35:31 +0000 tschellenbach http://www.mellowmorning.com/?p=746 Last night Facebook changed the format they use for codes. (codes are an intermediate step in the process of requesting access tokens.)

This change broke the caching for the convert code step for Django Facebook, breaking login, connect and registration functionality. Fortunately this was quickly reported by developers in a country where there was no Queensday yesterday.

I encourage everybody to update to 5.0.13 to make sure your Facebook integration keeps on working.

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2013/05/01/django-facebook-hotfix-update-to-5-0-13/feed/ 4
Open graph and timeline sharing using Django Facebook http://www.mellowmorning.com/2012/10/03/open-graph-and-timeline-sharing-using-django-facebook/ http://www.mellowmorning.com/2012/10/03/open-graph-and-timeline-sharing-using-django-facebook/#comments Wed, 03 Oct 2012 11:04:38 +0000 tschellenbach http://www.mellowmorning.com/?p=713 As many apps will find out today, Facebook is removing it’s offline_access permission on October 3rd. For most apps this will mean that many of your open graph shares start failing.

Fashiolista has built up quite some experience with tweaking this and today we’ll be sharing some tips. The actual code we’re using has been included in the latest version of Django Facebook.

1.) Store and retry your shares

There are several advantages of storing your open graph shares in the database. You get:

  • Stats
  • Error tracking
  • Ability to retry individual shares
  • Ability to retry a user’s shares if you get an updated token
  • Ability to delete shares (since you store the Facebook object id)

Especially the ability to retry shares was important to us. Django Facebook provides a convenient OpenGraphShare model to store all your shares in. Have a look at the example below:

class DjangoModel:
    def share_to_facebook(self, graph=None):
        from django_facebook.models import OpenGraphShare
        #this is where the magic happens
        share = OpenGraphShare.objects.create(
            user_id=self.user_id,
            action_domain='fashiolista:love',
            content_type=content_type,
            object_id=self.id,
        )
        share.set_share_dict(kwargs)
        share.save()
        result = share.send()

Note that we store all info required for sharing to Facebook in the OpenGraphShare model. The actual Facebook API request is sent when you call share.send().

Using this flow has the benefit that Django Facebook will retry your open graph shares if a user’s token updates. By doing this more of your open graph shares will actually reach Facebook.

2.) Extend your tokens

Facebook’s has deprecated offline access. By default you will now get a short lived access token (usually 1-2 hours). Often you will want longer lived tokens though. For example when your app keeps a user logged in for 30 days, storing a token once with a duration of 2 hours doesn’t get you very far. If you need longer lived tokens, you can now extend your token via a Facebook API call. These long lived tokens will keep working for 60 days.

The high level API for extending tokens is located in:

user.get_profile().extend_access_token()

In the new version of Django Facebook your token will be automatically extended upon connecting with Facebook. There is however a performance overhead to this extra API call. That’s where the following point comes in:

3.) Use Celery

Calling the Facebook API is something which takes quite a bit of time. If you’re unlucky a single API call can easily take up to 2000 ms. Celery is a tool which allows you to easily run tasks in the background, ensuring your pages stay fast for the users. At Fashiolista we use tasks for checking comment spam, adding loves, clearing cache, posting to Facebook and extending your Facebook access tokens. You can learn more about Celery in this guide.

Setting up Django Facebook to use Celery is trivial. Simply set the following settings to True.

#Use celery for storing friends or likes
FACEBOOK_CELERY_STORE = True
#Use celery for extending access tokens in the background
FACEBOOK_CELERY_TOKEN_EXTEND = True

Using Celery speeds things up enormously for the end user, so I recommend using it.

Concluding

Upgrading to the latest version of Django Facebook and implementing these tips will get you a very solid open graph implementation. Let me know in the comments what steps you’ve taken to get these numbers up.

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2012/10/03/open-graph-and-timeline-sharing-using-django-facebook/feed/ 5
Performance metrics for a social network http://www.mellowmorning.com/2012/08/22/performance-metrics-for-a-social-network/ http://www.mellowmorning.com/2012/08/22/performance-metrics-for-a-social-network/#comments Wed, 22 Aug 2012 14:30:38 +0000 tschellenbach http://www.mellowmorning.com/?p=694 This is a talk I gave at the Amsterdam Performance Meetup.

The presentation starts by introducing Fashiolista.
It still amazes me and 3 other guys started Fashiolista and grew it to the 2nd largest online Fashion community.
I guess Marc Andreesen had a point in his “Why Software Is Eating The World” article.

The talk focuses on how we use metrics to drive optimization at Fashiolista.
And narrows down on tools like:

If you’re looking up the links from the presentation, these are the most notable ones:

The Presentation

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2012/08/22/performance-metrics-for-a-social-network/feed/ 2
Fashiolista in NY http://www.mellowmorning.com/2012/02/11/fashiolista-in-ny/ http://www.mellowmorning.com/2012/02/11/fashiolista-in-ny/#comments Sat, 11 Feb 2012 18:16:16 +0000 tschellenbach http://www.mellowmorning.com/?p=678 The Fashiolista team is in New York for the fashion week. I’m looking forward to meet some local tech startups. Drop me a mail or leave a comment if you want to grab a coffee.

Cheers,
Thierry Schellenbach
CTO/ Founder
Fashiolista

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2012/02/11/fashiolista-in-ny/feed/ 0
Facebook open graph publishing simplified http://www.mellowmorning.com/2012/02/01/facebook-open-graph/ http://www.mellowmorning.com/2012/02/01/facebook-open-graph/#comments Wed, 01 Feb 2012 19:00:15 +0000 tschellenbach http://www.mellowmorning.com/?p=583 Facebook has just enabled the open graph for 60 lucky apps. The new open graph beta allows you to post a user’s actions to their timeline. This activity is shown to the user’s friends in Facebook’s newsfeed and ticker. Furthermore your data is nicely aggregated on a user’s Facebook profile. Fashiolista’s aggregation for instance looks like this:

Posting these actions on Facebook can greatly enhance the viral growth of your company. Spotify, one of the launch partners, has grown by more than 4mil active users. This blogpost explains how to use Django Facebook to integrate your Django based site with Facebook.

How open graph works

Before going into the code though we need to understand the basic concepts of the open graph: actions and objects. Facebook’s getting started interface explains it best:

Actions are the verb, objects are what the action is applied to. You submit the data for these actions and objects to Facebook. An example would be watching (action) the movie Pan’s Labyrinth (object). Every object should be represented by a dedicated URL. For instance if you look at Chiara’s profile (object) on Fashiolista you will see the following open graph data:

<meta property="og:title" content="ChiaraFerragni" />
<meta property="og:image" content="http://bit.ly/rso3ig" />
<meta property="og:type" content="fashiolista:fashiolista" />
<meta property="og:site_name" content="Fashiolista" />

To post to the open graph you specify an action and the url for the object. You can read more about it in Facebook’s open graph docs.

Getting permission

Users only need to give you permission to the open graph once. You specifically need the publish_actions permission. When asking for this permission a pretty permission interface as shown below will appear:

Notice the tiny add to timeline box displayed at the bottom right corner of the interface.

Posting to the graph

The code below will show you how to post to the open graph. There are however a few requirements which you’ll need to go through.

  1. Register your own Facebook app and define actions and items
  2. Have Django Facebook installed

Simple posting to the graph

After receiving this permission we can post to the user’s timeline. Below is the most basic example:

@facebook_required(scope='publish_actions')
def open_graph_beta(request):
    '''
    Simple example view on how to do open graph postings
    '''
    fb = get_persistent_graph(request)
    entity_url = 'http://www.fashiolista.com/item/2081202/'
    result = fb.set('me/fashiolista:love', item=entity_url)
    messages.info(request, 'The item has been shared to fashiolista:love')

This posts the action love to the users timeline with the object data found at the url http://www.fashiolista.com/item/2081202/.
The syntax me/fashiolista:love translates to post to me in the namespace fashiolista with the action love.

Asynchronous posting to the graph

While the above example works, you often won’t want to keep your users waiting for the Facebook API request. Especially since they are quite sluggish at the moment.
Below there’s a version of the code using celery. Celery is a task queuing system which enables you to run tasks asynchronously.

@task.task(ignore_result=True)
def open_graph_beta(user):
    '''
    Example posting to open graph using a celery task
    '''
    profile = user.get_profile()
    fb = profile.get_offline_graph()
    entity_url = 'http://www.fashiolista.com/item/2081202/'
    result = fb.set('me/fashiolista:love', item=entity_url)

Concluding

Integrating with open graph is easy. Head over to the github page of Django Facebook to get started. Contributions are more than welcome.

Fashiolista Jobs

Do you also see the beauty in clean code? Are you experienced with high scalability web apps? Currently we’re looking for additional talent over at our Amsterdam office. Feel free to drop me a line at my personal email for more information: thierryschellenbach[át]gmail.com

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2012/02/01/facebook-open-graph/feed/ 3
Django Facebook 3.2 – Simple image upload and wall posts http://www.mellowmorning.com/2011/10/23/django-facebook-3-2-simple-image-upload-and-wall-posts/ http://www.mellowmorning.com/2011/10/23/django-facebook-3-2-simple-image-upload-and-wall-posts/#comments Sun, 23 Oct 2011 22:21:27 +0000 tschellenbach http://www.mellowmorning.com/?p=568 Most of the Facebook examples are written in PHP and unfortunately for us they always seem so damn simple. I think the Python libraries should allow you to write more elegant code and the new version of Django Facebook let’s you do just that.

Much of the new found simplicity comes from the facebook_required decorator. This decorator is similar to login_required, but instead checks the Facebook permissions given to you. Writing the input of a form to someone’s wall is now as simple as this:

@facebook_required(scope='publish_stream')
def wall_post(request):
    fb = get_persistent_graph(request)

    message = request.POST.get('message')
    fb.set('me/feed', message=message)

    messages.info(request, 'Posted the message to your wall')

    return next_redirect(request)

Another example would be uploading some photos to a user’s timeline:

@facebook_required(scope='publish_stream,user_photos')
def image_upload(request):
    fb = get_persistent_graph(request)
    pictures = request.POST.getlist('pictures')

    for picture in pictures:
        fb.set('me/photos', url=picture, message='the writing is one The '
            'wall image %s' % picture)

    messages.info(request, 'The images have been added to your profile!')

    return next_redirect(request)

As you can see the syntax is very straightforward. You no longer have any technical excuse against integrating Facebook.
More examples and installation instructions can be found on Django Facebook’s github.

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2011/10/23/django-facebook-3-2-simple-image-upload-and-wall-posts/feed/ 14
Amsterdam based, VC funded startup, Fashiolista looking for new team members http://www.mellowmorning.com/2011/08/15/amsterdam-based-vc-funded-startup-fashiolista-looking-for-new-team-members/ http://www.mellowmorning.com/2011/08/15/amsterdam-based-vc-funded-startup-fashiolista-looking-for-new-team-members/#comments Mon, 15 Aug 2011 08:44:32 +0000 tschellenbach http://www.mellowmorning.com/?p=424 Over the past months Fashiolista has grown to be one of the largest fashion communities worldwide. Dividing attention between scaling the site and creating new features has been quite a challenge. We are looking for a very experienced django developer to join our team.

About Fashiolista

Fashiolista is best described as “twitter for fashion”. Girls follow each other’s fashion finds and indicate which items they love. We are funded by Atomico ventures and several high profile angel investors.

Why you will love working at Fashiolista

- Young team, startup culture
- Developers in the founding team
- The team has been working with Django for more than 4 years
- Modern stack (Django 1.3, postgres, redis, memcached, jquery, celery, solr, GIT)
- Learning culture

Did I mention we are located in the centre of Amsterdam?

Who we are looking for

We are looking for a talented Django developer with experience in building highly scalable applications. Since our team is small, strong experience with Linux or Freebsd system administration would be a big plus.

  • Experienced with Django and Python (> 3 years preferably)
  • Knowledge of SQL and query optimization
  • Javascript experience
  • Test driven development
  • Memcached and other caching techniques
  • GIT

Bonus points for:

  • Knowledge of FreeBSD or Linux system administration
  • Redis/ NoSql experience
  • SOLR experience
  • Postgres Trigger experience
  • Celery experience
  • CS degree

For this position you need to be willing to work in The Netherlands/ Amsterdam. Furthermore the position is full time.

To conclude

We are looking for someone with an excellent work attitude and considerable experience. It doesn’t matter if you are a student, cum laude graduate, or drop out, as long as you’re extremely passionate about what you do. You will be working in a startup and we expect your input on a wide range of challenges.

If you recognize yourself in the above description or would like more information please contact me at:
thierry…fashiolista.com

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2011/08/15/amsterdam-based-vc-funded-startup-fashiolista-looking-for-new-team-members/feed/ 1
Django Facebook 3.0 – OAuth migration – Time to upgrade! http://www.mellowmorning.com/2011/08/13/django-facebook-3-0-oauth-migration-time-to-upgrade/ http://www.mellowmorning.com/2011/08/13/django-facebook-3-0-oauth-migration-time-to-upgrade/#comments Sat, 13 Aug 2011 14:40:16 +0000 tschellenbach http://www.mellowmorning.com/?p=434 Facebook is migrating to HTTPS and OAuth to increase the safety of their users. Unfortunately these changes aren’t backwards compatible and will require some effort to follow. To support the new Facebook system you need to upgrade to Django Facebook 3.0 before October 1st.

In addition to the required migrations, this version also includes several new features. The largest change is the underlying Facebook API client. You can read about the improvements here or skip down to the upgrade instructions.

Open Facebook – New Python Facebook client

Open Facebook is a python client to the Facebook graph API. Currently it’s included in Django Facebook, but in time it will be spun of as a separate project. The client is supported, tested and up to date with the current version of Facebook’s graph API.
It handles connection issues cleanly and raises separate error classes for various Facebook error scenarios.
The syntax is very straightforward to use:

open_facebook = OpenFacebook(token)
#info about me
open_facebook.me()

#retrieving a page
open_facebook.get('fashiolista')

#retrieving your albums
open_facebook.get('me/albums')

#posting a message on your wall
open_facebook.set('me/feed', message='Check out Fashiolista', picture=image_url)

#setting a like
open_facebook.set('fashiolista/likes')

#fql example
result = open_facebook.fql('SELECT name FROM user WHERE uid = me()')

#authorization is handled separately from the API class
token = FacebookAuthorization.get_app_access_token()
test_user = FacebookAuthorization.create_test_user(token)

Album upload Example

Uploading pictures to Facebook is as simple as this:

open_facebook = get_facebook_graph(request)
photo_urls = [
    'http://d.fashiocdn.com/images/entities/0/6/t/p/d/0.365x365.jpg',
    'http://e.fashiocdn.com/images/entities/0/5/E/b/Q/0.365x365.jpg',
]
for photo in photo_urls:
    uploaded = open_facebook.set('me/photos', url=photo,
        message='Fashiolista is awesome', name='FashiolistaTest'
    )

So there are good reasons to upgrade even if Facebook didn’t force us to :)

How to upgrade to 3.0

First Step – Install Django Facebook 3.0
Follow the installation instructions.

Javascript changes
In your Facebook initialization code enable OAuth.

FB.init({appId: facebookAppId, status: false, cookie: true, xfbml: true, oauth: true});

Perms has been renamed to scope.

FB.login(function() {}, {'scope' : 'offline_access'});

Django Facebook changes
The get_facebook_graph function is no longer persistent by default, if you want the old behavior use get_persistent_graph.
Furthermore the FacebookUserConverter class and the core Facebook API client are now separated. get_facebook_graph returns the core facebook API client. To go from the API class to the user converter class use something like

graph = get_facebook_graph(request)
facebook = FacebookUserConverter(graph)

That should be all.
If you are encountering problems feel free to let me know in the comments.

Last Step – Enable the new Facebook Migrations
Go to the Facebook Apps page and enable the OAuth migration.
Select your app -> About -> Advanced -> Migrations
Enable Force OAuth
Enable OAuth Migration

Background reading

Moving to OAuth 2.0 + HTTPS
Updated JavaScript SDK and OAuth 2.0 Roadmap
New Facebook Authentication Docs
PHP SDK v.3.1.1
PHP SDK v3.0.0

We’re hiring!

Do you also see the beauty in clean code? Are you experienced with high scalability web apps? Currently we’re looking for additional talent over at our Amsterdam office. Feel free to drop me a line at my personal email for more information: thierryschellenbach[at]gmail.com

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2011/08/13/django-facebook-3-0-oauth-migration-time-to-upgrade/feed/ 11
Django Facebook 2.0 – Integrating Facebook http://www.mellowmorning.com/2011/06/23/django-facebook-2-0-integrating-facebook/ http://www.mellowmorning.com/2011/06/23/django-facebook-2-0-integrating-facebook/#comments Thu, 23 Jun 2011 15:18:40 +0000 tschellenbach http://www.mellowmorning.com/?p=350 It’s been a year since Facebook changed the web with the open graph API and their like button. Unfortunately Facebook didn’t have much developer love for the python/django platform. Django Facebook aims to make it easy to build facebook apps and integrate facebook with your website.

Key functionality

One of the strong points of Django Facebook is the ability to register users using Facebook. It ports all of Facebook’s user data to the Django user and profile models. This allows you to have a secure register/connect/login flow using Facebook, greatly reducing the barriers to start using your application. Below an example of me registering for Fashiolista using the Facebook register flow.

Me on Facebook

Me on Fashiolista

In this blog post I will explain how to get started implementing a Facebook connect flow. Django Facebook can however do quite a bit more, as you can see in the feature list below. Development over at the github repo is very active. I strongly appreciate help on improving the functionality so please fork and contribute.

Features

  • Register users using the Facebook open graph API
    • Full profile data birthday, gender, website, about me, username, email and picture
    • Support for mobile authentication
    • Fallback to registration form for entering additional data when required
  • Build Facebook Canvas applications
  • Mobile registration using Facebook
  • Execute Facebook FQL queries
  • Upload pictures to Facebook
  • Find your Facebook friends

Getting Started

Now let’s get started with building a Facebook login/connect/register flow. This post will guide you through it step by step.

Prerequisites

Create a Facebook app

Have django registration installed (other registration systems will require some small code changes)

pip install django_facebook :)

A.) Settings and more

Define these settings in your settings file.
FACEBOOK_API_KEY
FACEBOOK_APP_ID
FACEBOOK_APP_SECRET

add django facebook to your installed apps
‘django_facebook’,
add this line to your url config
(r’^facebook/’, include(‘django_facebook.urls’)),
add this line to your context processors
‘django_facebook.context_processors.facebook’,
add this to your AUTHENTICATION_BACKENDS
‘django_facebook.auth_backends.FacebookBackend’,

B.) Adjust your user Profile model

Secondly we need to be able to store the Facebook data on your user profile.
The easiest way to do this is to add the abstract model in django_facebook/models.py called FacebookProfileModel to your profile model.
After your profile is ready to store Facebook data you should have a working example at /facebook/connect/.
Let me know in the comments if something went wrong up to this point :)

C.) Design and integration

You can style the facebook form and button anyway you see fit. Over at Fashiolista we added a nice facepile for example. The basic markup is located in the example file connect.html.
We use the facebook javascript SDK for a smooth user integration. You can load the facebook JS like this:

<script src="{{ MEDIA_URL }}js/original/facebook.js" type="text/javascript"></script>
<script>
facebookAppId = '{{ FACEBOOK_APP_ID }}';
function facebookJSLoaded(){
FB.init({appId: facebookAppId, status: false, cookie: true, xfbml: true});
}
window.fbAsyncInit = facebookJSLoaded;
F = new facebookClass(facebookAppId);
F.load();
</script>

Subsequently implement a form which calls Facebook via javascript. Note that you can control which page to go to after connect using the next input field.

<form action="{% url facebook_connect %}?facebook_login=1" method="post">
<a href="javascript:void(0);" style="font-size: 20px;" onclick="F.connect(this.parentNode);">Register, login or connect with facebook</a>
<input type="hidden" value="{{ request.path }}" name="next" />
</form>
<div id="fb-root"></div>

That was all, you should now have a working registration flow using Facebook. Let me know in the comments if you encounter any difficulties.
If you want to go one step further and understand the facebook API, you can find the Facebook documentation here.
Django Facebook received tons of improvements from the python community. I’m certainly missing a few authors, but I would like to thank a few specifically:

Many thanks to (amongst many others)

More posts coming up

  • Building a facebook canvas app using Django Facebook
  • Find and invite friends using Django Facebook

We’re hiring!

Do you also see the beauty in clean code? Are you experienced with high scalability web apps? Currently we’re looking for additional talent over at our Amsterdam office. Feel free to drop me a line at my personal email for more information: thierryschellenbach[at]gmail.com

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2011/06/23/django-facebook-2-0-integrating-facebook/feed/ 17
Mock Django Request for testing http://www.mellowmorning.com/2011/04/18/mock-django-request-for-testing/ http://www.mellowmorning.com/2011/04/18/mock-django-request-for-testing/#comments Mon, 18 Apr 2011 12:53:11 +0000 tschellenbach http://www.mellowmorning.com/?p=343 When testing your applications I sometimes find myself needing to mock a request object. Unfortunately it is quite hard to find a good fake request factory which mimics a normal request.

Django has a class included for this purpose called RequestFactory. However it doesn’t fake the session object, breaking most of my test code. To fix this I wrote a tiny snippet implementing the RequestFactory with session and user support. Hope it helps :)

from django.core.handlers.base import BaseHandler
from django.test.client import RequestFactory

class RequestMock(RequestFactory):
    def request(self, **request):
        "Construct a generic request object."
        request = RequestFactory.request(self, **request)
        handler = BaseHandler()
        handler.load_middleware()
        for middleware_method in handler._request_middleware:
            if middleware_method(request):
                raise Exception("Couldn't create request mock object - "
                                "request middleware returned a response")
        return request

See the gist here.

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2011/04/18/mock-django-request-for-testing/feed/ 3
Mixing Django with Jinja2 without losing template debugging http://www.mellowmorning.com/2010/08/24/mixing-django-with-jinja2-without-losing-template-debugging/ http://www.mellowmorning.com/2010/08/24/mixing-django-with-jinja2-without-losing-template-debugging/#comments Tue, 24 Aug 2010 01:26:39 +0000 Rick van Hattem http://www.mellowmorning.com/?p=321 Since I have finally set up my own blog this post has been moved to:
http://w.wol.ph/2013/07/28/mixing-django-with-jinja2-without-losing-template-debugging/

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2010/08/24/mixing-django-with-jinja2-without-losing-template-debugging/feed/ 14
Django open inviter – contact importer – python http://www.mellowmorning.com/2010/08/09/django-open-inviter-contact-importer-python/ http://www.mellowmorning.com/2010/08/09/django-open-inviter-contact-importer-python/#comments Mon, 09 Aug 2010 22:41:11 +0000 tschellenbach http://www.mellowmorning.com/?p=295 Django open inviter is a python port of the PHP api client for openinviter.com’s contact importer to work with Django. I build it for our fashion community, Fashiolista.com, where it is currently in production usage and fully functional. If you are a member of Fashiolista (which I highly doubt given the different audiences) you can test it by clicking find friends in your profile.

Usage is extremly straight forward:

from django_open_inviter.open_inviter import OpenInviter
o = OpenInviter()
contacts = o.contacts('example@example.com', 'test')

Get the code here.

Share and Enjoy: Digg Sphinn del.icio.us Facebook Mixx Google

]]>
http://www.mellowmorning.com/2010/08/09/django-open-inviter-contact-importer-python/feed/ 4