0

I am trying to record and upload an audio to django server using rest framework. My audio is getting recorded as well as the server is working fine. But they aren't working together. I am getting a status 400 Bad request. I have tried using both axios and fetch() in react but nothing is helpful. This is when I use axios : enter image description here

This is when I use fetch() enter image description here

This is react code:

  onStop(recordedBlob) {
    var headers ={
      'Content-Type' : 'multipart/form-data'
    }
    const data = new FormData(); 
        data.append('audio', recordedBlob);
        console.warn(recordedBlob);
  /*      fetch("http://127.0.0.1:8000/temp/",{
          method:'POST',
          body:data,
          headers:headers
        }).then( res => console.log(res)).catch(error => {
          console.log(error);
        })*/

        axios.post("http://127.0.0.1:8000/temp/", data, { 'headers':headers
        })
        .then(res => {
            console.warn(res);
        }).catch((error)=>{
          console.log(error);
        });
        
  }

My django views file :


class AudioCreateView(ModelViewSet):
    queryset=Audio.objects.all()
    serializer_class = AudioSerializer
    def create(self, request, *args, **kwargs):
        if 'file' not in request.data:
            raise ParseError('No File Uploaded')
        file_obj = request.data['audio']
        # do some stuff with uploaded file
        Audio.objects.create(audio=file_obj)
        return Response(data="File Received")

My serializers file :



class AudioSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model= Audio
        fields = ['audio']

My django settings :



INSTALLED_APPS = [
    'corsheaders',
    'lang_translator.apps.LangTranslatorConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL= "/media/"
REST_FRAMEWORK={
    'DEFAULT_PERMISSION_CLASSES': [
   'rest_framework.permissions.AllowAny',
]
}
CORS_ORIGIN_ALLOW_ALL=True

My django Model :

from django.db import models

class Audio(models.Model):
    audio = models.FileField(upload_to='images/')
    

I finally found out the problem. The problem is with the audio blob recorded. When I tried to upload audio and image files using new html file and postman. The server worked perfectly fine in both of those situations. I just need to find another way to record and send audio with react. Does anyone have any idea for this ?

2 Answers 2

1

ModelViewset don t have 'post' action try to follow the documentation on Viewsets https://www.django-rest-framework.org/api-guide/viewsets/

'The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().'

Sign up to request clarification or add additional context in comments.

3 Comments

Tried it no change in result.
Can you show us de model? I think you don t need to override the .create() method. Try to replace HyperlinkedModelSerializer with ModelSerializer. Another question is how you send the data? json?
Earlier I was using ModelSerializer but I was having the same problem. So I changed to HyperlinkedModelSerializer .
1

I finally found out the problem. The problem is with the audio blob recorded. Rather than sending the recordedBlob You should send recordedBlob.blob.Because react-mic returns a blob containing the audio blob as well as other data related to it. So recordedBlob.blob is the actual data which is to be sent.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.