CSRF token missing on models with a file/imagefield

I have a project which is set up on AWS using lambda, s3, …

Because it is still in production we are using DjangoAdmin to manage the data in it.
All of my models work fine when I try to save them except the ones that have a filefield or imagefield in them. When I save those, I get a 403 - CSRF token missing error.

The weird thing is, working on localhost, It works perfectly, it even saves the files correctly into the s3 bucket. but once deployed on AWS Lambda, it throws me this error.

Anybody else had this problem? I’ve been searching for answers the past 2 weeks… asking on different forums but sadly didn’t find a solution for it.

Thanks in advance

Hi YorbenVerhoest, I don’t have a quick answer for you. I’d suggest digging into where exactly it’s breaking.

  • Does the token get generated and sent to the browser (hidden input, header or cookie)?
  • Does the token get sent back to the server?
  • Is the server causing the token to cycle on each request? This will require a fair amount of digging into django’s internals unless someone can chime in.

Hello CodenameTim!

Thanks for the interest in my question

So, i’ve done some digging and after a while I found out that when I save a model, that has a filefield / imagefield in it. My POST data wont be sent with the request that i make.

And because my csrfmiddlewaretoken is in my POST data, it makes sense that it gives me this error.

Now I’m trying to figure out, why this only happens when I’m not on localhost and why it only happens when there is an filefield / imagefield involved.

If you got any tips on how I would handle this , that would be awsome.

either way, I’ll keep you posted when I find a solution for this.

Did you determine that the client/browser isn’t sending the data or is request.POST empty?

Are you doing anything different on non-local environments in your application? Maybe some type of library on the client side to upload the image to S3 before hitting the lambda app?

Well, I wrote a custom csrffailureview and printed my request data in it.

And upon saving a model with an imagefield in it. It sends me to this page where I can see that my request.POST is empty.

(For testing, I saved another model without an imagefield and deleted the csrf cookie so that it would also send me to that csrffailureview. and there I can see that my request.POST has data.)

So by that thought I think that my request.POST is just empty for some reason…

How does this get used? Is another view calling it, redirecting to it or does the form submission get sent to it directly?

You should also check your browser’s developer tools on the network panel. Inspect the request there to make sure it contains everything you expect the browser to be sending to the server.