Django CSRF Token without forms

后端 未结 4 1257
天命终不由人
天命终不由人 2021-02-05 21:04

Sounds strange but what about the scenario posting contents with Javascript (for example AJAX) without using a form (could be possible to read several contents from the surface)

4条回答
  •  情歌与酒
    2021-02-05 22:04

    One CSRF token is assigned to every session ( i.e. every time you log in). So before you wish to get some data entered by user and send that as ajax call to some function which is protected by csrf_protect decorator, try to find the functions that are being called before you are getting this data from user. E.g. some template must be being rendered on which your user is entering data. That template is being rendered by some function. In this function you can get csrf token as follows: csrf = request.COOKIES['csrftoken'] Now pass this csrf value in context dictionary against which template in question is being rendered. Now in that template write this line: Now in your javascript function, before making ajax request, write this: var csrf = $('#csrf').val() this will pick value of token passed to template and store it in variable csrf. Now while making ajax call, in your post data, pass this value as well : "csrfmiddlewaretoken": csrf

    This will work even if you are not implementing django forms.

    In fact, logic over here is : You need token which you can get from request. So you just need to figure out the function being called immediately after log in. Once you have this token, either make another ajax call to get it or pass it to some template which is accessible by your ajax.

提交回复
热议问题