'Why Django rest framework is not saving data but returns 200 ok code

I have successfully send a post request to deployed(in Heroku) Django rest API from react axios but the data is not saved in my database. I use MongoDB(Djongo) as a databse. Let me show you the code I have used.

settings.py

"""
Django settings for CyberMinds project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path
import django_heroku

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "rest_framework.authtoken",
    "corsheaders",

    "accounts",
    "threat_catalog_models",
    'django_rest_passwordreset',
    "threat_catalog",
    # "risk_model",
    "risk_model",
    "business_process",
]

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

ROOT_URLCONF = "config.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "config.wsgi.application"


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "djongo",
        "NAME": "cyberminds",
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = "/static/"

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
    ],
}

AUTH_USER_MODEL = "accounts.Account"

CORS_ORIGIN_ALLOW_ALL = True

ADMIN_SITE_HEADER = "CYBERMINDS Administration"

CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
]

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
    # 'DEFAULT_PERMISSION_CLASSES': [
    #     'rest_framework.permissions.IsAuthenticated',
    # ],
    # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    # 'PAGE_SIZE': 10,

}

APPEND_SLASH = True
django_heroku.settings(locals())

serializers.py

class ExcelUploaderWithClient(serializers.Serializer):
    file = serializers.FileField()
    client = serializers.IntegerField()
    business_process = serializers.IntegerField()

views.py

class UploadBusinessImpactExcelBySuperUSer(APIView, ExcelHandlingView):

    permission_classes = (
        IsAuthenticated,
        permissions.IsCybermindAdmin,
    )

    def post(self, request):
        self.can_model_handle_ExcelHandlingView(models.BusinessImpact)

        serializer = serializers.ExcelUploaderWithClient(
            data=request.data)
        if serializer.is_valid():
            data = serializer.validated_data
            file = data.get("file")
            client = data.get("client")
            business_process_id = data.get("business_process")
            

            try:
                business_process = get_business_process_by_client(
                    client, business_process_id
                )
            except (
                models.BusinessProcess.DoesNotExist,
                accountModels.Client.DoesNotExist,
            ) as e:
                return Response(
                    "business process or client does not exist",
                    status=status.HTTP_404_NOT_FOUND,
                )

            if (
                file.content_type
                == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            ):
                # self.delete_every_recore_on_that_model(models.BusinessImpact)
                self.delete_every_record_that_match_criteria(
                    models.BusinessImpact,
                    {"client": client, "business_process": business_process},
                )
                excel_file = pd.read_excel(file)
                data = pd.DataFrame(
                    excel_file,
                    columns=self.get_excel_fields(
                        models.BusinessImpact.excel_titles),
                )

                for _, row in data.iterrows():
                    self.create_model_object(
                        models.BusinessImpact,
                        row,
                        {"client": client, "business_process": business_process.id},
                    )

                return Response("Successfully Loaded data from excel.")

            else:
                return Response(
                    {"file": ["File type must be excel with .xlxs extension."]},
                    status=status.HTTP_400_BAD_REQUEST,
                )

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I used React Axios for post request and here is the code

const handleUploadFile = (e) => {
    let myfile = file;

    let formData = new FormData();
    formData.append("file", myfile);
    formData.append("client", company_name);
    formData.append("business_process", business);
    http({
      url: "https://cyberminds-backend.herokuapp.com/api/business_process/upload-business-impact-excel-by-superuser",
      method: "POST",
      mode: "cors",
      data: formData,
      headers: { "Content-Type": "multipart/form-data" },
    }).then(
      (response) => {
        alert("File uploaded Sesscessfullyyyyy");
      },
      (err) => {
        console.log(err);
      }
    );
  };

Here is the request from chrome dev tools.

Header Response

How can I actually save the post data into my database?

Thanks



Solution 1:[1]

the reason u are uploading files and not saving, is because u did not setup staticfiles in your settings. Add these in your settings underneath static url:

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'staticfiles/static/')
]

and the run python manage.py collectstatics on your server

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nzabakira floris