1from django.views.decorators.csrf import csrf_exempt
2
3@csrf_exempt
4def xyx(request):
5 #your code
6
7#this makes the function accept post request without csrf token
8#use it just for quick check or for operations where csrftoken authentication
9#isn't required
1<form action="{% url "submit-form-url-name" %}" method="post" accept-charset="utf-8">
2 {% csrf_token %}
3 {{ form.field1 }}
4 {{ form.field2 }}
5 ...
6</form>
1# get csrf token value in template
2{{ csrf_token }}
3# render a input form element
4{% csrf_token %}
1let data = {
2 'file': file,
3 'fileName': file.name,
4};
5// You have to download 3rd Cookies library
6// https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
7let csrftoken = Cookies.get('csrftoken');
8let response = fetch("/upload/", {
9 method: 'POST',
10 body: JSON.stringify(data),
11 headers: { "X-CSRFToken": csrftoken },
12})
13
1Cross Site Request Forgery protection¶
2The CSRF middleware and template tag provides easy-to-use protection against
3Cross Site Request Forgeries. This type of attack occurs when a malicious
4website contains a link, a form button or some JavaScript that is intended
5to perform some action on your website, using the credentials of a logged-in
6user who visits the malicious site in their browser. A related type of attack,
7‘login CSRF’, where an attacking site tricks a user’s browser into logging into
8a site with someone else’s credentials, is also covered.
9
10The first defense against CSRF attacks is to ensure that GET requests
11(and other ‘safe’ methods, as defined by RFC 7231#section-4.2.1) are
12 side effect free. Requests via ‘unsafe’ methods, such as POST, PUT,
13 and DELETE, can then be protected by following the steps below.
1function getCookie(name) {
2 let cookieValue = null;
3 if (document.cookie && document.cookie !== '') {
4 const cookies = document.cookie.split(';');
5 for (let i = 0; i < cookies.length; i++) {
6 const cookie = cookies[i].trim();
7 // Does this cookie string begin with the name we want?
8 if (cookie.substring(0, name.length + 1) === (name + '=')) {
9 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
10 break;
11 }
12 }
13 }
14 return cookieValue;
15}
16const csrftoken = getCookie('csrftoken');
17