utamaro’s blog

誰かの役に立つ情報を発信するブログ

Djangoでtwitter認証をしたあとにツイートする方法

前提として、social-auth-app-djangoを使ってtwitterでの認証が実装できている状態とします。

class TwitterPost(TemplateView):
    post_api = "https://api.twitter.com/1.1/statuses/update.json"

    def post(self, request, *args, **kwargs):
        social_user = UserSocialAuth.objects.filter(user=request.user).first()
        # ここでバリデーションを入れるべきでしょう。
        twitter_oauth = OAuth1Session(
            SOCIAL_AUTH_TWITTER_KEY,
            SOCIAL_AUTH_TWITTER_SECRET,
            social_user.tokens.get('oauth_token'),
            social_user.tokens.get('oauth_token_secret'),
        )
        params = {"status": 'twitter post api test.', "lang": "ja"}
        result = twitter_oauth.post(self.post_api, params)
        return redirect('home')

バリデーションのコードは省いています。

これが実行されると、ログインしているユーザがtwitter post api test.とツイートします。

次にhtmlのテンプレートを(特別なことはやっていませんが)htmlのどこかに入れます。

{% if user.is_authenticated %}
<form action="{% url 'twitter_post' %}" method="post">
    {% csrf_token %}
    <button type="submit">
        <span>twitterで共有</span>
    </button>
</form>
{% endif %}

settings.pyに以下のpathを追加します。

    path('twitter_post', TwitterPost.as_view(), name='twitter_post'),

これでOK