-1

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()),
]

terminal error:

Internal Server Error: /employees/
Traceback (most recent call last):
  File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 511, in dispatch
    self.response = self.finalize_response(request, response, *args, **kwargs)
  File "C:\Users\moham\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 423, in finalize_response
    assert isinstance(response, HttpResponseBase), (
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` 
Mohammad Nazari
  • 137
  • 1
  • 12

2 Answers2

0

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)
Anonymous User
  • 494
  • 4
  • 12
0

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)
coderiot
  • 173
  • 1
  • 6
  • still i got 500! – Mohammad Nazari Aug 28 '22 at 11:07
  • Ok, what is the error then? is it 500 or 403? Please make clear what the actual HTTP status code is. If it is 500 please add the trace from the server running the python code, I mean give us the actual error. Also please turn off authetication generally in settings to see whether somehting is still wrong with SessionAuth. – coderiot Aug 28 '22 at 11:22
  • I have adjusted my answer, please check DEFAULT_AUTHENTICATION_CLASSES – coderiot Aug 28 '22 at 11:30
  • i hadn't define it in my project – Mohammad Nazari Aug 28 '22 at 12:09
  • From your comment I do not unserstand whether you checked that variable or not. Yes you may not have personally defined it, and it might still be defined, that is what is meant by `DEFAULT_` – coderiot Aug 28 '22 at 12:36