djangopermissionscsrfcsrf-tokendjango-rest-viewsets

CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins


Please help me solve the problem. I was building an app consisting of Django Rest Framework and ReactJS. I used ViewSets.

my error: Screenshot of the error

Demo

response data:

{"detail":"CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins."}

DeleteLead function in ReactApp

 export const deleteLead = (id) => (dispatch) => {
  axios
    .delete(`/api/leads/${id}/`)
    .then((res) =>
      dispatch({
        type: DELETE_LEAD,
        payload: id,
      })
    )
    .catch((err) => {
      console.log(err);
    });
};

LeadViewSet: from rest_framework import viewsets, permissions from .serializsers import LeadSerializers from leads.models import Lead

# lead viewset
class LeadViewSet(viewsets.ModelViewSet):
    queryset = Lead.objects.all()
    # permission - bu ruxsat beruvchi
    permission_classes = [
        permissions.AllowAny # barcha uchun ruxsat
    ]
    serializer_class = LeadSerializers

LeadSerzializers:

# lead serializer
class LeadSerializers(serializers.ModelSerializer):
    class Meta:
        model=Lead
        fields="__all__"

Lead model:

class Lead(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=100, unique=True)
    message = models.TextField(max_length=500, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Solution

  • Try to set your CSRF trusted origins, allowed host and in the settings file like this

    CSRF_TRUSTED_ORIGINS = [
        'http://localhost:8000'
    ],
    ALLOWED_HOSTS = [
        'localhost',
    ],
    CORS_ORIGIN_WHITELIST = [
        'http://localhost:8000',
    ]