将对象从AngularJS前端发布到Django后端时,serializer.is_valid()= false

时间:2015-11-12 14:53:35

标签: angularjs django

我有一个AngularJS前端和一个Django后端。

前端使用以下两个$ http调用来调用后端:

athleticsApp.controller('athletesListController', ['$scope', '$http', function($scope, $http) {
    $scope.athletes = [];

    $scope.getAthletes = function(){
        $http
            .get('http://serverip:8666/athletics/athletes/')
            .success(function(result) {
                $scope.athletes = result;
            })
            .error(function(data, status) {
                console.log(data);
                console.log(status);
            });
    }

    $scope.init = function() {
        $scope.getAthletes();
    }

    $scope.init();

}]);


athleticsApp.controller('athleteNewController', ['$scope', '$http', function($scope, $http) {
    $scope.athlete = {
        firstName : '',
        lastName : ''
    };

    $scope.postNewAthlete = function(){
        $http
            .post('http://serverip:8666/athletics/athletes/', $scope.athlete)
            .success(function(result) {
                // set url fraction identifier to list athletes
            })
    }
}]);

GET电话会议成功。 POST调用会生成以下错误:

  

400(BAD REQUEST)

当我运行Python调试器时,我可以看到serializer.is_valid()为假。

(Pdb) serializer = AthleteSerializer(data=request.data)

(Pdb) serializer
AthleteSerializer(data={u'lastName': u'Smith', u'firstName': u'John'}):
    first_name = CharField(max_length=30)
    last_name = CharField(max_length=30)

(Pdb) serializer.is_valid()
False

Django代码如下所示:

urls.py

from django.conf.urls import patterns, url

from views import Athletes

urlpatterns = [
    url(r'^athletes/', Athletes.as_view()),
]

views.py

from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Athlete
from django.shortcuts import get_object_or_404, render

from athletics.serializers import AthleteSerializer

class Athletes(APIView):
    def get(self, request, format=None):
        import pdb; pdb.set_trace()
        all_athletes = Athlete.objects.all()
        serializer = AthleteSerializer(all_athletes, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        import pdb; pdb.set_trace()
        serializer = AthleteSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            creation_data = serializer.save()
            return Response()


def index(request):
    return render(request, 'athletics/index.html')

serializers.py

from rest_framework import serializers
from .models import Athlete

class AthleteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Athlete
        fields = (
            'first_name',
            'last_name'
        )

settings.py

"""
Django settings for mysitedjango project.

Generated by 'django-admin startproject' using Django 1.8.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secretkey'

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

INTERNAL_IPS = (
    'myip'
)

CORS_ORIGIN_ALLOW_ALL = True

ALLOWED_HOSTS = []


# Application definition

REQUIRED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Third party apps
    'rest_framework',

)

PROJECT_APPS = (
    # This project
    'athletics',
    'testetics',
)

INSTALLED_APPS = REQUIRED_APPS + PROJECT_APPS

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',

    'django.contrib.messages.middleware.MessageMiddleware',
    'corsheaders.middleware.CorsMiddleware',

)

ROOT_URLCONF = 'mysitedjango.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 = 'mysitedjango.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Europe/Stockholm'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

0 个答案:

没有答案