javascriptdjangowindow.location

JAVASCRIPT: After sending Item to Database (POST) the window.location.reload() does not work. How to refresh the Data in HTML-Template?


I recode a Tutorial on Youtube. Django, Python, HTML an Javascript. Everthing works fine exept the window.location.reload() function.

I try some workarounds with

and some more.

I have a hunch that the reload is executed before or during the code before the reload. But I do not know.

The goal is to send the data from the input to the database and only then refresh the page.

This ist the Code from the tutorial:

index.html (shortened)

<body>
    <header>
        <h1>Shoppinglist</h1>
        <div id="input-field">
            <label for="item-input">Was möchtest du einkaufen?</label>
            <input type="text" name="item" id="item-input">
        </div>
        <button id="btn" onclick="addItem()">+</button>
    </header>
    <div id="item-table">
        {%  for row in all_items %}
        <div class="list-item">
            <input type="checkbox"> {{row.name}}
        </div>
        {% endfor %}
    </div>

   
    <script>

        function addItem(){
            let itemName = document.getElementById("item-input").value;
            let formData = new FormData();
            let token = '{{csrf_token}}';
            formData.append('itemName', itemName);
            formData.append('csrfmiddlewaretoken', token);
            fetch('/mylist/', {
                method: 'POST',
                body: formData
            });
            window.location.reload();
        };

    </script>
</body>
</html>

views.py

from django.shortcuts import render
from .models import ShoppingItem

# Create your views here.
def mylist(request):
    if request.method == 'POST':
        print('Received date: ', request.POST['itemName'])
        ShoppingItem.objects.create(name = request.POST['itemName'])
    all_items = ShoppingItem.objects.filter(done = 0)
    return render(request, 'index.html', {'all_items':all_items})

models.py

from django.db import models
from datetime import date

#Create your models here.
class ShoppingItem(models.Model):
    creatDate = models.DateField (default=date.today)
    name = models.CharField (max_length =200)
    done = models.BooleanField(default=False)

    def __str__(self):
        return '(' + str(self.id) +') ' +self.name

Solution

  • Try this:

    async function addItem() {
      let itemName = document.getElementById("item-input").value;
      let formData = new FormData();
      let token = "{{csrf_token}}";
      formData.append("itemName", itemName);
      formData.append("csrfmiddlewaretoken", token);
      await fetch("/mylist/", {
        method: "POST",
        body: formData,
      });
      window.location.reload();
    }