CSRF verification failed after adding a filefield on model

I'm having a weird problem.
So I have an application where my model was completely fine until I added a Filefield to it.

Now I'm getting a CSRF-Verification failed error, even if I don't try to upload a file and leave it blank, it gives me the error below.

enter image description here

This is my model:

class Municipality(models.Model):
    activate_date = models.DateField()
    deactivate_date = models.DateField()
    code = models.CharField(max_length=200)
    name = models.CharField(max_length=200)
    alt_name = models.CharField(max_length=200, blank=True, null=True)
    logo = models.FileField( upload_to='Logo/muni', max_length=200, blank=True, null=True)

My Application is set up on AWS using AWS Lambda, S3, and other needed services

My S3 bucket (where my file should be uploaded to) is defined in my settings.py file with the env variable that has been defined on AWS Lambda environment variables

AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME', default=None)

I don't get why my model won't save even if I don't include a file.

The weird thing about it is that when I'm working locally, it doesn't give me this error. And I can save this model with or without uploading a file.

Other models where no Filefield or Imagefield is defined are perfectly working online and locally.

Any reasons why I'm getting this error whenever I try to add a Filefield or Imagefield?

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.

  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

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.

Back to Top