Search code examples
djangodjango-modelsweb-applicationsdjango-forms

How to stop page refresh on each task addition in my Django To-do app?


I am quite new to the web development world and have just built a Todo app using Django. I have used Django ModelForm for adding tasks to my TaskModel.

Now my problem is that each time I add a task, the whole page refreshes as the added task goes to the database. It is not a very good user experience, as it is refreshing the page on each task addition and also it is taking time for reloading the page. What should I do to stop page refresh but still add the task to the database?

my views.py looks something like this:

def index(request):
    if request.method == 'POST':
        form = TaskForm(request.POST or None)

        if form.is_valid():  
            form.save()
            all_tasks = TaskModel.objects.all()
            return HttpResponseRedirect(reverse("index"))
    else:
        all_tasks = TaskModel.objects.all()
    return render(request, "todo_list/index.html", {"all_tasks": all_tasks})

Note: I have used authentication in my todo app so that the tasks can be accessed from any device, so I don't think storing my task merely in the browser cache will work. But I am open to any suggestions.


Solution

  • Back-end

    Use django-rest-framework so that you can handle the server traffic manually.

    Front-end

    You can use a DOM API called XMLHttpRequest, but also you can use more easy to use APIs such as fetch.

    When the form event is emitted we have to e.preventDefault().

    form.addEventListener("submit", (e)=>{
      e.preventDefault();
    
      // use the same URL in form's action <form action="{{url}}"></form>
      fetch(url, {
        method: "POST",
        data: new FormData(form),
      })
      .then((response)=>{
        return response.json()
      })
      .then((json)=>{
        return console.log(json);
      })
      .catch((err)=>{
        console.err(err); // an error occured
      });
    });
    

    The Django server can respond with a different type of data, plain/text or application/json are suitable in this situation.

    BTW, fetch is a function that returns a Promise, so you can use async and await to make you code look better. You can use axios, or JQuery.ajax to make XMLHttpRequest more easy to handle.