Reputation: 41
I'm trying to render a variable that will update multiple time in the code, but it just renders the last one to the template, for example on :
views.py:
def test(request):
message = 'first massage'
#do something
message = 'second massage'
return render(request,'test.html',{'message':message})
test.html :
<h1> {{message}} </h1>
It only displays the second message, but I want it to display the first message then after it changed, display the second message. Any help ?
Upvotes: 0
Views: 2115
Reputation: 21
Hello I think you can solve it by doing the following.... You need to create a loop.. it will look something like this..
Before your html code type in {% for message in messages %}
And after your html code type in {% endfor %}
Hopefully it works....
Upvotes: 0
Reputation: 141
If you want to change your 'message' variable dynamically ( like 'message' variable has something to do with your models),
a.)Update your 'message' variable using python in views.py, Create an api which returns JsonResponse.Then you can fetch this data through JavaScript and update (document.getElementById("someID").innerHTML=``${message}`)
in Views.py
def testapi(request):
# do something
return JsonResponse({"message":"VALUE_OF_MESSAGE"},status=201)
in javascript file
fetch('/testapi')
.then(response => response.json())
.then(resp => {
console.log(resp); //output=> {"message":"VALUE_OF_MESSAGE"}
var message=resp.message;
document.getElementById('someId').innerHTML= ``${message}`;
});
You can perform fetch request whenever you want to and any number of times.
2.)If you have to do something with elements in the page to update your message variable, I recommend you to use JavaScript directly.
Upvotes: 2