Question: csrf cookie not set django rest

Question

csrf cookie not set django rest

Answers 0
Added at 2016-12-19 22:12
Tags
Question

When working on REST browsable API the responses work fine but when I started working on postman to integrate with front end on the other side the respond become:

 {
  "detail": "CSRF Failed: CSRF cookie not set."
}

I tried everything to solve this error but nothing change, and checked every question here on CSRF token but still didn't work

These are my codes: views.py:

from django.shortcuts import render

from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework import status
from User.serializers import UserDataSerializer, ImageSerializer
from rest_framework.views import APIView
from rest_framework import generics
from User.models import UserData,Image
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from rest_framework.renderers import TemplateHTMLRenderer
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
class Signup(APIView):
    def post(self, request, format = None):
       serializer = UserDataSerializer(data = request.data)
       if(serializer.is_valid()):
           user = User.objects.create_user(
               username = serializer.data['username'],
               first_name = serializer.data['first_name'],
               last_name = serializer.data['last_name'],
               email = serializer.data['email'],
               password = serializer.data['password'],
               )
        #add the name because it is not with create_user method
        # user.name = serializer.data['name']
        # user.save()
        login(request, user)
        print ("logged")
        text = {'valid' : True , 'errors' :"ur password"+serializer.data['password']}
        return JsonResponse(serializer.data)
    else:
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class Login(APIView):
   def post(self, request):
       username = request.data.get('username')
       password = request.data.get('password')
       user = authenticate(username=username, password=password)

       if user is not None:
           login(request, user)
           serializer = UserDataSerializer(user)
           return JsonResponse(serializer.data, status=status.HTTP_302_FOUND)
       else:
           text = {'valid' : False , 'errors' : "Invalid Username or Password"}
           return Response(text, status=status.HTTP_401_UNAUTHORIZED)

class Logout(APIView):
    def get(self, request):
        logout(request)
        return Response({"valid": True}, status=status.HTTP_200_OK)

class ImageUpload(generics.CreateAPIView):

    queryset = Image.objects.all()
    serializer_class = ImageSerializer

settings.py:

"""
Django settings for app project.

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

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'baz^+ip1ik4_fla*zg$9q#37e(5jg6tmnwzj4btqw@nw=si)+('

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CSRF_COOKIE_SECURE = False
ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'User.apps.UserConfig',
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    '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',
]

ROOT_URLCONF = 'app.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.core.context_processors.csrf',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'app.wsgi.application'

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
}
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ImageSearchDB',
        'USER': 'root',
        'PASSWORD': '1234',
        'HOST': 'localhost',
        'PORT': '',
        'OPTIONS': {
        'init_command': 'SET default_storage_engine=INNODB',
        }
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.10/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',
    },
]

# AUTHENTICATION_BACKENDS = (
#     'app.User.backends.EmailOrUsernameModelBackend',
#     'django.contrib.auth.backends.ModelBackend'
# )
# Internationalization
# https://docs.djangoproject.com/en/1.10/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/1.10/howto/static-files/

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = 'media/'

urls.py

from django.conf.urls import url
from User import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [

    url(r'^login/?$', views.Login().as_view()),
    url(r'^signup/?$', views.Signup().as_view()),
    url(r'^logout/?$', views.Logout().as_view()),
    url(r'^trail/?$', views.ImageUpload().as_view())

]
urlpatterns = format_suffix_patterns(urlpatterns)   #no need
Answers to

csrf cookie not set django rest

Source Show
◀ Wstecz