Home > Net >  getting dynamic data from views to javascript
getting dynamic data from views to javascript

Time:06-11

Just like we can set a context variable for the default users in a django template, var user = "{{request.user}}" How do I do the same thing for a custom Model?

When I try using var text = "{{ news }}"; it displays random letters instead of the objects one by one

let's say there are three objects associated with News model:

object1 = "this is test one"
object2 = "this is test two"
object3 = "this is test three"

model

class News(models.Model):
    news_today = models.CharField(max_length=80, null=True, blank=True)

views

def test(request):
    news = News.objects.all()
    context = {"news ": news}

template

<script>

    var text = "{{request.news}}";

</script>

js [trying to achieve showcasing of one sentence at a time from those three objects]

var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 5000);

function change() {
  elem.innerHTML = text[counter];
  counter  ;
  if (counter >= text.length) {
    counter = 0;
  }
}

CodePudding user response:

For what you are trying to do, you do not need to get it from request, news is its own context variable like request, so all you have to do is call it directly, like this:

<script>

    var text = "{{ news }}"

</script>

PS: Keep in mind that {{news}} and {{ news }} , the whitespace is ignored.

CodePudding user response:

You are trying to assign a django model queryset to a simple var in JS, that is a bad idea, you need to be more concise, if you need a list of texts you can loop the queryset and build a list of texts:

var text = [];
{% for n in news %}
    text.append("{{n.news_today}}");
{% endfor %}
// do what ever you want with your list of news texts
  • Related