EzDevInfo.com

Django-facebook

Facebook open graph api implementation using the Django web framework in python Mellow Morning

Django: Full fledge Facebook and Twitter integration (Django-Facebook, django-social-auth, django-allauth)

Before I post my question I would like to tell you that I'm aware of few excellent django packages out there for twitter and facebook integration:

So, here's my question:

What I want?

I want to:

  1. Allow users to registration via facebook and twitter. (easy to implement using any of above).
  2. Allow multiple social accounts integration into one user account. (I think both #2 and #3 can do it.)
  3. Create profile from facebook or twitter data (needs extended permissions in case of fb). So, it means we also need to access data from facebook and twitter.
  4. Allow user to post to facebook and twitter from django app (activity as well as via forms).
  5. Inviting and Finding facebook friends (#3 can do it.)
  6. Provide same functionality as facebook app. (#3 can do it.)
  7. Post to user's owned facebook page. (I'm not sure if #3 can do it.)

What I think

If I had to deal with facebook only then I think Django-Facebook answers almost all of my questions. But since I also want to support twitter I'm not sure what I should do. All I can think of:

  1. Django-Facebook for facebook + django-social-auth or django-allauth for twitter. I'm not sure if this combination can work. Please let me know if you tried anything like that.
  2. django-social-auth or django-allauth only if any of these can provide aforementioned facebook functionality as well.

[Edit:] Actually I'm looking for answers to both of the following questions:

  1. If I choose to use django-social-auth only then can somebody point me to the samples/code snippets for interacting with facebook and twitter.
  2. If I want to use Django-Facbook (because it provides lot of functionality), can I choose it for facebook and django-social-auth (or django-allauth) for twitter only. I mean to say everything related to facebook using Django-facebook and everything related to twitter using social-auth or allauth. Will this combination work?

Thanks for your valuable suggestions in advance.


Source: (StackOverflow)

Django: TemplateSyntaxError: Could not parse the remainder: ':password_change' from 'admin:password_change'

In a very new Django 1.5.4 project I am getting this issue when I type localhost:8000/admin/.

TemplateSyntaxError: Could not parse the remainder: ':password_change' from 'admin:password_change'. The syntax of 'url' changed in Django 1.5, see the docs.

I am guessing it has to do with Django_facebook plugin (https://github.com/tschellenbach/Django-facebook).

part of my settings.py

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'grappelli',
    'filebrowser',
    # Uncomment the next line to enable the admin:
     'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    #'django.contrib.admindocs',
     'tinymce',
     'sorl.thumbnail',
     'south',
     'django_facebook',
     'djcelery',
     'devserver',
     'main',
)
AUTH_USER_MODEL = 'django_facebook.FacebookCustomUser'

AUTHENTICATION_BACKENDS = (
    'django_facebook.auth_backends.FacebookBackend', 
    'django.contrib.auth.backends.ModelBackend',
    # Uncomment the following to make Django tests pass:
    'django.contrib.auth.backends.ModelBackend',
)

Did I do anything wrong?

PS: This is my full traceback https://gist.github.com/anonymous/e8c1359d384df7a6b405

EDIT:

I am pasting the output of grep as per request:

$ ack-grep --type=python -r ':password_change' .
lib/python2.7/site-packages/django/contrib/admin/sites.py
264:url = reverse('admin:password_change_done', current_app=self.name)

lib/python2.7/site-packages/grappelli/dashboard/dashboards.py
147:reverse('%s:password_change' % site_name)],

$ ack-grep --type=html -r ':password_change' .
lib/python2.7/site-packages/django/contrib/admin/templates/admin/base.html
36:<a rel='nofollow' href="{% url 'admin:password_change' %}">{% trans 'Change password' %}</a> /

lib/python2.7/site-packages/grappelli/templates/admin/includes_grappelli/header.html
12:{% url admin:password_change as password_change_url %} 

Source: (StackOverflow)

Advertisements

OAuth2 specification states that 'perms' should now be called 'scope'. Please update. Django Facebook connect

If a django baseg webpage, and I use a django-facebook (Django Facebook by Thierry Schellenbach ) And today I noticed, that there is an Error on login in with facebook, the error message is:

OAuth2 specification states that 'perms' should now be called 'scope'. Please update. FB.provide('',{getLoginStatus:function...signed_request,code'});return a;}}});

And I don't know how to fix it.

(I don't want to download new version, becouse, I made some change with model registration and etc.)


Source: (StackOverflow)

Facebook Graph API Scheduled Posts created but not published

I'm using django-facebook's Open Facebook API to try to defer a post with an image to a facebook page. The (relevant part of the) code is:

graph_api = OpenFacebook(integration.long_lived_page_token)
message = "something"
picture = "http://example.com/image.jpg"
d = datetime.datetime.strptime('07-25-2014 06:40 pm UTC', '%m-%d-%Y %I:%M %p %Z')
timestamp = timestamp = int(time.mktime(d.timetuple()))
try:
    facebook_response = graph_api.set('/{0}/feed'.format(
    facebook_page_id), message=message,
    link=picture, picture=picture,
    scheduled_publish_time=timestamp, published=0)
except:
...

This seems to work fine (I get the post id on facebook_response) but when the time comes to post this scheduled post nothing happens. When I check at the facebook page I see an error saying 'Sorry, something went wrong publishing this scheduled post' and offers to delete it or post it then. So, I can't seem to figure out what am I doing wrong. I found a similar question but it does not offer a good answer.

Oh, I forgot to say when I remove timestamp and published=0 parameters (i.e. I post on that exact moment), the post gets created and published on the page's feed.


Source: (StackOverflow)

Getting information about the user from Facebook using django_facebook

first of all I would like to apologize to the community if this is a repost. I was searching stackoverflow for something that might help me on this matter but my search ended with no success. So here comes my problem.

Maybe it's my lack of skills, but I personally couldn't quite figure my way out through django_facebook documentation. I went through the whole thing and even though I think that all of the pieces are explained well, creating the big picture was pretty hard for me...

I managed to connect django_facebook with an app on facebook and even login, but what I couldn't do is pull information about the user who is logged in. My goal is to allow users to login/register with Facebook on my website, and pull their basic information from Facebook so that I can suggest them as User information for their profile on my website.

I would be really thankful, if you can explain the whole login/register and getting informations about the user process thoroughly.

p.s. someone suggested django_allauth to me. Should I switch to that? If yes, what would be the pros&cons of both djang_facebook and django_allauth? p.p.s. Also I wasn't able to find any decent tutorial for django_facebook nor django_allauth. If you have any, please gimme the links :)


Source: (StackOverflow)

FacebookUserConverter function get_and_store_likes() gives error?

I am developing a Facebook Canvas application using django-facebook. When I used FacebookUserConverter.get_and_store_like(), it gives me this error:

[Errno 10061] No connection could be made because the target machine actively refused it

My app name is fbData, and fbData.models contains following classes:

from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django_facebook.models import FacebookModel, get_user_model
from django_facebook.utils import get_profile_model
import logging
logger = logging.getLogger(__name__)


try:
    from django.contrib.auth.models import AbstractUser, UserManager
    class CustomFacebookUser(AbstractUser, FacebookModel):
    '''
    The django 1.5 approach to adding the facebook related fields
    '''
    objects = UserManager()
    # add any customizations you like

    middle_name = models.CharField(max_length=255, blank=True, null=True)
    verified = models.BooleanField(default=False) 
    locale = models.CharField(max_length=255, blank=True, null=True)
    languages = models.CharField(max_length=255, blank=True, null=True)
    link = models.CharField(max_length=255, blank=True, null=True)
    age_range = models.CharField(max_length=255, blank=True, null=True)
except ImportError, e:
    logger.info('Couldnt setup FacebookUser, got error %s', e)
    pass


# Create your models here.
class UserProfile(FacebookModel):
    '''
Inherit the properties from django facebook
'''
    user = models.OneToOneField(settings.AUTH_USER_MODEL)



@receiver(post_save)
def create_profile(sender, instance, created, **kwargs):
"""Create a matching profile whenever a user object is created."""
    if sender == get_user_model():
        user = instance
        profile_model = get_profile_model()
        if profile_model == UserProfile and created:
            profile, new = UserProfile.objects.get_or_create(user=instance)

my fbData.views is:

@facebook_required(canvas=True)
def home(request,graph):
    context = RequestContext(request)
    facebook_converter = FacebookUserConverter(graph)
    user_data = facebook_converter.facebook_registration_data(graph.get('me')['username'])


    user_data['access_token'] = graph.access_token
    try:

        fb_user = CustomFacebookUser.objects.get(facebook_id=user_data['facebook_id'])

        fb_user.access_token = user_data['access_token']
        fb_user.save()
        facebook_converter.get_and_store_likes(fb_user)       
    except CustomFacebookUser.DoesNotExist:
        custom_facebook_user = CustomFacebookUser(password = user_data['username'],username = user_data['username'],first_name = user_data['first_name'],last_name = user_data['last_name'],is_active = True, facebook_id = user_data['facebook_id'])
        custom_facebook_user.save()
        facebook_converter.get_and_store_likes(custom_facebook_user)

My settings.py contains:

CUSTOM_USER_MODEL = bool(int(os.environ.get('CUSTOM_USER_MODEL', '1')))

if DJANGO != '1.5.1':
    CUSTOM_USER_MODEL = False

if CUSTOM_USER_MODEL:
    AUTH_USER_MODEL = 'django_facebook.FacebookCustomUser'
else:
    AUTH_USER_MODEL = 'auth.User'
    AUTH_PROFILE_MODULE = 'fbData.UserProfile'

FACEBOOK_CELERY_STORE = True
FACEBOOK_CELERY_TOKEN_EXTEND = True

Source: (StackOverflow)

Django, Howto connect (and extent) facebook and django-userena or similar

It's been explicitly written in Django-facebook that they recommend it to be used with Userena:

We recommend using Django Userena. It seems easier to work with than Django Registration. Both are supported and good packages though. To use django userena simply point to the userena compatability layer.

AUTH_PROFILE_MODULE = 'django_facebook.FacebookProfile'

My question comes from AUTH_PROFILE_MODULE = 'django_facebook.FacebookProfile' part. I have developed my own UserProfile in Userena and also inherited some system Actors like Student and Tutors based upon their own needs. so my setting is something like this:

AUTH_PROFILE_MODULE = 'profiles.UserProfile' 

Within the django-facebook there is also an awesome example project that has written for mixing userena and django-facebook settings. But my problem still exists..

Should I replace my own code with facebook's one ??

This is my code :

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.db.models import permalink

from userena.models import UserenaBaseProfile

from courses.models import Course

class UserProfile(UserenaBaseProfile):
    user = models.OneToOneField(User, unique=True, verbose_name=_('user'), related_name='user_profile')
    department     = models.ForeignKey('Department' , null = True , blank = True , related_name=_('user'))
    name           = models.CharField(max_length = 100)
    birthday       = models.DateField()

    def __unicode__(self):
        return self.name

class Student(UserProfile):
    courses = models.ManyToManyField(Course , null = True, blank = True, related_name = _('student'))

Thanks beforehand ..


Source: (StackOverflow)

Using django-facebook to display text on facebook canvas

I am practicing using django-facebook to integrate my django app with facebook and turn it into a facebook app. The documentation for django-facebook is very bad but I have managed to get my sample app to load the facebook canvas page. But I am unable to display anything on the canvas page.

Any advice or suggestions would be appreciated. Sorry if this question is a little vague or unclear. Please let me know if I can clarify something.

Cheers


Source: (StackOverflow)

Logging out in Django Facebook?

Using Django-facebook for the first time.

  1. For some reason, if i log in with facebook, but later log out of my Facebook account. My application stays logged in with the default Django user, with an expired session token because "the user has logged out". If I then re-log in to facebook, the Django app stays "logged out" of Facebook.

  2. In the case above, I have tried attaching @facebook_required_lazy to the top of my view function, but to no effect. What is the intended behavior of this decorator in this use case? The view contains a call to get_persistent_graph.


Source: (StackOverflow)

django-facebook not inserting facebook data to the models

I have installed django-facebook in my Working application but it is creating a lots of problems. I have followed the installation of django-facebook here but I have not been able to implement it properly.

In facebook/example when I try to connect to facebook, it prompts the user for facebook credentials but it's not able to redirect to the next page as I am getting following error:

user or profile didn't have attribute facebook_id

I did manage.py syncdb but facebook attributes remain 'null' in DB after connecting to facebook in facebook/example.

I have added following to my code as in the documentation:

account/model.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django_facebook.models import FacebookProfileModel

class User_info(FacebookProfileModel):
    user_id = models.ForeignKey(User)
    dob = models.DateField(blank=True, null=True)
    contact = models.IntegerField(max_length=20, blank=True, null=True)
    avatar = models.ImageField(upload_to='user_images', default='user_images/root.jpeg', null=True, blank=True)

def create_facebook_profile(sender, instance, created, **kwargs):
    if created:
        User_info.objects.create(user_id=instance)

post_save.connect(create_facebook_profile, sender=User)

settings.py

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'account',
'django_facebook',
)

TEMPLATE_CONTEXT_PROCESSORS =(
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.core.context_processors.request',
'django_facebook.context_processors.facebook',
)

AUTHENTICATION_BACKENDS = (
'django_facebook.auth_backends.FacebookBackend',
'django.contrib.auth.backends.ModelBackend',)

FACEBOOK_APP_ID = 'xxxxxxxxxxxxx'
FACEBOOK_APP_SECRET = 'xxxxxxxxxxxxxx'

urls.py

urlpatterns = patterns('',
url(r'^accounts/login/$',  login, {'template_name': 'login.html'}),
url(r'^accounts/logout/$', logout, {'next_page': '/accounts/login/'}, name='auth_logout',),
url(r'^accounts/signup/$', account.views.register, name='signup'),
url(r'^facebook/', include('django_facebook.urls')),
)

Please help me on this. Thanks.


Source: (StackOverflow)

django-facebook internal code saying it can't find facebook_id

I've followed the tutorial and the examples for django-facebook from https://github.com/tschellenbach/Django-facebook/tree/master/facebook_example

I've got it up and running (as in i've run syncdb and migrations, and integrated the javascript and css code into my template).

When I click the link in my template, it successfully connects to Facebook and I can authorize. However, when it redirects, I get an error:

Request Method: POST
Request URL:    http://127.0.0.1:8000/facebook/connect/?facebook_login=1
Django Version: 1.5.1
Exception Type: AttributeError
Exception Value:    user or profile didnt have attribute facebook_id
Exception Location: /usr/local/lib/python2.7/dist-packages/django_facebook/utils.py in get_user_attribute, line 109
Python Executable:  /usr/bin/python
Python Version: 2.7.3

This is within django-facebook's code, and I'm not sure if I've done something wrong with my setup. I've created my own UserProfile model which extends the abstract FacebookProfileModel class (I've tried using FacebookModel as well):

from django_facebook.models import FacebookProfileModel
from django.db.models.signals import post_save

class UserProfile(FacebookProfileModel):
    user = models.OneToOneField('auth.User')

def create_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_profile, sender=User)

I can see the profile get created in the db, although it's all nulls (except for the user id used in the foreign key). Not sure what I'm doing wrong, any pointers?


Source: (StackOverflow)

Facebook Login in Selenium Tests

I'm working on a django project, using django_facebook for Facebook interaction, and Selenium for automated system testing.

In the tests, when it comes to logging to facebook from my application, I do this:

        self.browser.get(self.live_server_url)
        self.browser.find_element_by_xpath('//*[@id="facebook_login_js"]/input').click()

        self.browser.switch_to_window(self.browser.window_handles[1])
        self.login_to_facebook()

but it fails because Facebook's JS SDK hasn't finished its asynchronous initialization process. My tests used to work in the past, don't know if something changed now (like slower initialization).

I've thought of a solution like using fbAsyncInit, but that code is provided by django_facebook in a Javascript file and I don't want to touch it.

Have any idea how to wait until Facebook JS SDK is completely load so I can use the login functionality?


Source: (StackOverflow)

facebook_django : Given URL is not permitted by the application config

I'm getting this error for facebook login in local development. I'm using facebook_django package. And my dev server runs on 0.0.0.0:8000. In my site url I've tried setting my site url to 127.0.0.1:8888 and 0.0.0.0:8000 both and both ways it gives the same error

Given URL is not permitted by the application configuration.:
One or more of the given URLs is not allowed by the App's settings. 
It must match the Website URL or Canvas URL, or the domain must be a 
subdomain of one of the App's domains.

Also what should be the input for App Domain field in local development ?


Source: (StackOverflow)

Links in django_facebook app result in Bad Request: missing signed_request

I'm using the django_facebook library installed on pythonanywhere. When I click a link from one view to another, I get an error message:

400 Bad Request

Missing signed_request.

Could someone give me the brief on how links work in a facebook app?

Removing the @canvas_only decorator doesn't solve the problem, because I need access to the graph api.

Here's the code:

views.py:

from django.shortcuts import render
from django_facebook.decorators import canvas_only
#from django_facebook.decorators import facebook_required
#from django.utils.decorators import method_decorator

from models import Poem, Share
from django import forms
from django.views.generic import View

class PoemEntryForm(forms.Form):
    words = forms.CharField( widget=forms.widgets.Textarea(), initial='ENTER\nPOEM\nHERE\nONE\nWORD\nPER\nLINE' )

@canvas_only
def home(request):
    me = request.facebook.graph.get_object('me')
    my_username = me['username']
    request.session['username'] = my_username

    try:
        poems = Poem.objects.filter(user=my_username)
    except Poem.DoesNotExist:
        poems = []

    # convert poems into tuples of information relevant to the home page
    # sort them in reverse chronological order
    # ie: title and created
    poems = [(poem.title(), poem.created) for poem in sorted(poems, key=lambda poem: poem.created, reverse=True)]

    try:
        shared = Share.objects.filter(shared_to=my_username)
    except Share.DoesNotExist:
        shared = []

    shared = [(poem.title(), poem.user, poem.created) for poem in sorted(shared, key=lambda poem: poem.created, reverse=True)]

    return render(request, 'home.html', {
        'me': me,
        'my_poems': poems,
        'shared': shared,
    })

class Create(View):
    #@method_decorator(canvas_only)
    def get(self, request, *args, **kwargs):
        #self.me = request.facebook.graph.get_object('me')
        form = PoemEntryForm(request.GET)
        return render(request, 'create.html', {
            'form': form,
            'debug': request.session['username']
        })

    #@method_decorator(canvas_only)
    def post(self, request, *args, **kwargs):
        if request.session['username']:
            form = PoemEntryForm(request.POST)
            poem = Poem()
            poem.user = request.session['username']
            poem.text = request.POST['words']
            poem.save()
            return render(request, 'submitted.html', {})
        else:
            return render(request, 'error_submitting.html', {})

submitted.html:

<html>
    <body>
        <h3>You submitted a poem</h3>
        <a rel='nofollow' href="https://finebitstrings.pythonanywhere.com/">Home</a>
    </body>
</html>

Source: (StackOverflow)

Mysterious problem with Fandjango

I've just configured fandjango with my simply django application.

Here's the files:

VIEWS.PY

from django.http import HttpResponse
from django.shortcuts import render
from fandjango.decorators import facebook_authorization_required

@facebook_authorization_required()
def home(request):
    return render(request, 'home.html', {'facebook_user': request.facebook.user})

HOME.HTML

{% if facebook_user.first_name %}
You are:<br>

{{ facebook_user.first_name }} {{ facebook_user.last_name }}.
<br>ID: {{ facebook_user.facebook_id }}
<br>YOUR URL: {{ facebook_user.profile_url }}
<br><img src="http://graph.facebook.com/{{ facebook_user.facebook_id }}/picture?type=large">

{% else %}There's a problem here.{% endif %}

Now, when I go to http://apps.facebook.org/myapplicationname and I allow the access for application to take account's infos, I see the home.html.

BUT (here's the BIG problem) sometimes I see all my infos (if condition is true) but sometimes I don't see my info and I see "There's a problem here". In the database the data is ok.

I've checked this with others account and there's still this mysterious problem.


Source: (StackOverflow)