Incoming file from post is "fakepath"

Brand new to react. My file is sending as a fakepath. I know this is for browser sercurity but I expected it to be different in my view. When I deserialize the request.body with json.loads I get this FileNotFound error.

fitz.FileNotFoundError: no such file: 'C:\fakepath\HW 3 CPSC 332.pdf'

When I deserialize the body with my own serializer it returns that the object is not valid. I am assuming this is due to the same issue with the fake file path.

request.body

b'{"title":"sdfg","content":"","file":"C:\\\\fakepath\\\\HW 3 CPSC 332.pdf"}'

views.py

@api_view(['POST'])
def createPost(request):
    serializer = SinglePostSerializer(data=request.body)
    
    if serializer.is_valid():
        serializer.save()
        return Response({'message': 'File uploaded successfully'}, status=status.HTTP_201_CREATED)
    else:
        return Response({'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class SinglePostSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

models.py

# Create your models here.
class Post(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=50)

    likes = models.IntegerField(default=0)
    comment_count = models.IntegerField(default=0)

    pdf_file = models.FileField(upload_to='media/pdfs/')
    images = models.ManyToManyField(SheetMusicImage)
    
    comments = models.ManyToManyField('Comment', blank=True)
    date_created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.pdf_file.name

CreatePostPage.js

import React, { useState, useEffect} from 'react'

const CreatePostPage = () => {


    const [formData, setFormData] = useState({
        // Initialize form fields here
        // For example:
        title: '',
        content: '',
    });

    const handleChange = (e) => {
        setFormData({
          ...formData,
          [e.target.name]: e.target.value,
        });
      };

    const handleSubmit = async (e) => {
        e.preventDefault();

        try {
            console.log(JSON.stringify(formData))
            const response = await fetch('posts/createPost', {
            method: 'POST',
            headers: {
            'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData),
        });

        if (response.ok) {
            // Handle successful submission, e.g., redirect or show a success message
            console.log('Post created successfully');
        } else {
            // Handle error cases
            console.error('Failed to create post');
        }
        } catch (error) {
        console.error('Error:', error);
        }
    };

    return(
        <div>
            <form onSubmit={handleSubmit}>
                <input type="text" id="title" name="title" placeholder="Title" onChange={handleChange}/>
                <input type="file" id="file" name="file"  accept="application/pdf" onChange={handleChange}/>
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}

export default CreatePostPage
Back to Top