Django/React 415(不支持的媒体类型)

Django/React 415 (Unsupported Media Type)

当我尝试从 React 提交表单时出现 POST http://localhost:8000/api/reports/ 415 (Unsupported Media Type),但我不明白问题出在哪里。

这是代码。

models.py

class Report(models.Model):

    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    description = models.TextField()
    address = models.CharField(max_length=500)
    reporter_first_name = models.CharField(max_length=250)
    reporter_last_name = models.CharField(max_length=250)
    reporter_email = models.CharField(max_length=250)
    reporter_phone = models.CharField(max_length=250)
    report_image_1 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
    report_image_2 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
    report_image_3 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
    date = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ('-date',)

    def __str__(self):
        return self.description

我也试过给图片设置默认值,但还是报错。

serializers.py

class ReportSerializer(serializers.ModelSerializer):
    categoryName = CategorySerializer(many=False, read_only=True, source='category')

    class Meta:
        model = Report
        fields = '__all__'

views.py

class ManageReports(viewsets.ModelViewSet):
    serializer_class = ReportSerializer
    parser_classes = [MultiPartParser, FormParser]

    def get_object(self, queryset=None, **kwargs):
        id = self.kwargs.get('pk')
        return get_object_or_404(Report, id=id)

    def get_queryset(self):        
        return Report.objects.all()

这是负责提交的代码。

report.js

    const initialPostData = Object.freeze({
        category: '',
        address: '',
        description: '',
        reporter_first_name: '',
        reporter_last_name: '',
        reporter_email: '',
        reporter_phone: '',
    });

    const [postData, updatePostData] = useState(initialPostData);
    const [postImage1, setPostImage1] = useState({image: null});
    const [postImage2, setPostImage2] = useState({image: null});
    const [postImage3, setPostImage3] = useState({image: null});

    const handleChange = (e) => {
        if([e.target.name] == 'reporter_image_1') {
            setPostImage1({
                image: e.target.files[0],
            });
        } else if([e.target.name] == 'reporter_image_2') {
            setPostImage2({
                image: e.target.files[0],
            });
        } else if([e.target.name] == 'reporter_image_3') {
            setPostImage3({
                image: e.target.files[0],
            });
        } else if([e.target.name] == 'category') {
            updatePostData({
                ...postData,
                [e.target.name]: e.target.value,
            });
        } else {
            updatePostData({
                ...postData,
                [e.target.name]: e.target.value.trim(),
            });
        }
    };


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

        let formData = new FormData();
        formData.append('category', postData.category);
        formData.append('address', postData.address);
        formData.append('description', postData.description);
        formData.append('reporter_first_name', postData.reporter_first_name);
        formData.append('reporter_last_name', postData.reporter_last_name);
        formData.append('reporter_email', postData.reporter_email);       
        formData.append('reporter_image_1', postImage1.image);       
        formData.append('reporter_image_2', postImage2.image);        
        formData.append('reporter_image_3', postImage3.image);       

        const submitForm = await submitReport(formData);

这是 submitReport API

API.js

const axiosInstance = axios.create({
    baseURL: 'http://localhost:8000/api/',
    timeout: 5000,
    headers: {
        Authorization: accessToken
            ? 'JWT ' + accessToken
            : null,
        'Content-Type': 'application/json',
        accept: 'application/json',
    }, 
});

// Submit Report Form
const submitReport = async(formData) => {
    const { data } = await axiosInstance.post('reports/', {...formData });
    return data;
}

这些应该是了解正在发生的事情所需的所有文件。

提前致谢。

您在视图集上的 parser_classes 属性是错误的。如果您想在请求正文中接受 JSON 格式,您需要在 parser_classes 属性中包含 JSONParser

请参阅 DRF 文档中 here 的相关部分。

我找到了解决方案,我在 submitReport 函数中使用了扩展运算符,但我不需要使用它,所以:

API.js

// Submit Report Form
const submitReport = async(formData) => {
    const { data } = await axiosInstance.post('reports/', {...formData });
    return data;
}

变成

// Submit Report Form
const submitReport = async(formData) => {
    const { data } = await axiosInstance.post('reports/', formData);
    return data;
}