0

I am running a django website . Here is my code :

views.py:

@permission_classes((IsAdminUser,))
class ProfileView(viewsets.ModelViewSet):
    queryset=Profile.objects.all()
    serializer_class=ProfileSerializer
    @csrf_exempt
    def list(self,request):
        return Response({'message':'Append Profile ID to the API to view Profile of Particular User'})

def get_serializer_class(self):
    serializer_class = self.serializer_class

    if self.request.method == 'PUT' or self.request.method == 'PATCH':
        serializer_class = ProfilesSerializer

    return serializer_class

@permission_classes((IsAdminUser,))
    class LoginView(viewsets.ModelViewSet):
        queryset = Token.objects.all()
        serializer_class = LoginSerializer
        http_method_names = ['get', 'head']

urls.py:

router=routers.DefaultRouter()
router.register('profiles',views.ProfileView)
router.register('login', views.LoginView)

urlpatterns = [
    path('home/',include(router.urls)),
]

I need to get response in JSON . If i enter the url in postman , i am getting the error like this `"CSRF Failed: CSRF cookie not set." Can someone help me to fix this error?

Karthik J
  • 109
  • 4
  • 12
  • Does this answer your question? [Django CSRF Cookie Not Set](https://stackoverflow.com/questions/17716624/django-csrf-cookie-not-set) – rpm192 Jan 06 '20 at 07:00
  • Does this answer your question? [Django Rest Framework remove csrf](https://stackoverflow.com/questions/30871033/django-rest-framework-remove-csrf) – Iain Shelvington Jan 06 '20 at 07:07
  • urlpatterns = [ path('login/',csrf_exempt(views.LoginView.as_view())), ] – Iqbal Hussain Jan 06 '20 at 07:12
  • I have tried this . But it is still showing error as "The `actions` argument must be provided when calling `.as_view()` on a ViewSet." – Karthik J Jan 06 '20 at 07:16
  • No i have tried the above 2 links as well. Still the error is there. – Karthik J Jan 06 '20 at 07:17

1 Answers1

0

You can put this functions in your JS file and try.

function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
beforeSend: function(xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
}
});
Pratiksha k
  • 1
  • 1
  • 1
  • 2