How Can I Use Django Social Auth To Connect With Twitter?
I'm trying to use the Django Social Auth package to connect with Twitter, but I'm having difficulty understanding how exactly to do this as I can't find any examples. I am assuming
Solution 1:
I will give you a sample and this is a customize twitter login,
- the name of the app is social
- pip install Twython
- create LOGIN_REDIRECT_URL, TWITTER_SECRET and TWITTER_KEY
settings.py
# Twitter settingsTWITTER_KEY = 'xxxxxx'TWITTER_SECRET = 'xxxxxxxx'
models.py
classTwitterProfile(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
<ahref="{% url social:twitter_login %}">Twitter</a>
Post a Comment for "How Can I Use Django Social Auth To Connect With Twitter?"