[Solved]-How can I use Django Social Auth to connect with Twitter?

5๐Ÿ‘

โœ…

I will give you a sample and this is a customize twitter login,

  1. the name of the app is social
  2. pip install Twython
  3. create LOGIN_REDIRECT_URL, TWITTER_SECRET and TWITTER_KEY

settings.py

# Twitter settings
TWITTER_KEY = 'xxxxxx'
TWITTER_SECRET = 'xxxxxxxx'

models.py

class TwitterProfile(models.Model):
    user = models.ForeignKey(User)
    oauth_token = models.CharField(
        max_length=200
        )
    oauth_secret = models.CharField(
        max_length=200
        )
    screen_name = models.CharField(
        max_length=50, 
        blank=True, null=True
        )

    def __unicode__(self):
        return "{0}".format(self.user)

urls.py

urlpatterns = patterns('social.views',      
    url(
        r'^twitter/login/$', 
        "twitter_login", 
        name="twitter_login"
    ),

    url(r'^twitter/callback/$', 
        "twitter_callback", 
        name="twitter_callback"
    ),   
)

views.py

def twitter_login(request):
    twitter = Twython(
        twitter_token = settings.TWITTER_KEY,
        twitter_secret = settings.TWITTER_SECRET,
        callback_url = request.build_absolute_uri(reverse('social:twitter_callback'))
    )
    auth_props = twitter.get_authentication_tokens()
    request.session['request_token'] = auth_props
    return HttpResponseRedirect(auth_props['auth_url'])


def twitter_callback(request, redirect_url=settings.LOGIN_REDIRECT_URL):
    twitter = Twython(
        twitter_token = settings.TWITTER_KEY,
        twitter_secret = settings.TWITTER_SECRET,
        oauth_token = request.session['request_token']['oauth_token'],
        oauth_token_secret = request.session['request_token']['oauth_token_secret'],
    )

    authorized_tokens = twitter.get_authorized_tokens()

    try:
        profile = TwitterProfile.objects.get(screen_name = authorized_tokens['screen_name'])
        user = User.objects.get(pk=profile.user_id)
        user.backend = 'django.contrib.auth.backends.ModelBackend'

        if user.is_active:
            auth_login(request, user)
            return HttpResponseRedirect(reverse('app_name:url_name'))
        else:
            //failed back to login
            return HttpResponseRedirect(reverse('app_name:login'))
    except TwitterProfile.DoesNotExist:
        screen_name = authorized_tokens['screen_name']
        oauth_token = authorized_tokens['oauth_token']
        oauth_token_secret = authorized_tokens['oauth_token_secret']

        //create new twitter profile
        //create new user here
        //authenticate the new register user then login
        .........

template

<a href="{% url social:twitter_login %}">Twitter</a>
๐Ÿ‘คcatherine

Leave a comment