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

4

14

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
Preferable answered 6/1, 2022 at 19:14 Comment(0)
L
22

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',
]
Lasonde answered 6/1, 2022 at 22:56 Comment(1)
BROOOOOOO THANK YOU!!!!!!!!!!Coverture
H
0

Adding more to what Jaime wrote, I have this:

python manage.py shell <<EOF
from django.conf import settings
from urllib.parse import urlparse

print([urlparse(origin).netloc.lstrip("*") for origin in settings.CSRF_TRUSTED_ORIGINS])
print({origin for origin in settings.CSRF_TRUSTED_ORIGINS if "*" not in origin})
EOF

Running the above will reveal what the set details for CSRF_TRUSTED_ORIGINS are.

I had a situation where I was correct but then, somewhere below the settings file, this same setting was referring to a localhost:7007, and it was already deployed.

The above helped me detect and fix it. And if your app is inside a docker container, start it as:

docker exec -i add-container-name-here python manage.py shell

and the other parts of it will remain the same as shown above.

a sample of the error page on deployment

Heall answered 1/3, 2023 at 20:20 Comment(0)
R
0

To all the people who are doing this locally, this might be because you are logged-in to the Django admin panel. Logging out fixed the error.

All the CSRF solution is the right way to do it. However, if you are building a local project, this solution may work.

This is because, Django expects a CSRF token when a user session exists and since Django uses cookie sessions by default, which are susceptible to cross site request forgery (CSRF). Of course when there is no user logged in there is no reason to use CSRF because there is no cookie to protect so the request will work without the token.

Regatta answered 4/7, 2023 at 1:13 Comment(0)
D
0

I was also getting the same issue while performing the API testing in postman and i resolved the this issues by clearing the cookies in postman tool

Deface answered 8/11, 2023 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.