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?
- Catch the moment when the value is changed.
- Send to Django via Axios.
You can do this either with direct functions in the element, or with Event Listener. Within this function you should take the input value, using the onInput event (either in direct functions, or with Listener). Within this function you will make the call to the view.
let data = 'valor do input'
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.
const config = {
// O nome do header é o Django que dá, por padrão. Mas você pode mudar nas configurações.
headers: {
''X-CSRFToken': csrftoken,
}
}
Soon after adjusting the settings, you send your request.
Just make an HTTP request by sending the value. O
<input>
is in a form? If yes, when submitting the form the request is made and the value sent to the route you set for the view.– Woss
Anderson <input> is in a form but initially the input has no value. only after the user enters something he would have to take value, and complete the rest of the form inputs based on this value.
– Eduardo
So search for AJAX requests.
– Woss