Django: update a page without reloading

18,844

What your looking is an ajax call to update the data on the page without the whole page refresh. For that, you would require a javascript call to send the form data to the backend and receive a json object back on success.

You can write a separate view for that or handle that by method check in the same view at python end(I prefer sep view for APIs). If using the same view remember to return the JSON object instead of a template renderer.

What javascript is doing is simply taking form data from your webpage and sending it to the designated URL then waiting for the response. For it to apply changes it needs a response(#can read about js promises). So there need to be a backend(python in this case) to listens to this call and return appropriate data(on success).

A nice follow links can be:

https://www.geeksforgeeks.org/handling-ajax-request-in-django/

https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

http://www.tangowithdjango.com/book17/chapters/ajax.html

Share:
18,844
Esrat
Author by

Esrat

Updated on August 28, 2022

Comments

  • Esrat
    Esrat over 1 year

    I want to update my homepage.html with button action and show some result from the server. But the problem is when I click on the button the whole page is reloading. Here, my project name is "T2KG". My form tag looks like this:

    <form method="POST">
            {% csrf_token %}
    
            <center><textarea placeholder="Give a input sentence....."
          class="text" name="sent" rows="5" cols="70" font="15px arial, sans-serif" autofocus>Barack Obama born in Hawaii. Hawaii locates in USA.</textarea></center><br>
            <button type="submit" class="btn btn-primary btn-block" id="display_result">Generate Triple</button>
    </form>
    

    By searching in many websites I have understood that my view.py and urls.py is not correct and also I have to use AJAX. But How to implement in this situation I don't know. I have tried but couldn't find any way out. In view.py I return the value like this:

    def result(request):
    text = 'null'
    if request.method == 'POST':
        form_input = Sentence(request.POST)
        if form_input.is_valid():
            text = form_input.cleaned_data['sent']
        else:
            form_input = Sentence()
    
    triples = getTriples(text)
    
    ent_list = entityList(text)
    triples = predicateList(aggregate(triples, ent_list))
    return render(request, './T2KG/homepage.html',{'triples': triples, 'json_triples': json.dumps(triples), 'text':text})
    

    And my urls.py is:

    urlpatterns = [
    path('', views.set_sent, name='set_text'),
    url(r'^T2KG/homepage', views.result, name='result'),]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    

    Please help me.