1

views.py

context = {'select_company': select_company,}
return render(request, 'invest/chart.html', context)

html

<option value="{{o}}">{{select_company}}</option>----------{{select_company}} can show its value
<script>
company = {{select_company|safe}}; ---------------js tell me undefined
</script>

django 2.2 python 3.7 how to solve the weird problem

2
  • Is your script embedded in your django template or in a separate file? If in your template, look at the source in your browser. You might need to quote the string, if it's supposed to be string: var company = "{{ select_company|safe }}" Commented Apr 6, 2020 at 15:56
  • var company = "{{ select_company|safe }}" is what i want and solved the problem, the answer about data attributes is another solution. Commented Apr 7, 2020 at 1:58

2 Answers 2

2

Maybe data attributes:

your_template.html

<div id="some-element" data-company="{{ selected_company }}"></div>

your_javascript.js

const element = document.querySelector('#some-element');

console.log(element.dataset.company);
Sign up to request clarification or add additional context in comments.

Comments

1

When you want to assign a template variable to a string in javascript, you need to add the quotes. {{ select_company|safe }} will just expand the string in your template so you end up with:

var company = some string;

Since some isn't defined as variable, you get an "undefined" error.

Always do this:

var company = "{{ select_company|safe }}";

which will render as

var company = "some company";

Tip: Always take a look at the rendered source code in your browser developer tools when you get errors in your HTML pages, you will spot these kind of mistakes much easier.

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.