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

Posted

技术标签:

【中文标题】Django/React 415(不支持的媒体类型)【英文标题】:Django/React 415 (Unsupported Media Type) 【发布时间】:2022-01-17 01:42:05 【问题描述】:

当我尝试从 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;

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

提前致谢。

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

我已经尝试过了,但没有奏效,无论如何设法找到了解决方案,我添加了一个关于我如何设法做到这一点的答案。谢谢你的回复!【参考方案2】:

我找到了解决方案,我在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;

【讨论】:

以上是关于Django/React 415(不支持的媒体类型)的主要内容,如果未能解决你的问题,请参考以下文章

StatusCode: 415, ReasonPhrase: '不支持的媒体类型'

Angular/Keycloak:415 不支持的媒体类型

415 不支持的媒体类型:云 API

415 不支持的媒体类型 asp.net 核心

带有 REST Post 请求的 415(不支持的媒体类型)

BlueJeans ApiException:415“不支持的媒体类型”