4

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)

4
  • Since it is in a javascript file, it no longer has context of {{goals}} . move this code to your template instead. Commented Aug 11, 2013 at 21:33
  • You still have in your javascript: alert({{goals}});. Remove the {{}} from the javascript: alert(goals); Commented Aug 12, 2013 at 5:03
  • Also, do you have a __str__ or __unicode__ method defined for your goals model? Once you define such a method, then [object Object] will be replaced by that method's output. Commented Aug 12, 2013 at 5:12
  • I had alert(goals) in, I just didnt edit the above js script but I did now to reflect everything. Commented Aug 12, 2013 at 5:24

1 Answer 1

5

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 }}')
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks alot! It outputted which is great, but unfortunately with "&quot" marks around each key and value in the json object (since I serialized the variable as JSON in my views.py.) Would you happen to know why this is or how to fix it?
By default, every variable that isn't an instance of Django's SafeString SafeUnicode or SafeBytes classes will be auto-escaped. You can use {% autoescape off %} and {% endautoescape %} to prevent a block from being auto-escaped, but for single variables you'll want to use the safe filter, that will just mark a single variable as being safe: {{ goals|safe }}.
I tried that and the alert returned [object HTMLUListElement]. tHen I tried accessing goals.pk since that is one of the keys in the JSON, but the alert returned undefined. So is the javascript variable "goals" a JSON object after setting it to "{{ goals|safe }}" in the script tag in the html file? Im confused as to why when I try accessing a field of the goals variable it returns undefined.
Maybe you need to loose the quotes around {{ goals|safe }}. Can you post whats in the source code of your html page?
@user1987920 Actually meant: what do you see when you go to 'View page source' in your browser, or what is the output of {{ goals|safe }}. Anyway, I updated my answer with what I think should work, though my JSON seems to be a bit rusty at the moment.

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.