SlideShare a Scribd company logo
Integrating Facebook Connect
 authentication in your Django
          application
      Michael Trosen
      mrtrosen@lab305.com
      http://www.twitter.com/mrtrosen
      Lab305, LLC
      http://www.lab305.com
      http://djangonyc.lab305.com
      Django-NYC Presentation
      July 2nd, 2009
Django Reinhardt




•   Prominent European Jazz Musician
•   January 1910 – May 1953
•   Hurt in a fire when he was 18, played solos with only 2 fingers!
•   cofounded the Quintette du Hot Club de France
     – Information obtained from Wikipedia

          Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
?
Sorry, wrong meeting!



   Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
• Django is a high-level Python Web
  framework that encourages rapid
  development and clean, pragmatic design
• Django focuses on automating as much
  as possible and adhering to the DRY
  (Don't Repeat Yourself) principle.
• http://www.djangoproject.com
      Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
With the Facebook Connect APIs you gain access to
  ● Identity

       ●   A user's name, photos, and more
  ●   Friends
       ●   Data about a users friends
  ●   Distribution
       ●   All of the integration points within Facebook, like
           stream stories and notifications
  ●   Integration
       ●   Profile boxes, profile tabs, and publishers, just like
           apps on Facebook.


              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
What’s involved?
•   Create a Facebook Application
•   Install PyFacebook
•   Install Ryan Mark’s django-facebook app
•   Create a new django project
•   Configure your settings.py
•   Configure your urls.py
•   Create some templates
•   Create your views
•   Run your application!


       Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Assumptions
•   Using Ubuntu for development
•   Already have Django installed
•   You have git-core installed
•   You have subversion installed
•   You have mysql installed
•   You install packages to /usr/local
•   You have basic Django knowledge
•   You know what Facebook is

       Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Add the Facebook Developer
        Application
http://www.facebook.com/developers/




     Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create a Facebook App
      Setup new application




  Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create a Facebook App




  Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure Facebook App

                                                         Edit Settings




                                  IMPORTANT – API
                                  Keys

  Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure Facebook Connect
          Settings




  Connect URL: http://localhost:8000
  Connect Logo – shown in connect dialog
  box when user is validating
   Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your database
• #> mysql –u root –p
• mysql> create database djangonyc;
• mysql> quit;




       Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Install PyFacebook
• PyFacebook GitHub location
  – http://github.com/sciyoshi/pyfacebook/tree/master

• PyFacebook Tutorial:
  – http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial

• Install PyFacebook
  – #> git clone git://github.com/sciyoshi/pyfacebook.git
  – #> cd pyfacebook
  – #> python setup.py install
  – Ensure it’s working, open a python shell and try:
      • import facebook.djangofb



              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Install Ryan Mark’s
       django-facebookconnect
• Website
  – http://code.google.com/p/django-facebookconnect
• SVN Download
  – #> svn checkout http://django-facebookconnect.googlecode.com/svn/trunk/
    django-facebookconnect

• Please Note:
  – I've modified the django-facebookconnect
    django app to be a bit more functional and to
    obtain more data from facebook. This
    modified version is included in the sample
    application download
             Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create a new Django Application
• #> django-admin startproject djangonyc
• #> django-admin startapp exampleapp

• Copy the django-facebookconnect app
  into your new project
  – #> cp -R /usr/local/django-facebookconnect/django-
               facebookconnect/facebookconnect ./djangonyc/




            Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your settings.py
            Add your apps to INSTALLED_APPS


INSTALLED_APPS = (
  ‘django.contrib.auth',
    ‘django.contrib.sessions',
    ‘djangonyc.exampleapp',
    ‘djangonyc.facebookconnect',
)




               Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your settings.py
  Add the FacebookConnectMiddleware to your
              middleware_classes:
                             (order is important)


MIDDLEWARE_CLASSES =
( 'django.contrib.sessions.middleware.SessionMiddleware',
'facebook.djangofb.FacebookMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'facebookconnect.middleware.FacebookConnectMiddleware', )



            Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your settings.py
add facebook to your authentication backends



 AUTHENTICATION_BACKENDS = (
     'facebookconnect.models.FacebookBackend',
     'django.contrib.auth.backends.ModelBackend',
 )




         Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your templates dir
TEMPLATE_DIRS = (
     os.path.join(os.path.dirname(__file__), 'templates').replace('','/'),
)


   Note: This determines the path of the templates directory based of
   the location of the settings.py file




              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your database
  DATABASE_ENGINE = 'mysql'
  DATABASE_NAME = 'djangonyc'
  DATABASE_USER = 'user'
  DATABASE_PASSWORD = 'password'
  DATABASE_HOST = ''
  DATABASE_PORT = ''

Note: set the database username and password accordingly
Note: a blank host and port defaults to localhost and 3306
respectively for mysql




          Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your settings.py
       Configure Facebook Keys and Timeout
• FACEBOOK_CACHE_TIMEOUT = 1800
• FACEBOOK_API_KEY = '00000000000000000000000000000000'
• FACEBOOK_SECRET_KEY = '00000000000000000000000000000000‘
• FACEBOOK_INTERNAL = True

    Note: Set your facebook api and secret keys from the values created
    when you created your facebook application in the Facebook
    Developer Application on http://www.facebook.com




              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure some URLs
urlpatterns = patterns('',
   (r'^/?$', 'djangonyc.exampleapp.views.index'),
   (r'^accounts/profile', 'djangonyc.exampleapp.views.profile'),
   (r'^xd_receiver.html$', 'djangonyc.exampleapp.views.xd_receiver'),
   (r'^facebook/', include('facebookconnect.urls')),
)




              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Sync your database
• #> python manage.py syncdb
• We need to alter the auth_user table to
  change the size of the email column:
   – #> mysql -u root -p
   – mysql> use djangonyc;
   – mysql> alter table auth_user modify column email
     varchar(255);
 Note: In this example, do not create a super user when requested. All
 user creation is done when a user connects via facebook connect.

 Note: the email column needs to be modified because the email address
 from facebook is a proxy address that can be fairly long. You never
 receive a users 'real' email address from facebook.
             Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create a templates dir
   #> mkdir djangonyc/templates
Note: this is the directory we pointed to in the settings.py file




      Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your facebook
               xd_receiver.html file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <body>
    <script
        src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommRece
        iver.js" type="text/javascript">
    </script>
    </body>
</html>


        Note: this file is put in the templates directory
        (djangonyc/templates/xd_receiver.html)



               Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
create your base.html file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:fb="http://www.facebook.com/2008/fbml">
{% load facebook_tags %}
<head>
  {% facebook_js %}
  {% initialize_facebook_connect %}
</head>
<body>
  <div id='user'>
     {% if USER_LOGGED_IN %}
       <table border='0'> <tr> <td>
           Welcome {% show_facebook_first_name user %} {% show_logout %} <br />
           {% show_facebook_photo user %}
        </td> </tr>
        </table>
    {% else %}
      <table border='0'><tr>
            <td nowrap valign='middle' align='center'> {% show_connect_button %} </td>
            <td valign='middle' align='center'></td>
            </tr> </table>
    {% endif %}
   </div>
   {% block 'content' %} Page content here. {% endblock %}
</body>
</html>
                 Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
create your index.html file

  {% extends 'base.html' %}




   Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your profile.html page
{% extends 'base.html' %}                       Any page that uses the templates
{% load facebook_tags %}                        must load the tags
{% block 'content' %}
<div>
<form action="/accounts/profile/" method="post" name="profileForm" id="profileForm"> <table>
   <tr><td> <table border='0'>
    <tr>
    <td colspan='2'>
     <span>
        <label for="Fname">Name:</label><br>
        <input id="nameUser" name="nameUser" type="text" readonly
                value="{% show_facebook_full_name user %}">
    </span>
   </td>                                                              Facebook tag
  </tr>
  </table>
   </td>
   <td align='center' valign='top'>
            Facebook Profile Image<br />
            {% show_facebook_large_photo user %}
   </td>
   </tr></table>
</form> </div> </div>
{% endblock %}

                  Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your views
                       Imports

•from django.http import HttpResponseRedirect
•from django.shortcuts import render_to_response
•from django.conf import settings
•from django.template import RequestContext




       Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your views
                              index
def index(request):
  user = ''
  if request.user.is_authenticated():
      user = request.user.facebook_profile
  return render_to_response(
      "index.html",
      {
      'USER_LOGGED_IN': request.user.is_authenticated(),
      'user': user,
      },
      context_instance=RequestContext(request)
  )

               Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your views
                              profile
def profile(request):
  page = 'profile'
  user = ''

  if request.user.is_authenticated():
      user = request.user.facebook_profile
      friendList = request.user.facebook_profile.get_friends_profiles()
  else:
      print "REDIRECTING"
      return HttpResponseRedirect("/")
  return render_to_response(
      "profile.html",
      {
          'page': page,
          'USER_LOGGED_IN': request.user.is_authenticated(),
          'user': user,
          'friendList': friendList,
      },
      context_instance=RequestContext(request)
  )
Create your views
                            xd_receiver

def xd_receiver(request):
       return render_to_response('xd_receiver.html')




             Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Run your new application
• #> python manage.py runserver
 Note: the default port will be 8000. We pointed the Connect setting in your
 facebook application to be: http://localhost:8000

 You can view the running local app at: http://localhost:8000 on your local
 computer.




               Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
facebookconnect info
• Pluggable App
• Various settings/facebook values located
  in the facebookconnect
• I modified Ryan Marks code and added in
  more facebook values, and return all
  values from facebook




        Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Location of all dependencies
• Django
  – http://www.djangoproject.com
• Pyfacebook
  – http://wiki.developers.facebook.com/index.php/Python
• Django-facebookconnect
  – http://ryan-mark.com/2009/04/02/django-facebook-connect/
• Sample App Source Code
  – http://media.lab305.com/djangonyc-1.0.tgz




           Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Any Questions
• Example app can be viewed at:
  – http://djangonyc.lab305.com
• Full source code of example site is locate
  available
  – http://media.lab305.com/djangonyc-1.0.tgz
• Please send a tweet or email if you found
  this useful or if you have any questions, or
  if you want to hire us to help you!
  – http://www.twitter.com/mrtrosen
  – mrtrosen@lab305.com
         Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen

More Related Content

PPTX
How to use blogging for an allergist's practice
PPT
Ignite raleigh henry copeland 2010
PDF
TEDx Thessaloniki - The web is dead?
PPTX
Cyberbullying Investigation/Reporting/ Procedures
PDF
Tracking online conversations with Yahoo Pipes
PDF
Pwned in high ed
ODP
Pimp My Web Page
PDF
Get More Links to Your Site With the Skyscraper Technique
How to use blogging for an allergist's practice
Ignite raleigh henry copeland 2010
TEDx Thessaloniki - The web is dead?
Cyberbullying Investigation/Reporting/ Procedures
Tracking online conversations with Yahoo Pipes
Pwned in high ed
Pimp My Web Page
Get More Links to Your Site With the Skyscraper Technique

Similar to Lab305 Django Facebook Connect Integration Example (20)

PDF
Facebook Connect Tutorial
KEY
國民雲端架構 Django + GAE
PPTX
Social login integration
PPTX
Facebook appsincloud
PPTX
Django course
ODP
Presentasi jlp
PDF
Write FB Bot in Python3
PDF
a hands on guide to django
PPTX
Django Framework Interview Guide - Part 1
PDF
Building TweetEngine
PPTX
Facebook Messenger Bot with Flask & Google App Engine
ZIP
Facebook Developer Garage Milan
PPT
Introduction to python scrapping
PDF
Django Overview
PDF
django_introduction20141030
PDF
Build social apps for Facebook
DOCX
Akash rajguru project report sem v
PPTX
PDF
Introduction to Facebook Python API
PDF
Facebook Python SDK - Introduction
Facebook Connect Tutorial
國民雲端架構 Django + GAE
Social login integration
Facebook appsincloud
Django course
Presentasi jlp
Write FB Bot in Python3
a hands on guide to django
Django Framework Interview Guide - Part 1
Building TweetEngine
Facebook Messenger Bot with Flask & Google App Engine
Facebook Developer Garage Milan
Introduction to python scrapping
Django Overview
django_introduction20141030
Build social apps for Facebook
Akash rajguru project report sem v
Introduction to Facebook Python API
Facebook Python SDK - Introduction
Ad

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Big Data Technologies - Introduction.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
sap open course for s4hana steps from ECC to s4
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
The Rise and Fall of 3GPP – Time for a Sabbatical?
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Network Security Unit 5.pdf for BCA BBA.
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Approach and Philosophy of On baking technology
Building Integrated photovoltaic BIPV_UPV.pdf
Unlocking AI with Model Context Protocol (MCP)
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Programs and apps: productivity, graphics, security and other tools
NewMind AI Weekly Chronicles - August'25 Week I
Big Data Technologies - Introduction.pptx
Ad

Lab305 Django Facebook Connect Integration Example

  • 1. Integrating Facebook Connect authentication in your Django application Michael Trosen mrtrosen@lab305.com http://www.twitter.com/mrtrosen Lab305, LLC http://www.lab305.com http://djangonyc.lab305.com Django-NYC Presentation July 2nd, 2009
  • 2. Django Reinhardt • Prominent European Jazz Musician • January 1910 – May 1953 • Hurt in a fire when he was 18, played solos with only 2 fingers! • cofounded the Quintette du Hot Club de France – Information obtained from Wikipedia Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 3. ? Sorry, wrong meeting! Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 4. • Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design • Django focuses on automating as much as possible and adhering to the DRY (Don't Repeat Yourself) principle. • http://www.djangoproject.com Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 5. With the Facebook Connect APIs you gain access to ● Identity ● A user's name, photos, and more ● Friends ● Data about a users friends ● Distribution ● All of the integration points within Facebook, like stream stories and notifications ● Integration ● Profile boxes, profile tabs, and publishers, just like apps on Facebook. Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 6. What’s involved? • Create a Facebook Application • Install PyFacebook • Install Ryan Mark’s django-facebook app • Create a new django project • Configure your settings.py • Configure your urls.py • Create some templates • Create your views • Run your application! Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 7. Assumptions • Using Ubuntu for development • Already have Django installed • You have git-core installed • You have subversion installed • You have mysql installed • You install packages to /usr/local • You have basic Django knowledge • You know what Facebook is Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 8. Add the Facebook Developer Application http://www.facebook.com/developers/ Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 9. Create a Facebook App Setup new application Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 10. Create a Facebook App Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 11. Configure Facebook App Edit Settings IMPORTANT – API Keys Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 12. Configure Facebook Connect Settings Connect URL: http://localhost:8000 Connect Logo – shown in connect dialog box when user is validating Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 13. Create your database • #> mysql –u root –p • mysql> create database djangonyc; • mysql> quit; Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 14. Install PyFacebook • PyFacebook GitHub location – http://github.com/sciyoshi/pyfacebook/tree/master • PyFacebook Tutorial: – http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial • Install PyFacebook – #> git clone git://github.com/sciyoshi/pyfacebook.git – #> cd pyfacebook – #> python setup.py install – Ensure it’s working, open a python shell and try: • import facebook.djangofb Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 15. Install Ryan Mark’s django-facebookconnect • Website – http://code.google.com/p/django-facebookconnect • SVN Download – #> svn checkout http://django-facebookconnect.googlecode.com/svn/trunk/ django-facebookconnect • Please Note: – I've modified the django-facebookconnect django app to be a bit more functional and to obtain more data from facebook. This modified version is included in the sample application download Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 16. Create a new Django Application • #> django-admin startproject djangonyc • #> django-admin startapp exampleapp • Copy the django-facebookconnect app into your new project – #> cp -R /usr/local/django-facebookconnect/django- facebookconnect/facebookconnect ./djangonyc/ Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 17. Configure your settings.py Add your apps to INSTALLED_APPS INSTALLED_APPS = ( ‘django.contrib.auth', ‘django.contrib.sessions', ‘djangonyc.exampleapp', ‘djangonyc.facebookconnect', ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 18. Configure your settings.py Add the FacebookConnectMiddleware to your middleware_classes: (order is important) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'facebook.djangofb.FacebookMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'facebookconnect.middleware.FacebookConnectMiddleware', ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 19. Configure your settings.py add facebook to your authentication backends AUTHENTICATION_BACKENDS = ( 'facebookconnect.models.FacebookBackend', 'django.contrib.auth.backends.ModelBackend', ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 20. Configure your templates dir TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates').replace('','/'), ) Note: This determines the path of the templates directory based of the location of the settings.py file Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 21. Configure your database DATABASE_ENGINE = 'mysql' DATABASE_NAME = 'djangonyc' DATABASE_USER = 'user' DATABASE_PASSWORD = 'password' DATABASE_HOST = '' DATABASE_PORT = '' Note: set the database username and password accordingly Note: a blank host and port defaults to localhost and 3306 respectively for mysql Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 22. Configure your settings.py Configure Facebook Keys and Timeout • FACEBOOK_CACHE_TIMEOUT = 1800 • FACEBOOK_API_KEY = '00000000000000000000000000000000' • FACEBOOK_SECRET_KEY = '00000000000000000000000000000000‘ • FACEBOOK_INTERNAL = True Note: Set your facebook api and secret keys from the values created when you created your facebook application in the Facebook Developer Application on http://www.facebook.com Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 23. Configure some URLs urlpatterns = patterns('', (r'^/?$', 'djangonyc.exampleapp.views.index'), (r'^accounts/profile', 'djangonyc.exampleapp.views.profile'), (r'^xd_receiver.html$', 'djangonyc.exampleapp.views.xd_receiver'), (r'^facebook/', include('facebookconnect.urls')), ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 24. Sync your database • #> python manage.py syncdb • We need to alter the auth_user table to change the size of the email column: – #> mysql -u root -p – mysql> use djangonyc; – mysql> alter table auth_user modify column email varchar(255); Note: In this example, do not create a super user when requested. All user creation is done when a user connects via facebook connect. Note: the email column needs to be modified because the email address from facebook is a proxy address that can be fairly long. You never receive a users 'real' email address from facebook. Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 25. Create a templates dir #> mkdir djangonyc/templates Note: this is the directory we pointed to in the settings.py file Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 26. Create your facebook xd_receiver.html file <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <body> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommRece iver.js" type="text/javascript"> </script> </body> </html> Note: this file is put in the templates directory (djangonyc/templates/xd_receiver.html) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 27. create your base.html file <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> {% load facebook_tags %} <head> {% facebook_js %} {% initialize_facebook_connect %} </head> <body> <div id='user'> {% if USER_LOGGED_IN %} <table border='0'> <tr> <td> Welcome {% show_facebook_first_name user %} {% show_logout %} <br /> {% show_facebook_photo user %} </td> </tr> </table> {% else %} <table border='0'><tr> <td nowrap valign='middle' align='center'> {% show_connect_button %} </td> <td valign='middle' align='center'></td> </tr> </table> {% endif %} </div> {% block 'content' %} Page content here. {% endblock %} </body> </html> Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 28. create your index.html file {% extends 'base.html' %} Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 29. Create your profile.html page {% extends 'base.html' %} Any page that uses the templates {% load facebook_tags %} must load the tags {% block 'content' %} <div> <form action="/accounts/profile/" method="post" name="profileForm" id="profileForm"> <table> <tr><td> <table border='0'> <tr> <td colspan='2'> <span> <label for="Fname">Name:</label><br> <input id="nameUser" name="nameUser" type="text" readonly value="{% show_facebook_full_name user %}"> </span> </td> Facebook tag </tr> </table> </td> <td align='center' valign='top'> Facebook Profile Image<br /> {% show_facebook_large_photo user %} </td> </tr></table> </form> </div> </div> {% endblock %} Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 30. Create your views Imports •from django.http import HttpResponseRedirect •from django.shortcuts import render_to_response •from django.conf import settings •from django.template import RequestContext Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 31. Create your views index def index(request): user = '' if request.user.is_authenticated(): user = request.user.facebook_profile return render_to_response( "index.html", { 'USER_LOGGED_IN': request.user.is_authenticated(), 'user': user, }, context_instance=RequestContext(request) ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 32. Create your views profile def profile(request): page = 'profile' user = '' if request.user.is_authenticated(): user = request.user.facebook_profile friendList = request.user.facebook_profile.get_friends_profiles() else: print "REDIRECTING" return HttpResponseRedirect("/") return render_to_response( "profile.html", { 'page': page, 'USER_LOGGED_IN': request.user.is_authenticated(), 'user': user, 'friendList': friendList, }, context_instance=RequestContext(request) )
  • 33. Create your views xd_receiver def xd_receiver(request): return render_to_response('xd_receiver.html') Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 34. Run your new application • #> python manage.py runserver Note: the default port will be 8000. We pointed the Connect setting in your facebook application to be: http://localhost:8000 You can view the running local app at: http://localhost:8000 on your local computer. Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 35. facebookconnect info • Pluggable App • Various settings/facebook values located in the facebookconnect • I modified Ryan Marks code and added in more facebook values, and return all values from facebook Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 36. Location of all dependencies • Django – http://www.djangoproject.com • Pyfacebook – http://wiki.developers.facebook.com/index.php/Python • Django-facebookconnect – http://ryan-mark.com/2009/04/02/django-facebook-connect/ • Sample App Source Code – http://media.lab305.com/djangonyc-1.0.tgz Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 37. Any Questions • Example app can be viewed at: – http://djangonyc.lab305.com • Full source code of example site is locate available – http://media.lab305.com/djangonyc-1.0.tgz • Please send a tweet or email if you found this useful or if you have any questions, or if you want to hire us to help you! – http://www.twitter.com/mrtrosen – mrtrosen@lab305.com Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen