6

I am doing my django project and I cannot find answer to how can I call my site from javascript function.

  var time = 5;
  setInterval(function() {
    if(time > 0) {
      document.getElementById("timecounter").innerHTML = "You will be redirected in "
      + time + " seconds. If not then ";
      time--;
    } else {
      location.href="{% url 'index' %}"
    }

  },1000)

this location.href redirects to wrong place. It literally puts "{% url 'index' %}" in URL.

Thank you for help!

8
  • Is this code used in a django-template? Commented Feb 27, 2016 at 12:15
  • Hi, this is in static/timecounter.js and I am calling this from my html Commented Feb 27, 2016 at 12:18
  • @chazefate Your template tag {% url (obviously) won't work unless it is used in a Django view/template. Use absolute URL of your site instead. Commented Feb 27, 2016 at 12:20
  • 1
    You want to redirect to the root directory? Why don't you just use / Commented Feb 27, 2016 at 12:25
  • 1
    As @ilse2005 has said, you need to redirect to / or wherever index is. Template tags are only interpreted by django when rendering a page. Javascript is run in the browser, totally unrelated to django Commented Feb 27, 2016 at 14:32

1 Answer 1

7

As your code is static and not processed by django, you can't use template tags. Change your code to this:

var time = 5;
  setInterval(function() {
    if(time > 0) {
      document.getElementById("timecounter").innerHTML = "You will be redirected in "
      + time + " seconds. If not then ";
      time--;
    } else {
      location.href="/" //this will redirect to your index
    }

  },1000)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.