Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass data from Django view to react

Tags:

reactjs

django

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

like image 476
ChemseddineZ Avatar asked Mar 31 '26 00:03

ChemseddineZ


1 Answers

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.

like image 189
keepAlive Avatar answered Apr 02 '26 14:04

keepAlive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!