代码之家  ›  专栏  ›  技术社区  ›  Tesh Aych

为什么Django rest框架不保存数据却返回200 ok代码

  •  0
  • Tesh Aych  · 技术社区  · 2 年前

    我已经成功地从react axios向部署(在Heroku中)Django rest API发送了一个post请求,但数据没有保存在我的数据库中。我使用MongoDB(Djongo)作为数据库。让我给你看看我用过的代码。

    设置.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()
    

    视图.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)
    

    我使用React Axios进行后期请求,下面是代码

    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);
          }
        );
      };
    

    这是chrome开发工具的请求。

    Header Response

    如何将帖子数据保存到我的数据库中?

    谢谢

    0 回复  |  直到 2 年前
        1
  •  0
  •   nzabakira floris    2 年前

    你上传文件而不保存的原因是你没有在设置中设置静态文件。在静态url下的设置中添加以下内容:

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

    和跑步 python manage.py collectstatics 在您的服务器上