REACT-DJANGO Post form to an API 400 error strict-origin-when-cross-origin
I'm having a problem where when I try to post a FORM to my API it gives me this error.
Request URL: http://localhost:8000/api/
Request Method: POST
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin
I did follow a tutorial to create the API and I think that may be the problem I don't even know where to start looking!
I don't know where I'm messing up at and it's really frustrating!
This is my REACT Post form page
import axios from "axios";
import { useState, useEffect } from "react";
import { useHistory } from "react-router";
import "./createpost.css";
const CreatePost = () => {
const [username, setUsername] = useState("");
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [image, setImage] = useState(null);
const [category, setCategory] = useState("");
const history = useHistory();
const AddPost = async () => {
let formField = new FormData();
formField.append("title", title);
formField.append("description", description);
formField.append("category", category);
if (image !== null) {
formField.append("image", image);
}
await axios({
method: "post",
url: "http://localhost:8000/api/",
data: formField,
}).then((response) => {
console.log(response.data);
history.push("/");
});
};
useEffect(() => {
if (localStorage.getItem("token") === null) {
} else {
fetch("http://127.0.0.1:8000/api/v1/users/auth/user/", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${localStorage.getItem("token")}`,
},
})
.then((res) => res.json())
.then((data) => {
setUsername(data.username);
});
}
}, []);
return (
<div className="background">
<div className="post-container">
<form className="form">
<input id="user" type="text" style={{ display: "none" }} />
<input
className="createtitle"
type="text"
placeholder="Title"
value={title}
name="title"
required
onChange={(e) => setTitle(e.target.value)}
/>
<input
className="createtitle"
type="text"
placeholder="Category"
value={category}
name="category"
required
onChange={(e) => setCategory(e.target.value)}
/>
<textarea
className="createdesc"
type="text"
placeholder="Description..."
name="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div className="form-bottom">
<input
className="upload"
type="file"
name="image"
src={image}
onChange={(e) => setImage(e.target.files[0])}
/>
<button onClick={AddPost} className="createsubmit">
POST
</button>
</div>
</form>
</div>
</div>
);
};
export default CreatePost;
THIS IS MY BACKEND API MODELS AND VIEWS PAGE!
MODEL:
from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
category_choice = (
('Cook', 'Cook'),
('Coding', 'Coding'),
('Workout', 'Workout'),
('Martial Arts', 'Martial Arts'),
('Voice Lessons', 'Voice Lessons'),
)
class Post(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=100, choices=category_choice, default='')
def __str__(self):
return self.title
VIEWS
from django.http import JsonResponse
from django.shortcuts import render
# third party imports
from rest_framework import mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics
from .serializers import PostSerializer
from .models import Post
class TestView(APIView):
permission_classes = (IsAuthenticated, )
def get(self, request, *args, **kwargs):
qs = Post.objects.all()
post = qs.first()
# serializer = PostSerializer(qs, many=True)
serializer = PostSerializer(post)
return Response(serializer.data)
def post(self, request, *args, **kwargs):
serializer = PostSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors)
class PostView(
mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
serializer_class = PostSerializer
queryset = Post.objects.all()
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class PostCreateView(mixins.ListModelMixin, generics.CreateAPIView):
serializer_class = PostSerializer
queryset = Post.objects.all()
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class PostListCreateView(generics.ListCreateAPIView):
serializer_class = PostSerializer
queryset = Post.objects.all()