1

I have a Django model:

class MyModel(models.Model):
    charField = models.CharField(maxLength=200)
    textField = models.TextField()

and an HTML template with a JS function that displays charField and textField like this:

document.getElementById("someElement").innerHTML = "{{ myObject.charField }}";
document.getElementById("someOtherElement").innerHTML = "{{ myObject.textField }}";

The former works fine, but the latter doesn't. I assume the problem is the fact that it is a TextField because there is no other difference between the two. How can I fix this?

1 Answer 1

2

For a <textarea> you should use .value, so:

document.getElementById("someOtherElement").value = "{{ myObject.textField }}";

for <div>, you should ineed use .innerHTML.

Note that both are not a good idea since Django will HTML encode the values, and thus thus can result in &quot;, &amp;, etc. in the values. You should use the |escapejs template filter [Django-doc]:

document.getElementById("someElement").innerHTML = "{{ myObject.charField|escapejs }}";
document.getElementById("someOtherElement").innerHTML = "{{ myObject.textField|escapejs }}";
Sign up to request clarification or add additional context in comments.

16 Comments

I did that but it still doesn't show anything. Any idea what could be the problem? It works when I put {{ myObject.textField }} directly in the element.
@Kristína: can you see anything on the browser console? Exactly what is the content that you render as output?
@Kristína: note that if you do this directly, the encoding is different, since for a html argument, it uses ampersand encoding, whereas for Javascript, you should JSON-encode it.
Sorry for a stupid question, I'm completely new to this. Should I type the javascript line into the console?
@Kristína: yes, I was initially under the impression that it was a <textarea>, not a <div>. For a <div> it is indeed innerHTML.
|

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.