2

when I am writing my Django view sometimes I pass as a context a JSON serialized object this way:

context = {'mydata': json.dumps(my_dictionary)}
return render(request, "mytemplate.html", context=context)

Then in mytemplate.html, in a js script, I do something like:

var myVar = {{ mydata }}

At this point PyCharm throws a warning about myVar, because that variable might not have been initialized since it doesn't recognise the django template tag as a valid value for a variable in javascript.

Now, I understand it is just a warning, but is there a clean way to get rid of it? Am I doing anything wrong?

Alasdair
  • 298,606
  • 55
  • 578
  • 516
valenz
  • 311
  • 1
  • 2
  • 13
  • I think I ended up just turning the warning off, not sure if thats a viable solution for you – Sayse Feb 09 '16 at 15:42
  • I think I'll just add an extra var myVar = null; but that's annoying.. – valenz Feb 09 '16 at 15:44
  • 1
    @user2283224 - Also that might solve those declarations but it doesn't help with methods i.e `myMethod({{something}}, {{else}});` – Sayse Feb 09 '16 at 15:53
  • 4
    @user2283224 You can avoid all of that if you adopt a better approach (By making JS pull the data from an API, instead of via injection through Django template string interpolation. It's an extra HTTP request, but this makes the JS part completely static and cachable, which improves the performance, because then the HTML and JS part is static/cached, and browsers can do several HTTP requests in parallel). Ref: http://stackoverflow.com/a/34843506/238639 – bakkal Feb 09 '16 at 15:58
  • These warnings get shown if you declare a variable inside an if statement or similar. If you post your view I could point out a fix for these warnings. – markwalker_ Feb 09 '16 at 15:59
  • @marksweb - `` is enough to reproduce the issue – Sayse Feb 09 '16 at 16:01
  • @Sayse yes, and I know the issue, but doing that won't help us point out what the fix in user2283224's view is. – markwalker_ Feb 09 '16 at 16:07
  • @Sayse ah yes `mydata != myVar`. My mistake. – markwalker_ Feb 09 '16 at 16:14
  • @bakkal - thanks for the link, really interesting. I knew there was something deeper behind a simple warning :). I just started with Django and I thought string interpolation was a good practice but apparently if the data has to arrive to external scripts, then an API call will be the best choice. – valenz Feb 09 '16 at 16:32

0 Answers0