user1987920
user1987920

Reputation: 165

Django variable isnt recognized by javascript

I serialized an object of mine using the built in method with django and then passed it into my template. When I put {{goals}} in the html, the data shows perfectly. However, when I try to access it through a js script, it doesnt work. Why is this? I alerted it and it keeps coming as undefined.

#Python Views
def characterscreen(request):
    goals = serializers.serialize("json", Goal.objects.filter(userprofile=userprof)) 
    #goals = Goal.objects.filter(userprofile=userprof).values()
    return render_to_response('levelup/characterscreen.html', {'goals': goals}, context_instance=RequestContext(request))

Python Model

class Goal(models.Model):
    title = models.CharField(max_length = 30)
    userprofile = models.ForeignKey(UserProfile)
    type = models.CharField(max_length = 5)

    def __unicode__(self):
        return str(self.title)

JS File

    $("body").onload =  load_goals();


function load_goals (){
     alert(goals);}

HTML

    <!DOCTYPE html>
    <html>
    <head>
        {% load staticfiles %}
        <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static 'levelup/style.css' %}" />
        {% block header %}{% endblock%}
    </head>
    <body>
        <div id="headercontainer">
            <div id="header">

            </div>
        </div>
        {% block content %}{% endblock %}   <script type="text/Javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>  <script type="text/Javascript" src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> 
<script type="text/javascript">goals = "{{ goals|safe }}"</script>
        <script type="text/Javascript" src="{% static 'levelup/script.js' %}"></script>
    </body>
    </html>

I tried removing the quotes and now the variable is just alerting a [object Object],[object Object] when I do alert(goals)

Upvotes: 4

Views: 1266

Answers (1)

knbk
knbk

Reputation: 53669

That's because external .js files aren't processed like html files are. This only works with inline scripts. So you should put this in your HTML file:

<script type="text/javascript">
    goals = "{{ goals }}"
</script>
<script type="text/javascript" src="script.js" />

Then you can use the goal variable in script.js.

EDIT:
JSON always uses double quotes, so you'll have to put single quotes around it. Additionally, althrough a JSON string actually represents a real Javascript object when used without quotes, it's best to parse the JSON before you use it. As you seem to be using jQUery, use:

goals = $.parseJSON('{{ goals|safe }}')

Upvotes: 5

Related Questions