12

I wan't to test my django web app with locust.io. In a form I have a problem with CSRF token. I do the following:

class WebsiteTasks(TaskSet):
    def on_start(self):
        print("On start")

    @task
    def post_answer(self):
        self.client.get("/polls/2/vote")
        self.client.post("/polls/2/vote/", {"choice": "8"})

Why do I get a 403 error? That the post is forbidden, the locust documentation says that the client objects keeps the session alive..

Kaizendae
  • 853
  • 11
  • 24
renzop
  • 1,194
  • 2
  • 12
  • 26

2 Answers2

22

change your code as:

@task
def post_answer(self):
    response = self.client.get("/polls/2/vote")
    csrftoken = response.cookies['csrftoken']

    self.client.post("/polls/2/vote/", 
                     {"choice": "8"}, 
                     headers={"X-CSRFToken": csrftoken})
sax
  • 3,708
  • 19
  • 22
5

I ran into this problem running a Locust test against Django 1.8.5 and it required adding the csrf token to the cookies, headers, and form POST data as well like below in order to not get caught up with a 403. Something like:

@task
def post_answer(self):
    response = self.client.get("/polls/2/vote")
    csrftoken = response.cookies['csrftoken']

    self.client.post("/polls/2/vote/", {"choice": "8",
                     "csrfmiddlewaretoken": csrftoken}, 
                     headers={"X-CSRFToken": csrftoken},
                     cookies={"csrftoken": csrftoken})
iepathos
  • 499
  • 5
  • 7