Perform the action of a form without updating the page on Django

Asked

Viewed 51 times

1

I am developing a project where I need to add members to a group, for this, I go through all registered members and present them in my html template. Each member has next to the "add" button only always when doing this, it updates the page... I would like to know how to do this without updating, IE, I click add and it is already automatically added.

py views.

def adicionar_membros(request, id):
    plan=Planejamento.objects.get(id=id)
    usuarios = User.objects.all() # estendi o modelo padrão de usuarios do django

    return render(request,'site/adicionar_membros.html', {'plan':plan, 'usuarios':usuarios})

add members.html

{% extends 'base.html' %}

{% block title %} Adicionar Membros {%endblock%}

{% block content %}

  <section id="team" class="team2">
    <div class="container" data-aos="fade-up">
      <div class="row">
        {% for i in usuarios %}
            <h4>{{i.first_name}}</h4>
            <form method="POST">
               {% csrf_token %}
               <input type="submit">Adicionar</input>
            </form>
        {%endfor%}

{%endblock%}

1 answer

1

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?

  1. Grab the moment the button is clicked.
  2. 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!!!

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.