Reputation: 133
I'm building a Django app and I would like to have a view/function add a line of html to the inner html of a specific div element with an id every time it is run.
I know how to do this with Javascript but then I would need the view to run that script every time it runs. Is there a way to do this in the Python document?
Upvotes: 2
Views: 3891
Reputation: 919
The title of your question asks about creating a DOM Element in python. In order to do so, inside your views.py
from django.template import Context, Template
def in_some_view(request):
template = Template('<div class="new-dom-element">Element</div>')
'''
You can create elements above. You can even give it Context Variables
For example: template = Template('<div class="new-dom-element">{{ context_variable }}</div>')
'''
context = Context({'context_variable': your_python_variable})
#By sending the context variable "your_python_variable", you can do anything iteratively.
dom_element = template.render(context)
#Now you can return this dom_element as an HttpResponse to your Javascript.
#Rest of your code.
return HttpResponse(dom_element)
Note: I answered this keeping in mind that you don't want to take a way outside the domain of AJAX requests. If so, then it's really difficult to bring and append some data if an HTML is already displayed on the browser screen. That's exactly why AJAX was created in the first place.
Hope this helps. Thanks.
Upvotes: 1