python - CSRF verification fails on requests.post() -


can't figure 1 out. csrf verification works fine in django template views. here i'm trying post python client using techniques i've found in other posts. client.get(url) call provide token (the debugger shows, example: client.cookies['csrftoken'] = 'poqmv69mupzey0nylmifbglfdfbgduo9') requests.post() fails error 403, csrf verification failed. what's going on?

my django view (with dummy stuff in methods):

class cameraupload(view):     template_name = "account/templates/upload.html"      def get(self, request):         dummy = videoform()         return render(request, self.template_name, {'form': dummy})      def post(self, request):         dummy = videoform()         return render(request, self.template_name, {'form': dummy}) 

and client that's trying post:

import requests  url = 'http://127.0.0.1:8000/account/camera_upload/'  client = requests.session() client.get(url) csrftoken = client.cookies['csrftoken']  payload = {     'csrfmiddlewaretoken': csrftoken,     'tag': '69' }  r = requests.post(url, data=payload) 

edit:

tried adding referer per this link code looks like:

r = requests.post(url, data=payload, headers=dict(referer=url)) 

but same problem exists.

solution:

turns out generating new request after calling method outside of client. relevant line should read:

r = client.post(url, data=payload) 

you should using session (client) post:

r = client.post(url, data=payload, headers=dict(referer=url)) 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -