shabda
Comments
Reactions

How to build a Facebook app in Django

By : Shabda Raaj

Facebook has a simple and robust API which allows users to build applications for the Facebook platform. We being the intelligent developers will use the superb Django framework to build our application.

The completed code for this is available at https://svn.uswaretech.com/favlang/. The completed application is deployed to facebook here.

How does a Facebook application work?

  1. The users make a request to apps.facebook.com/yourapp/page1/
  2. The Facebook servers make a request to yourserver.com/page1/
  3. You get the requests and can make calls to Facebook API, and use FQL to query the Facebook tables.
  4. You send back a page written in FBML to FB servers.
  5. FB servers render your FBML to HTML.
  6. FB servers send a HTML request to the user.

What tools does FB provide you?

  1. FQL: Facebook Query Language. This is a language similar to SQL. Sample this

SELECT name, pic FROM user WHERE uid=211031 OR uid=4801660

  1. Facebook API: This is a set of RESTful urls which can be used to get data from Facebook and to do actions on the behalf of the logged in users.

  2. FBML: Facebook Markup Language. This is a set of tags, similar to Html tags, which allow you to get your page rendered with extra information on the facebook servers.

<fb:name uid="211031">

would show the name of the user with the id.

What else do you need?

  1. A server, which can run Django. Duh.
  2. We are using Python, so we can use FB rest API directly. But somebody has already done the hard work and written the awesome Pyfacebook library, which makes talking to Facebook a breeze.

What will we build?

We will build a application which allows you to store your favorite programming language at Facebook. This has a single page with single input box where you can store your favorite programming language.

The completed code for this is available at https://svn.uswaretech.com/favlang/. The completed application is deployed to facebook here.

Getting Started

  1. Go to http://www.facebook.com/developers/
  2. Create a new app, give it a name.
  3. Get your application api key, and application secret.
  4. Map callback url to the base of your Server.
  5. Download the Pyfacebook library, and put it where Python can find it. The following import statements should work. import facebook and import facebook.djangofb

Setting up your App

  1. Edit settings.py and add the following settings.

    FACEBOOK_API_KEY = '1673458a9d3ddaa8c6f888d7150da256'
    FACEBOOK_SECRET_KEY = '666197caab406752474bd0c6695a53f6'

  2. Add facebook.djangofb.FacebookMiddleware to MIDDLEWARE_CLASSES

  3. Create an app named Favlang to hold our Code.

Our App

Its a simple Django app with Models, views and Urls. The only difference with a normal Django app is that, a. The templates are in FBML. b. We will use FQL and FBAPI to talk to FB.

Urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('favlang.views',
    (r'^$', 'canvas'),
)

A basic Urlpatter, mapping patterns to views, nothing FB specific to see here.

Models.py

from django.db import models

class FacebookUser(models.Model):
    """A simple User model for Facebook users."""

    # We use the user's UID as the primary key in our database.
    id = models.IntegerField(primary_key=True)
    language = models.CharField(max_length=64, default='Python')

A normal models.py. Nothing FB specific to see here. (Instead of an autoincrementing PK, we have a PK which we will set manually to FB uid.)

Views.py

from django.http import HttpResponse
from django.views.generic.simple import direct_to_template

import facebook.djangofb as facebook

from favlang.models import FacebookUser

@facebook.require_login()
def canvas(request):
    # Get the User object for the currently logged in user
    user, created = FacebookUser.objects.get_or_create(id = request.facebook.uid)

    # Check if we were POSTed the user's new language of choice
    if 'language' in request.POST:
        user.language = request.POST['language'][:64]
        user.save()

    # User is guaranteed to be logged in, so pass canvas.fbml
    # an extra 'fbuser' parameter that is the User object for
    # the currently logged in user.
    return direct_to_template(request, 'favlang/canvas.fbml', extra_context={'fbuser': user})

Ok. SO finally something FB specific. Lets see what is happening behind the scenes.

  1. We are putting our view behind a @facebook.require_login() decorator. This is similar to the login_required decorator. It makes sure that a valid FB user is logged in before it allows access to our view.

  2. The Middleware facebook.djangofb.FacebookMiddleware attaches a facebook object to the request, which provides access to the logged in user and some other relevant data.

  3. We created a FacebookUser for the currently logged in user, in our database, with this line.

user, created = FacebookUser.objects.get_or_create(id = request.facebook.uid)

  1. We returned the FBML with our data. The FBML is parsed by the Facebook servers and HTML returned to the user.

The template

<fb:header>
  {% comment %}
    We can use {{ fbuser }} to get at the current user.
    {{ fbuser.id }} will be the user's UID, and {{ fbuser.language }}
    is his/her favorite language (Python :-).
  {% endcomment %}
  Welcome, <fb:name uid="{{ fbuser.id }}" firstnameonly="true" useyou="false">!
</fb:name>

<div class="clearfix" style="border: 1px solid rgb(216, 223, 234); padding: 10px; float: left; margin-left: 30px; margin-bottom: 30px; width: 500px;">
  Your favorite language is {{ fbuser.language }}.
  <br><br>

  <div class="grayheader clearfix">
    <br><br>

    <form action="." method="post">
      <input name="language" value="{{ fbuser.language }}" type="text">
      <input value="Change" type="submit">
    </form>
  </div>
</div>

This template is written in FBML. FBML is a superset of HTML. The tags which start with <fb: are="" facebook="" specific="" tags.="" for="" example="" the="" tag="" fb:name="" =""><fb:name uid="{{ fbuser.id }}" firstnameonly="true" useyou="false"> renders the name of the user whose uid is passed in uid.

There is also a form which allows user to change their Favorite language. In views.py this is handled as

if 'language' in request.POST:
    user.language = request.POST['language'][:64]
    user.save()

Resources.

  1. Facebook developers.
  2. Facebook developers wiki.
  3. Facebook developers forum.
  4. [Pyfacebook]
  5. FBAPI Documentation
  6. FQL Documentation
  7. FBML Documentation

  8. Code listing

  9. Live Application


Related Posts


Can we help you build amazing apps? Contact us today.

Topics : facebook

Comments

johannes

thanks alot for your tutorial! it's great to have a django facebook app 'framework'.

i stepped over some traps while following your tutorial:

somewhere before "Getting Started" you might have forgotten to mention 'django-admin.py startproject facebook_sample'.

in that case, facebook_sample.favlang must be added to INSTALLED_APPS in settings.py.

in views.py i changed the import path from 'from favlang.models import FacebookUser' to 'from facebook_sample.favlang.models import FacebookUser'

also you might not have mentioned where to store the template canvas.fbml ('templates/favlang/canvas.fbml' in favlang app folder).

finally, i've created a location for the favlang app in my apache's httpd.conf:

SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE facebook_sample.settings
PythonOption django.root /favlang
PythonDebug On

and added this app as my callback url in facebook:
http://mydomain.com/favlang/

thank you again for your great tutorial!!!

commmenttor
Linoleum

How to build a Facebook app in Django...

From the Usawaretech Blog comes this incredibly detailed tutorial on using Django to write applications for Facebook.

It gives a brief overview on how Facebook applications communicate with the server, walks through setting up the application api ke...

commmenttor
Alvaro Brange

Hi,
Thank you for show it. It worked very well to me, using Django, PostreSQL and Ubuntu, the site will available on: www.wetwoo.com
Regards,
Álvaro

commmenttor
Dougal Matthews

6. FB servers send a HTML request to the user.

should be

6. FB servers return a HTML response to the user.

commmenttor
Bryan 18th May, 2009

Thanks for taking the time to post this!

commmenttor
webspinner 3rd Sept., 2009

Thanks for this tutorial.
How do you get the form parameters ?
if 'language' in request.POST:
user.language = request.POST['language'][:64]
user.save()

What are the parameters in request.POST?

commmenttor
David

Thank you very much for this wonderful tutorial. I appreciate it. Up and running on Facebook now!

commmenttor
madeeha

all the peoples are same

commmenttor
affan

The tutorial here: http://wiki.developers.facebook.com/index.php/User:PyFacebook_Tutorial says that it doesn't work with Django 1.x, any idea which version of Django it would work with?

commmenttor
pirosb3

Awesome library!!
And very nice tutorial too! simple and clear ;)

commmenttor
Sam Stoelinga

With the Graph API out, should we use the Graph API instead? But some parts overlap such as the FBML I guess.

This is a new library to build facebook apps with Django: http://readthedocs.org/docs/fandjango/en/latest/ and uses the new Graph API. Found it the same way I found this blog.

commmenttor
Cheap Oakley Batwolf Sunglasses For Sale

How to build a Facebook app in Django - Agiliq Blog | Django web app development

commmenttor
uggs winter boots

ugg boots deals How to build a Facebook app in Django - Agiliq Blog | Django web app development
uggs winter boots http://www.genecurry.com/dublin/uggs-winter-boots.html

commmenttor
uk nike cowboys authentic dez bryant green navy white elite limited on sales

Report of favourable options to discover more regarding nfl jersey before you are abandoned.
uk nike cowboys authentic dez bryant green navy white elite limited on sales http://www.akumaneko.com/products/cheap-girl-baseball-hats/2013-pro-bowl-jerseys-for-kids/haaiiamc-p-928.html

commmenttor
shop ugg boots sale

ugg boots price How to build a Facebook app in Django - Agiliq Blog | Django web app development
shop ugg boots sale http://www.millinerysupplies.ie/clearance/shop-ugg-boots-sale.html

commmenttor
big discount nike saints authentic roman harper orange navy white elite limited store online

nfl jersey Counterfeits - - An Awesome nfl jersey hack That experts claim Fools 92% of the users
big discount nike saints authentic roman harper orange navy white elite limited store online http://www.airmartechnology.com/catimages/soccer-goalkeeping-jerseys/cheap-nfl-jerseys-low-shipping/rffhhlgy-p-356.html

commmenttor
luxury nike bills authentic steve johnson blue navy white elite limited at our professional store

Something Every single person Ought To Know On nfl jersey
luxury nike bills authentic steve johnson blue navy white elite limited at our professional store http://www.flsincorp.net/blue/cheap-team-jerseys-football/pro-football-jerseys-wholesale/eztitzdk-p-746.html

commmenttor
shopping nike brett keisel womens jersey steelers orange navy white authentic soaking up summer fun

Fed up with the nfl jersey trends? I'm on this website on your behalf
shopping nike brett keisel womens jersey steelers orange navy white authentic soaking up summer fun http://www.apnadeccan.com/articles/cheap-nhl-jerseys-australia/arsenal-jersey-cheap/ugpgqkov-p-790.html

commmenttor
shop cheap marques colston game jersey: saints womens youth orange navy white free 50g in every pack

nfl jersey adds brand-new life into an old matter-- silver paradigm
shop cheap marques colston game jersey: saints womens youth orange navy white free 50g in every pack http://www.hcdubai.com/discount/nfl-jerseys-made-in-usa/college-football-replica-jerseys/oepgckcl-p-262.html

commmenttor
on sale uggs

uggs mens slippers How to build a Facebook app in Django - Agiliq Blog | Django web app development
on sale uggs http://sallyfortfarm.com/website/on-sale-uggs.html

commmenttor
our cheap discount authentic jeremy kerley orange navy white ladies mens kids sale outlet

Finish your meal and wind down While Figuring out the Tricks of nfl jersey
our cheap discount authentic jeremy kerley orange navy white ladies mens kids sale outlet http://www.suffolktrainstation.org/brown/football-jerseys-dallas/custom-pink-jerseys/xdgiewzt-p-977.html

commmenttor
fashion nate washington black gold white jersey throwback titans elite limited sale cheap

Peculiar write-up offers the small print around nfl jersey which only a couple of persons are conscious of.
fashion nate washington black gold white jersey throwback titans elite limited sale cheap http://www.asia-bolt.com/abouts/online-wholesale-mlb-jerseys/qbktcgik-p-187.html

commmenttor
cheap authentic aaron rodgers jersey womens mens youth navy blue white clearance sale

The things you do not fully understand regarding nfl jersey is likely to be costing much more than you may think.
cheap authentic aaron rodgers jersey womens mens youth navy blue white clearance sale http://bigdoggalleries.com/artists/netherlands-soccer-jersey/fgggqszh-p-101.html

commmenttor
best selling authentic jake locker brown orange white ladies mens kids up to 80% off discount

Components and formation throughout Nevada : nfl jersey actually leaves without good-bye
best selling authentic jake locker brown orange white ladies mens kids up to 80% off discount http://www.cash4giftcards.com/eby/official-soccer-jerseys/dgmdkviw-p-735.html

commmenttor
price explosion nike stevan ridley womens jersey patriots navy blue white authentic for sale

The Incredible Hush-hush Of Methods One Could Command nfl jersey Without The Need For Practical knowledge!
price explosion nike stevan ridley womens jersey patriots navy blue white authentic for sale http://www.dcgwest.com/contact/giants-nike-jersey/nike-stevan-ridley-womens-jersey-p-7123.html

commmenttor
price melt down andre johnson jersey nike texans authentic andre johnson blue grey white outlet york

Testing And Tracking nfl jersey So That You Could Rock The nfl jersey Realm
price melt down andre johnson jersey nike texans authentic andre johnson blue grey white outlet york http://www.ubupopland.com/Booking/italian-soccer-team-jerseys/qrbgwlna-p-734.html

commmenttor
black friday gucci porta passaporto 245820 a7m0n 2140 gucci handbags outlet off 60%

Update an gucci within half the time without spending additional money!
black friday gucci porta passaporto 245820 a7m0n 2140 gucci handbags outlet off 60% http://www.elementaurs.com/blog/herve-leger-flared-dress/nxcqnswf-p-627.html

commmenttor
cheap authentic michael michael kors uptown astor large shoulder tote black leather factory outlet

The Spectacular MK Trick That Are Able To Fool Everyone
cheap authentic michael michael kors uptown astor large shoulder tote black leather factory outlet http://www.foulire.com/eleves/michael-kors-jelly-sandals/hghdimze-p-936.html

commmenttor
uggs on sale

I really feel strongly about it and love reading extra on this topic. If potential, as you turn out to be experience, would you mind updating your blog with extra particulars?

commmenttor
harvest of values tony gonzalez black gold white jersey throwback falcons elite limited coupons

The Astounding Income Generation Potential Of nfl jersey
harvest of values tony gonzalez black gold white jersey throwback falcons elite limited coupons http://www.rittenhouseacupuncture.com/products/signed-hockey-jerseys/football-jersey-from-china/lyuwlugy-p-726.html

commmenttor
women ugg boots sale

www.uggs How to build a Facebook app in Django - Agiliq Blog | Django web app development
women ugg boots sale http://www.gullionviewpiggies.com/discount/women-ugg-boots-sale.html

commmenttor
full colours gucci handbag techno horsebit 240260 fpo1n 9014 gucci outlet online outlet sale

gucci-babe has certified the latest strategy : the steps to make a king's ransom from scratch
full colours gucci handbag techno horsebit 240260 fpo1n 9014 gucci outlet online outlet sale http://www.nehlsrealty.com/page/authentic-gucci-purse/gucci-size-chart/gucci-handbag-techno-horsebit-240260-fpo1n-9014---gucci-outlet-online-p-7483.html

commmenttor
best cheap moncler coats women breasted pure color white clearance

MONCLER-youngster has trialled this latest method - steps to make a fortune on your own
best cheap moncler coats women breasted pure color white clearance http://www.mdgfoa.org/gray/women-moncler-vest/sxylpdes-p-298.html

commmenttor
online cheap michael kors newman large shoulder tote black python embossed patent leather for sales

This Is The Tactic That Is Even Aiding MK-professionals To Expand
online cheap michael kors newman large shoulder tote black python embossed patent leather for sales http://giftcards4less.com/azshipping/where-are-michael-kors-purses-made/qiubmaok-p-442.html

commmenttor
cheap price nike jordy nelson womens jersey packers navy white silver authentic early bird specials

Stuff and fabrication in Vermont - nfl jersey has left without any adios
cheap price nike jordy nelson womens jersey packers navy white silver authentic early bird specials http://www.mountgambiertourism.com.au/files/cheap-hockey-jerseys-for-sale/nhl-steeler-jerseys-in-store/sqytihte-p-994.html

commmenttor
best authentic paul kruger jersey womens mens youth blue grey white outlet us online

Notice - Do Not Attempt to go by the other nfl jersey Instructions Before You Read This Cost-free Documentation
best authentic paul kruger jersey womens mens youth blue grey white outlet us online http://www.abshearlandscape.com/products/cheap-china-nike-nfl-jerseys/qqsnfovi-p-477.html

commmenttor
cheap price nike andre johnson womens jersey texans blue white red authentic supplier

Something all the others does with regards to nfl jersey and furthermore the things that youshould do completely different.
cheap price nike andre johnson womens jersey texans blue white red authentic supplier http://3dbeaufort.com/news/men-american-football-jerseys/nike-reversible-basketball-jerseys/fblgzszo-p-321.html

commmenttor
nail down a great rate authentic philip wheeler black white gold ladies mens kids for sales

The particular reason why almost anything that you've learned about nfl jersey is undoubtedly drastically wrong and what you want to learn.
nail down a great rate authentic philip wheeler black white gold ladies mens kids for sales http://www.alonarodeh.com/content/buy-nfl-pro-bowl-jerseys/authentic-cheap-jerseys-nba/authentic-philip-wheeler--black-white-gold-ladies-mens-kids-p-2467.html

commmenttor
shop for matt ryan jersey nike falcons authentic matt ryan red white gold sale cheap

Actual Procedures To Fully grasp nfl jersey And Ways One Could Enroll with The nfl jersey Elite
shop for matt ryan jersey nike falcons authentic matt ryan red white gold sale cheap http://www.catchthewaveministries.com/Tracts/recommended-best-soccer-jerseys-2013/gbcwbigd-p-75.html

commmenttor
Fake designer Givenchy bags

Fast ship. Merch as promised. Great Transaction!

commmenttor
prezzo scarpe prada luna rossa

The New York based company has sold, licensed, or closed a bunch of underperforming brands in recent years to switch its attention to its own retail stores.Completed transactions were generating $471 million in cash proceeds since August, Liz Claiborne said.October direct to consumer comparable sales were in line overall with the company's expectations as it heads into the Holiday season, Chief Executive William McComb said.Gross profit margins at the company rose to 53.7 percent from 50 percent last year, as it made money from licensing its namesake brand to JC Penney and sold more products at its high margin direct brands segment.For the third quarter, the company earned $2 million, or 2 cents a share from continuing operations, compared with a loss from continuing operations of $42 million, or 45 cents per share, last year.On an adjusted basis, it earned 5 cents a share from continuing operations, while analysts on average had expected a loss of 5 cents, according to Thomson Reuters I/B/E/S.Sales fell 9.1 percent to $398 million. However, excluding the impact of a $31 million decline in net sales of brands that have been licensed or exited, sales decreased 1.9 percent, the company said.Liz Claiborne shares closed at $8.37 on Tuesday on the New York Stock Exchange. Thomson Reuters journalists are subject to an Editorial Handbook which requires fair presentation and disclosure of relevant interests.Liz Claiborne

commmenttor
uggs on sale

ugg boots for men for cheap How to build a Facebook app in Django - Agiliq Blog | Django web app development
uggs on sale http://www.walkair.ie/sizing/uggs-on-sale.html

commmenttor
jordan femme grossesse 7eme mois

Das Camp Hill B眉ro befindet sich in 4075 Market Street.

commmenttor
official burberry medium tie dye smoked check tote bag 37541901 brown supplier

Whatever the authorities are generally not declaring in relation to BUBERRY and also the way it is affecting you actually.
official burberry medium tie dye smoked check tote bag 37541901 brown supplier http://www.gestalt-mty.com/articles/burberry-scarf-for-sale/utlgangr-p-12.html

commmenttor
65% discount air jordan 26 kids dark grey red see how low we can go

Neutral guide unwraps Some brand new things surrounding babyliss that no company is bringing up.
65% discount air jordan 26 kids dark grey red see how low we can go http://www.eaglespepband.com/images/air-jordan-outlet-store/air-jordan-6-retro-white-grey-blue-p-3786.html

commmenttor

Reactions

bsergean

Pretty cool.

This comment was originally posted on Reddit

rictic

There’s also an article series on this subject here: http://lethain.com/entry/2007/dec/04/two-faced-django-part-1-building-project-exists-si/

This comment was originally posted on Reddit

nitemayr

How to Build a Facebook Application in Django! http://bit.ly/DY591

This comment was originally posted on Twitter

ozgurv

How to build a Facebook app in Django http://bit.ly/DY591

This comment was originally posted on Twitter

aaloy

Django i Facebook, ben explicadet a http://bit.ly/DY591

This comment was originally posted on Twitter

© Agiliq, 2009-2012