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
Post a Comment