Using AJAX you can easily, but for this we will use a special tool, and configure it the right way.
First you need to install the Xios. It is an http client that can be added to your html by the script tag as you can see in the documentation.
What are we gonna do?
- Grab the moment the button is clicked.
- Send to Django via Axios.
To send a form through AJAX Django requires, that you specify that it is a multipart/form-data
Thus
<form method="POST" enctype="multipart/form-data">
And your Input must have a name attribute, so Django can get its value from the view. When the user submits the form you must capture the event
let form = document.getElementById('form'); // selecting the form
form.addEventListener('submit', function(event) { // adiciona o listener para o submit
event.preventDefault()//previne comportamento padrão
let data = new FormData(form); // Junta os dados do formulário
Right after you must make a request in Xios, sent the date variable.
axios.post('url-da-view', data, config)
.then((res)=>{
//aplique as mudanças no DOM aqui
})
.catch((erros)=>{
//Pegue os erros aqui.
})
All right, looks like we’re done, right? NOP. You see that config variable in the Axios call? There we have to send a cookie to Django, so that the back-end is protected from CSRF attacks. According to documentation of Django we must copy the following function to get the cookie:
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();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;}
const csrftoken = getCookie('csrftoken');
To send this cookie on Xios we use that config variable (before sending the request)
const config = {
// O nome do header é o Django que dá, por padrão. Mas você pode mudar nas configurações.
headers: {
'X-CSRFToken': csrftoken,
'Content-Type': 'multipart/form-data', //Aqui você passa o formato novamente.
}
}
Soon after adjusting the settings, you send your request.
I recommend you to put an Hidden input with the value of the pk or user name you want to add, so Django can take this value in the view, based on the input name, and can make the querysets. Assuming your input without the name 'user':
request.POST['user']
Thanks Rubens, Axios I don’t know, just heard about Ajax. I will research on to better understand what you guided me, I thank you already too much the detailed reply in this way, Thanks!!!
– DoRenatoRock
Tmj. In addition to Next has jquery, I just didn’t mention it because Next has this focus on this request feature, since jquery has many other things that you might not even use. But if you already use jquery in the project, you can try ajax in it too.
– Rubens Rafael