Django.fun

Form data is passing in html table

I am submitting the form data by using fetch API and then I want to show some variable values in HTML table. But it's not working as it's supposed to be. I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table. Without the fetch API submit, everything is working fine as per my need. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong.

views.py

def home(request):
    context={}

    if request.method=="POST":

        options_value=request.POST['dropdown_val']

        value=request.POST['val']

        print(options_value,value)

        context={"options_value":options_value, "value":value}

  return render(request, 'index.html',context)

index.html

<form method="POST" action="" id="form">

      {% csrf_token %}

          <select

            class="form-select"

            aria-label="Default select example"

            name="options_value"

            id="dropdown_val"

          >

            <option disabled hidden selected>---Select---</option>

            <option value="1">Profile UID</option>

            <option value="2">Employee ID</option>

            <option value="3">Email ID</option>

            <option value="4">LAN ID</option>

          </select>

          <input

            type="text"

            class="form-control"

            type="text"

            placeholder="Enter Value"

            name="value"

            id="value"

          />

          <input

            class="btn btn-primary"

            type="submit"

            value="Submit"

            style="background-color: #3a0ca3"

          />

    </form>

<table style="display: table" id="table">

        <tbody>

            <tr>

              <th scope="row">ProfileUID :</th>

              <td>{{options_value}}</td>

            </tr>
            
            <tr>

              <th scope="row">First Nane :</th>

              <td>{{value}}</td>

            </tr>

        </tbody>

      </table>

<script>

      let form = document.getElementById("form");

      let dropdown_val = document.getElementById("dropdown_val");

      let val = document.getElementById("value");

      const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value;



      form.addEventListener("submit", (e) => {

        e.preventDefault();

        const newform = new FormData();

        newform.append("dropdown_val", dropdown_val.value);

        newform.append("val", val.value);

        newform.append("csrfmiddlewaretoken", csrf);

        fetch("", {

          method: "POST",

          body: newform,

        })


      .then(response => response.text())
      .then(data => {
       console.log('Success:', data);
       })
       .catch(error => {
       console.error('Error:', error);
       });

      });

    </script>

Things in the POST array are indexed by the name, not the id. You need

options_value = request.POST['options_value']

not dropdown_val.

It seems like you are never rendering the response. A quick fix would be to simply overwrite the html from javascript whenever you receive the response after making a POST request:

      .then(response => response.text())
      .then(data => {
       console.log('Success:', data);
       document.write(data);
       })
       .catch(error => {
       console.error('Error:', error);
       });

Tutorials

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

Обработка периодических задач в Django с помощью Celery и Docker

View all tutorials →