Post to Facebook on Behalf of Your User with Python/Django

Posting on facebook through python is fairly simple: you need acquire your user’s facebook access token, which you use to access the users facebook wall.
Step 1: Create the facebook app
First, create a new facebook app on and note down the APP_ID and APP_SECRET. Store this information in your django file.
Step 2: Acquire an oauth code
To acquire an oauth code, simply redirect your user to the following url: along with these arguments:

'client_id': Your facebook app id
'redirect_uri': The url of your web app which will handle the redirect back from facebook
'scope': types of privileges to request from the user

We get:

def acquire_facebook_oauth_code(request):
    redirect_uri = 'http://your_cool_web_app/handle_facebook_redirect/'
    attrs = {'client_id': settings.FACEBOOK_APP_ID,
             'redirect_uri': redirect_uri,
    code_url = ''  % urllib.urlencode(attrs)
    return redirect(code_url)

Step 3: Handle the redirect from facebook
Upon successful signin and approval of your user, facebook will redirect back to the ‘redirect_uri’ used above, with an additional ‘code’ argument in the following format:
We can now use this code to acquire the access_token:

def handle_facebook_redirect(request):
    code = request.GET.get('code')
    attrs = {'client_id': settings.FACEBOOK_APP_ID,
             'client_secret': settings.FACEBOOK_APP_SECRET,
             'code': code }
    access_token_url = '' % urllib.urlencode(attrs)
    r = requests.get(access_token_url)
    access_token = urlparse.parse_qs(r.content)['access_token'][0]
    # save the access_token for your user
    user_profile = request.user.get_profile()
    user_profile.facebook_access_token = access_token
    return redirect('facebook_succeeded_page')

Step 4: Final step, use the access token to share on the facebook wall
Now that we have the access token saved, we can update the users status by sending a post request to

def share_on_facebook(request):
    payload = dict(message="Your fancy facebook wall status"),
    req ='', data=payload)
    return redirect('facebook_share_succeeded_page')

Make sure to import urllib, urlparse and requests when using the above code. The first two are built into python but requests can be installed with:

sudo pip install requests