csrf token inside form django code example
Example 1: django csrf token
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
Example 2: Django Rendering Forms Manually and using csfr token
<form action="{% url "submit-form-url-name" %}" method="post" accept-charset="utf-8">
{% csrf_token %}
{{ form.field1 }}
{{ form.field2 }}
...
</form>