0

I have an AngularJS front-end and a Django backend.

The front-end calls the backend using the following two $http calls:

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

The GET call is a success. The POST call generates the following error:

POST http://serverip:8666/athletics/athletes/ 403 (FORBIDDEN)

Why does it generate an error?

The Django code looks like this:

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):
        all_athletes = Athlete.objects.all()
        serializer = AthleteSerializer(all_athletes, many=True)
        return Response(serializer.data)

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

serializers.py

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

settings.py

# 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 = 'characters'

# 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/'

EDIT: I added settings.py

user1283776
  • 19,640
  • 49
  • 136
  • 276

3 Answers3

0

Add :

@api_view(['POST', 'GET'])

just before your Athletes class.

Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79
0

You need to make sure CSRF is sent if you're using the session based authentication.

Django documentation has a full explanation on how to do it: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

Note that there must be angular plugins that handles that already though I don't have one to recommend as I'm not using angular for my APIs.

Linovia
  • 19,812
  • 4
  • 47
  • 48
0

Could you post the full error you are getting? Django normally tells you why your request was rejected.

If the issue is the CSRF, have a look at:

XSRF headers not being set in AngularJS

which solved the issue I had accessing the django backend.

Community
  • 1
  • 1
Niels van Eldik
  • 211
  • 2
  • 7
  • I don't understand how to add the CSFR token from that site. How do I set it with Django? How do I add it to the post request in AngularJS? – user1283776 Nov 12 '15 at 10:52
  • In your setting you have 'django.middleware.csrf.CsrfViewMiddleware', which enables the csrf using cookies. On the angularjs side just add the code from the link – Niels van Eldik Nov 12 '15 at 11:23
  • It would be very useful if you could check and post the response you get from your backend as django normally tells you why it is not accepting your request – Niels van Eldik Nov 12 '15 at 11:24
  • I have tinkered a bit but don't know what relevant I have changed. The error message in the browser has changed to: 400 (BAD REQUEST) and the backend now receives the request, but doesn't store it because for some reason serializer.is_valid() is FALSE. So maybe I should close the question as, for an unknown reason that may have to do with my code or the server (which is maintained by someone else), I still have a problem, but my problem has changed. – user1283776 Nov 12 '15 at 12:16
  • 1
    If you now get a BAD request, your access issues seem to be fixed.As the server is now processing your request. Good luck fixing the next issue – Niels van Eldik Nov 12 '15 at 13:38