Get informations for each x seconds

I would like to know if there is a way to check every x seconds a value in a database table in django, and if it is the desired value, the user is redirected to another page.

what i tried:

I tried to use a form and it posts every 3 seconds and as soon as it makes the post it would check the table (model), but the page doesn't even load, because of sleep (it's worth mentioning that I tried SetTimeout and SetInterval)

def wait(request, slug):
    form = MatchForm()
    if request.method == 'POST':
        roomName = Match.objects.get(roomname = slug)
        if (int(roomName.num_players) > 1):
            return redirect(f'../play/{slug}')
    
    return render (request, 'chess/waiting_room.html', {'slug':slug, 'form':form})

waiting_room.html - javascript

function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}


subm_form()

function subm_form(){
  var form = $("#form")
  form.submit();
  sleep(3000)
  subm_form()
};

I preferred to reload the page for each 10 seconds and based on the table the view does something.

In the type of approach I needed, I saw that the POST and/or form didn't work very well as expected, but if you want to use it, try putting a function inside the TimeOut that gives submit.

VIEWS.PY

def wait(request, slug):
        roomName = Match.objects.get(roomname = slug)
        if (int(roomName.num_players) == 0):
            obj = Match.objects.get(roomname=slug)
            obj.player1 = f'{request.user.username}'
            obj.num_players = '1'
            obj.save()
        elif (int(roomName.num_players) == 1 and roomName.roomname.split('__vs__')[0] != request.user.username):
            obj = Match.objects.get(roomname=slug)
            obj.player2 = f'{request.user.username}'
            obj.num_players = '2'
            obj.save()
        elif (int(roomName.num_players) == 2):
            return redirect(f'../play/{slug}')
    

    
        return render (request, 'chess/waiting_room.html', {'slug':slug})

def play(request, slug):
    room = Match.objects.get(roomname=slug)
    context = {
        'iterator':'',
        'slug':slug,
        'actual_player' : 0,
        'room':room,
    }
    
    return render (request, 'chess/play.html', context)

MYPAGE HTML

setTimeout(function(){window.location.href=window.location.href;}, 10000);
Back to Top