[Django]-CSRF verification failed after adding a filefield on model

1👍

When using a models.FileField in Django, the key point is to declare the enctype as following:

<form enctype="multipart/form-data" action="" method="post">
  ...
  {% csrf_token %}
  ...
</form>

See here.

0👍

  1. Try clearing cookies and refreshing
  2. Check to make sure you have
    django.middleware.csrf.CsrfViewMiddleware in your middleware
  3. Check that you’re either on https or you have
    CSRF_COOKIE_SECURE=False

0👍

First of all you should check by undoing the changes you made to the model. If the problem still persists ,then you may have made some change elsewhere. Also try it from a different device and user account(even after clearing cookies/hard reload, somethimes browsers behave unexpectedly).
You can also try answers from these links.(link 1, link 2 )

Checking the html source may help.
Also, if you are using custom django admin forms, check them again if they require any changes. Using @csrf_exempt while trying different scenarios may help you understand, if this error is really because of csrf or there is another problem.

Also see this in django docs.

0👍

Same issue. Played with requires_csrf_token and csrf_protect. None worked for me.
Browser was launched in user session, and uploading file was 777 root:root in /home/username. changed file owner to user, and all worked.

So, in some scenarios, not only chmod 777, but chown username:username.

-1👍

I faced the same issue. My problem was with the file permissions, I had to use sudo chmod 777 file

👤P3RI9

Leave a comment