ChemseddineZ
ChemseddineZ

Reputation: 1828

pass data from Django view to react

I have a django view that returns a variable in order to be rendered in template

return render_to_response('index.html', {
    'courses': courses})

I'm using ReactJS to render the index.html file, but I'm not sure whether i have to point to index.html in my view or the ReactJS file.
If I have to point to index.html how can I use the courses variable with React ?

Update the variable courses that i'm passing is of type dictionnary

Upvotes: 3

Views: 7127

Answers (1)

keepAlive
keepAlive

Reputation: 6665

Templates processing is anterior to any sort of JavaScript interpretation. This means that you will have to, in some sense, emulate its hardcoding beetween the js tags.

First, know that the python dictionary is likely to be corrupted when received on the client side. To prevent this, you may want to send it as a json object. Which means that, in you script views.py, you will have to json.dumps your dictionary. As follows

from django.shortcuts import render
import json
#...
    #...
    return render(request,
                 'your_app/index.html',\
                  {'courses': json.dumps(courses)}\
                  )

Note that I use render instead of render_to_response, because render is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext

Also, note that you do have to point to your index.html, but the exact path depends on the strucutre of your project. Above, I assume you followed the recommended django project layout, i.e.

myproject/
    manage.py
    your_project/
        __init__.py
        urls.py
        wsgi.py
        settings/
            __init__.py
            base.py
            dev.py
            prod.py
    your_app/
        __init__.py
        models.py
        managers.py
        views.py
        urls.py
        templates/
            your_app/
                index.html
    [...]

Then, on the html side,

...
<script>
 var courses = {{courses|safe}}
// working with the variable courses
</script>
...

Now, you can do what you want with it, be it with ReactJS library.

Upvotes: 1

Related Questions