Aditya Goyal
Aditya Goyal

Reputation: 11

Axios POST request not working with the Django-RestFramework

When I try to post with the Postman App it works perfectly fine but when I post with the VUE-Axios it shows error 400 Bad Request so please help me out with this. Also the GET request works perfectly fine.

Only issue is with the POST request. Also with the default interface of API view it works fine. Please suggest change in Vue code. PS I am a beginner in Vue and API interaction

This is the Vue code:

var app = new Vue(
    {
    el:"#app",
    delimiters: ['[[',']]'],
    data:
    {
        message: "Integrated With VUE",
    },
    mounted: function(){
        axios.get('api/movie')
        .then(response => console.log(response));
    },
    methods : {
        postData() {
            axios.post('api/movie/', {
                params:
                {   
                id : 10,
                title: "Random",
                rating: 5,
                type: "4",
                description: "This is another test data",
                torrent: "",
                date_added: "Auto_Add"}
            },
            {headers :   {"X-CSRFToken": csrftoken},
            
        }).then( (response)=> {console.log(response); });
        }
    }
});

In Django View I have This

class MovieAPIView(APIView):
    def get(self, request, format=None):
        movies = Movie.objects.all()
        serializer = MovieSerializer(movies, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = MovieSerializer(data = request.data)
        if serializer.is_valid():
            print("Valid Serializer")
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

In Django Serializer I have This

class MovieSerializer(serializers.ModelSerializer):
        class Meta:
            model = Movie
            fields = ['id', 'title', 'rating', 'type', 'description', 'torrent', 'date_added']

Upvotes: 1

Views: 106

Answers (0)

Related Questions