Deploy django restframeworkapi on server
i want to set post req to my api application. in postman when I send the post in the object program, it returns the following text as a response and the data is not saved in the database.
i got in browser:
Employee List
POST /employees/
HTTP 403 Forbidden
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "CSRF Failed: CSRF token missing or incorrect."
}
but i got different error in postman:
Server Error (500)
is set:
DEBUG = False
ALLOWED_HOSTS = ['*']
in settings.py But the problem is still not solved and the error remains.
What should I do to fix this error?
views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . models import employees
from . serializers import employeeSerializer
class employeeList(APIView):
def get(self, request):
employees1 = employees.objects.all()
serializer = employeeSerializer(employees1, many=True)
return Response(serializer.data)
def post(self):
pass
models.py
from django.db import models
# Create your models here.
class employees(models.Model):
firstName=models.CharField(max_length=10)
lastName=models.CharField(max_length=10)
emp_id=models.IntegerField()
def __str__(self) -> str:
return self.firstName
urls.py
"""
Definition of urls for UpmenuDjango.
"""
from datetime import datetime
from django.urls import path
from django.contrib import admin
from django.contrib.auth.views import LoginView, LogoutView
# from app import forms, views
from rest_framework.urlpatterns import format_suffix_patterns
from webapp import views
urlpatterns = [
# path('', views.home, name='home'),
# path('contact/', views.contact, name='contact'),
# path('about/', views.about, name='about'),
# path('login/',
# LoginView.as_view
# (
# template_name='app/login.html',
# authentication_form=forms.BootstrapAuthenticationForm,
# extra_context=
# {
# 'title': 'Log in',
# 'year' : datetime.now().year,
# }
# ),
# name='login'),
# path('logout/', LogoutView.as_view(next_page='/'), name='logout'),
path("admin/", admin.site.urls),
path("employees/", views.employeeList.as_view()),
]
Add @csrf_exempt
to your request while testing.
Note: this is not good to do in production, but it helps while using Postman.
To not enforce csrf protection, wrap your route with csrf_exempt()
.
from django.views.decorators.csrf import csrf_exempt
...
path("employees/", csrf_exempt(views.employeeList.as_view())),
More information can be found here.
Your 500 error can be due to the fact that you only pass in your post request, try returning return Response(status=200)
.
class employeeList(APIView):
...
def post(self):
return Response(status=200)
That one is tricky.
I hope I do not mess up here, but you are probably using some SessionAuthenticaion
in your
AUTHENTICATION_BACKENDS
. This backend uses CSRF protextion. I ran into this failure at least once :)
To offer a quickfix you can simply add authentication_classes = ()
to your APIView
like this
class employeeList(APIView):
authentication_classes = ()
def get(self, request):
employees1 = employees.objects.all()
serializer = employeeSerializer(employees1, many=True)
return Response(serializer.data)
def post(self):
pass
If the problem still persists please check DEFAULT_AUTHENTICATION_CLASSES
and if SessionAuthentication
is part of it, remove it. To check it you can quickly use:
from rest_framework.settings import api_settings
print(api_settings.DEFAULT_AUTHENTICATION_CLASSES)
I finally found the answer to this problem! i changed these lines and solved my problem.
project urls.py
path("employees/", csrf_exempt(views.employeeList.as_view()))
settings.py
DEBUG = True
ALLOWED_HOSTS = []
view.py
def post(self, request):
pass