Home > Enterprise >  Dynamically updating Django template with new data
Dynamically updating Django template with new data

Time:07-06

I am creating a cricket website which shows the live scores of cricket matches using Django. I want my template to update its content in (section id='main-content') dynamically after some timeout and I don't know how to implement it.

Here is my code:

views.py

def livescores():
    # generates livescores and returns a dict containing live scores
    return scores

def display_scores(request):
    # calls the livescores function and gets the dict and 
    #passes it to django template for rendering purposes
    scores = livescores()
    return render(request, 'LiveScores/display_scores.html', scores)

template

<html>
    <head>
        <title>{{MatchName}}</title>
        {% load static %}
        ...
    </head>
    <body>
        <header>
          ...
        </header>
        <section  id="main-content">
            <div >
                <div >
                  <div >
                    <div >
                      <h5 >{{Team1}}</h5>
                      <p >{{RunRate}}</p>
                    </div>
                  </div>
                </div>
                <div >
                    <div >
                      <div >
                        <h5 >{{result}}</h5>
                        <p >{{situation}}</p>
                      </div>
                    </div>
                  </div>
                <div >
                  <div >
                    <div >
                      <h5 >{{Team2}}</h5>
                      <p >* LIVE</p>
                    </div>
                  </div>
                </div>
            </div>
        </section>
    </body>
</html>

I have followed some answers on SO regarding the use of Ajax for the purpose but it did me no help: some answers caused the navbar to duplicate when the content was updated and others just populated the tag with unnecessary things like 'Bootstrap CDN links'.

CodePudding user response:

If you don't want to go into ajax/js (at some point in future you will need too) I can recommend use htmx (htmx.org)

So change your view to:

def livescores(request=None):
    # generates livescores and returns a dict containing live scores
    if request is None:
        return scores
    else:
        return render(request, 'livescores/components/livescores.html', scores)

In livescores/components/livescores.html template:

  <div >
            <div >
              <div >
                <div >
                  <h5 >{{Team1}}</h5>
                  <p >{{RunRate}}</p>
                </div>
              </div>
            </div>
            <div >
                <div >
                  <div >
                    <h5 >{{result}}</h5>
                    <p >{{situation}}</p>
                  </div>
                </div>
              </div>
            <div >
              <div >
                <div >
                  <h5 >{{Team2}}</h5>
                  <p >* LIVE</p>
                </div>
              </div>
            </div>
        </div>

so here is nothing changing in your code.

Add urlpattern for livescores in yours urls.py

in livesocres.html main template change:

 <section  id="main-content">

to:

 <section  id="main-content" hx-get="/url/to/livescores" hx-trigger="every 5s">

and add:

  <script src="https://unpkg.com/[email protected]"></script>

CodePudding user response:

u need rest api that return json

from django.http import HttpResponse

def get_ajax_data(request):     
    scores=livescores()   
    return HttpResponse(json.dumps(scores), content_type='application/json')

and in your ajax call. here im using jquery

         var team1=$(`<div >
              <div >
                <div >
                  <h5 >{Team1}</h5>
                  <p >{RunRate}</p>
                </div>
              </div>
            </div>`)
          var desk=$(`<div >
                <div >
                  <div >
                    <h5 >{result}</h5>
                    <p >{situation}</p>
                  </div>
                </div>
              </div>`)
           var team2=$(`<div >
              <div >
                <div >
                  <h5 >{Team2}</h5>
                  <p >* LIVE</p>
                </div>
              </div>
            </div>`)
$(function(){
  setTimeout(function(){
     $.ajax({
          method: "GET",
          url: "{% url 'ajax_data' %}",
          data: {data: your_additional_data_to_send}
        }).done(function( score) {
       
       
       $(team1).find(".card-title").text(score.team1)
       $(team1).find(".card-text").text(score.runrate)
       $(desk).find(".card-title").text(score.result)
       $(desk).find(".card-text").text(score.situation)
       $(team2).find(".card-title").text(score.team2)
      
       $("#main-content").html(team1)           
       $("#main-content").append(desk)
       $("#main-content").append(team2)
      });
   },4000)


})
  • Related