Hello Guys,
I want to automate my tweets from my Django application. I want to make a post(on Twitter) each time I write and publish a blog. I have used REST API with OAuth2 in a simple python program and run it via CLI. But This is the 1st time I will be integrating into an application. How do I get started so I can post my blog (image, heading) to Twitter using Django?

The same way you would perform any functionality in Django.

The browser issues a request to a URL, Django dispatches that request to a view. The view receives a request and returns a response.
Whatever happens between receiving the request and returing a response is entirely up to you.

So I write my logic in Views.py and when a blog post is made it runs the API function(send the current post head and image).

Could you please share resources if you have any? most of the posts & videos just show how to build a rest API within Django.

Do we have any package that can handle oauth2 authentication ? I see a couple but am know which to use any suggestions on that?


It seems like you have your own resource:

You’re going to be using the same code - only you’re going to be using it within a view.

from requests_oauthlib import OAuth1Session
import json

payload = {
    "text":"New World!"

# Be sure to add replace the text of the with the text you wish to Tweet. You can also add parameters to post polls, quote Tweets, Tweet with reply settings, and Tweet to Super Followers in addition to other features.
payload = {"text": "Hello world! Post from API"}

# Get request token
#request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
#oauth = OAuth1Session(client_key= consumer_key, client_secret= consumer_secret)

oauth = OAuth1Session(

# Making the request
response = oauth.post(

if response.status_code != 201:
    raise Exception(
        "Request returned an error: {} {}".format(response.status_code, response.text)

print("Response code: {}".format(response.status_code))

# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))

This is my standalone code for posting using CLI

In view.py

    model = Post
    form_class = PostForms
    template_name = 'add_post.html'
    success_url = reverse_lazy('blogview')
    #fields = '__all__'

in forms.py

class PostForms(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('poster','title', 'author', 'category','snippet', 'body')

        widgets = {
            'title' : forms.TextInput(attrs={'class':'form-control'}),
            'author' : forms.TextInput(attrs={'class':'form-control', 'value': '','id':'current_user','type':'hidden'}),
            #'author' : forms.Select(attrs={'class':'form-control'}),
            'category': forms.Select(attrs={'class':'form-control'}),
            'snippet' : forms.TextInput(attrs={'class':'form-control'}),
            'body': forms.Textarea(attrs={'class': 'form-control'}),


How do I do it?

You didn’t show your complete view, but from what I can see, it appears most likely that you’re using one of the Django-provided CBVs.

When you have any of the Django CBVs, what method do you override to add custom functionality when a valid form is submitted?

Note - if you’re not all that familiar with how CBVs work, you may want to review the documentation starting at Class-based views | Django documentation | Django. You may also find the Classy Class-Based Views site and the CBV diagrams page to be helpful.

from gettext import Catalog
from unicodedata import category
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, TemplateView, CreateView, UpdateView, DeleteView
from cavertech.models import Post, Contact, Category
from cavertech.forms import PostForms,EditForms

# Create your views here.
#def home(request):
#    return render(request, 'home1.html',{})

class Home_view(CreateView):    # Hoeme page view 
    model = Contact
    template_name = 'home.html'
    fields =['email']
    success_url = reverse_lazy('home')

class Blog_view(ListView):       # Blog list view  
    model = Post
    template_name = 'blog_list.html'
    cats = Category.objects.all()
    ordering = ['-date']

class Article_view(DetailView):  # Blog detail view 
    model = Post
    template_name = 'article_view.html'

class Create_post_view(CreateView): # Create Blog
    model = Post
    form_class = PostForms
    template_name = 'add_post.html'
    success_url = reverse_lazy('blogview')
    #fields = '__all__'

class Update_post_view(UpdateView): # update Blog
    model = Post
    form_class = EditForms
    template_name = 'update_post.html'
    success_url = reverse_lazy('blogview')
    #fields = ['title', 'author', 'body']

class Delete_post_view(DeleteView): 
    model = Post
    template_name = 'delete_post.html'
    success_url = reverse_lazy('blogview')

#class Category_view(ListView):
#    model = Post
#    template_name = 'categories_view.html'

def Category_view(request, cats): # fuction view 
    category_post = Post.objects.filter(category=cats)
    return render(request, 'categories_view.html', {'category_post': category_post})

this is my complete view.py
I am not overriding any method.

Ok, let me rephrase my question.

If you wanted to override a method to add functionality to a view that will execute when a valid form is submitted, what method would you override?

I see the create post view would be the one. once the post is created I would like to do an API call to send the title and image of the blog to twitter

class Create_post_view(CreateView): # Create Blog
    model = Post
    form_class = PostForms
    template_name = 'add_post.html'
    success_url = reverse_lazy('blogview')
    #fields = '__all__'

Ok, that’s the view that you want to change.

When you want to change the behavior of a CBV, you generally override one (or more) of the methods that are defined for that view.

Which method do you think you want to override to add your functionality to do this? (You’ll want to do this after the form has been submitted and validated.)

Yes That is what I want to do