A quick way to add React components to your Django templates.

Overview

Python tests PyPI version

Django-React-Templatetags

Django-React-Templatetags

This django library allows you to add React (16+) components into your django templates.

Features

  • Include react components using django templatetags
  • Unlimited amount of components in one view
  • Support custom models (that is from the beginning not json-serializable)
  • Server side rendering with Hypernova or Hastur

Installation

Install the library with pip:

$ pip install django_react_templatetags

Where to go from here?

You should first read Getting started, then go through these topics:

Tests

This library include tests, just run python runtests.py

You can also run separate test cases: python runtests.py tests.test_filters.ReactIncludeComponentTest

Coverage

Make sure you have Coverage.py installed, then run coverage run runtests.py to measure coverage. We are currently at 95%.

Contributing

Want to contribute? Awesome. Just send a pull request.

Security

If you believe you have found a security issue with any of our projects please email us at [email protected].

License

Django-React-Templatetags is released under the MIT License.

Comments
  • Uncaught ReferenceError: ReactDOM is not defined

    Uncaught ReferenceError: ReactDOM is not defined

    I got this error( (index):14 Uncaught ReferenceError: ReactDOM is not defined ) in console while run this code snippet. i am using django 1.11.2. As i am beginner in ReactJS. please help me out.

    opened by DaxitaRajput 9
  • ES modules import

    ES modules import

    I have been investigating the usage of es module imports for react components in the react template tags in order to not use a bundler in the front end tooling process. Here is where the idea came from: Building without bundling and I got a working example that I will post here in the next comment

    opened by AriaMoradi 8
  • Hypernova SSR Example Doesn't Work

    Hypernova SSR Example Doesn't Work

    I followed the Hypernova SSR example, but the webpages I receive are completely blank.

    Tried to run the example directly, the following error occurs on the hypernova server:

    Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
    

    Any idea why this could be?

    opened by baranyildirim 7
  • Recommended development environment

    Recommended development environment

    Not a bug or problem with the project.

    Is there a development environment that anyone would recommend for doing frontend development with django-react-templatetags?

    Specifically, how do you go about developing react components and debugging them with the Django and Hypernova SSR setup?

    Thanks

    question 
    opened by baranyildirim 6
  • Support for callbacks/literals

    Support for callbacks/literals

    The current approach resolves template variables to a type, or fails. You cannot pass a literal, because the template tag forcibly passes json to the component tag.

    This eliminates literally half of the "IO" functionality of React, by killing the "O" part. The only way React components can communicate with the outside world is by callback, and this behaviour is unsupported, because functions are not JSON-encodable.

    I've looked through the documentation but see only mention of feeding data in, no capability for getting data back out via callback.

    Is there something I'm missing, or is there no support for passing in callback functions so that React components can communicate back to the page they're hosted on?

    opened by isolationism 6
  • Guidance on inline React component?

    Guidance on inline React component?

    Thanks for this really great library.

    The example in the readme shows a "Menu" React component loaded into part of a larger template. But there isn't any guidance on creating this React component for specific use as an inline component in a Django app using django-react-templates.

    The example app that is mentioned seems to be a full SPA-like React app built using react-sass-starterkit...unsure how that example fits into the inline component approach.

    Do you have any guidance or suggestions for building something more like the "Menu" component? (e.g. create a separate Django app "components" in your project, setup webpack to compile from components/src/my_component.js to static, make sure not to include X, etc. etc.)

    Probably very obvious to most but for a React newbie like me it's hard to discover the easiest way to write an inline (not SPA) React component for use with Django + django-react-templates.

    For example, I'm not sure if using react-sass-starterkit is appropriate for an inline component like "Menu"...does it bake in extra js that django-react-template will itself provide? Any extra steps to properly integrate the result of a webpack build in react-sass-starterkit into the Django app?

    Thanks for any suggestions.

    opened by danielmcquillen 6
  • When is the next release?

    When is the next release?

    Hey there,

    I was wondering when the next release would be published to pypi? There is useful SSR code currently in the develop branch (added like a month ago) that I don't believe is in v5.4.0 build.

    Thank you!

    question 
    opened by mendozao 5
  • Issue with rendering React when using the browser back button

    Issue with rendering React when using the browser back button

    Hi there,

    Firstly thanks for this project! It has enabled me to start shifting to start adding React to my codebase incrementally which is amazing!

    Disclaimer: This issue could be down to the particular code base I am working on. It is using this library which looks to mess with the state of the back button (https://github.com/defunkt/jquery-pjax)

    This issue can be reproduced as follows:

    1. Go to a page which uses this library
    2. Then navigate to another page
    3. Then use the browser back button
    4. If at this point you inspect the elements the uuid in the data/javascript is different from the uuid in the HTML id of the div where the React should render.

    Screen recording: https://www.loom.com/share/5247e399ace045ee82d3744b009d6b1bx

    Workaround: just use the identifier argument in the react_render template tag.

    opened by nanorepublica 4
  • XSS vulnerability: no escaping of HTML tags in rendered props

    XSS vulnerability: no escaping of HTML tags in rendered props

    I couldn't find a non-public channel on which to communicate the security vulnerability. Here it goes:

    Severity

    High. The injected code could be executed on any page in which the malicious input is rendered and can affect any visitor, including site admins. This could allow attackers to hijack sessions, execute any Javascript on the browser of the visitor or even include their own HTML into the page.

    Problem

    Normally Django would take care of escaping HTML tags in templates when including model fields and other variables in the rendered template. But in this case, the React props are simply rendered as a JSON object in a script element.

    Since the JSON inside the React.createElement(...) is not properly escaped, a malicious user is able to inject any custom HTML/Javascript into the rendered templates.

    Simple example

    1. Create any model with fields that can be set by the user, for example: UserProfile(name: str, bio: str, ...)
    2. Let the user fill in the data as usual: could be Django form, React component, REST API, etc...
    3. Populate any React component using this library, passing any of those fields as a prop:
    {% load react %}
    <html>
        <head>...</head>
    
        <body>
                {% react_render component="UserProfileComponent" prop_name=user_profile.name %}
        </body>
    
        {% react_print %}
    </html>
    
    1. If a user sets the name to be </script><script>alert('Foo')</script>, it will be rendered in the template as follows:
    <html>
        <head>...</head>
    
        <body>
                <div id="UserProfileComponent_UUID"></div>
        </body>
    
        <script>
            ReactDOM.render(
                React.createElement(UserProfileComponent, {"name": "</script><script>alert('Foo')</script>"}),
                document.getElementById('UserProfileComponent_UUID')
            );
        </script>
    </html>
    
    1. The first </script> ends the script element in which the React render snippet is placed, and executes the malicious code.

    Proposed solution

    I think that one of the following would prevent this vulnerability:

    1. Preferred: make use of Django's json_script to handle escaping of malicious code and render the JSON object into the template. https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#json-script
    <html>
        <head>...</head>
    
        <body>
                <div id="UserProfileComponent_UUID"></div>
        </body>
    
        <script id="UserProfileComponent_props_UUID" type="application/json">{"name": "\\u003C/script\\u003E..."}</script>
    
        <script>
            ReactDOM.render(
                React.createElement(UserProfileComponent, JSON.parse(document.getElementById('UserProfileComponent_props_UUID').textContent)),
                document.getElementById('UserProfileComponent_UUID')
            );
        </script>
    </html>
    
    1. Base64 encode the stringified props JSON on render, and decode within the <script>...</script> element on the browser. For example:
    <html>
        <head>...</head>
    
        <body>
                <div id="UserProfileComponent_UUID"></div>
        </body>
    
        <script>
            ReactDOM.render(
                React.createElement(UserProfileComponent, JSON.parse(atob("eyJuYW1lIjoiPC9zY3JpcHQ+PHNjcmlwdD5hbGVydCgnRm9vJyk8L3NjcmlwdD4ifQ=="))),
                document.getElementById('UserProfileComponent_UUID')
            );
        </script>
    </html>
    
    1. Recursively escape the strings in the rendered JSON before rendering the props into the template.

    Useful links

    1. https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#json-script
    2. https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/
    opened by anthonynsimon 4
  • Don't print script tag if no react components

    Don't print script tag if no react components

    I have found that in some browsers, a blank script tag is a syntax error. No need to output an empty script tag if there is no react component to render.

    opened by jproffitt 4
  • Remove context_processor required to run library.

    Remove context_processor required to run library.

    The context processor was providing an initial empty list of rendered components in order to include them in the {% react_print %} output. While render would anyway fallback to an empty list in case of no variable in current context, the library would throw a KeyError when running the {% react_print %}.

    The rationale behind this change is that the CP itself doesn't provide any significant value there and the list in the context can be dynamically created when rendering the first react component on the page.

    On the contrary, when using render_to_string which has no request context, the library would throw the KeyError mentioned before.

    opened by niespodd 4
  • Some tests misusing assertTrue for comparisons

    Some tests misusing assertTrue for comparisons

    assertTrue is not for comparing arguments, should use assertEqual for that.

    The developer's intent of the test was to compare argument 1 with argument 2, which is not happening. Really what is happening is the test is passing because first argument is truthy. The correct method to use is assertEqual. more details

    https://github.com/Frojd/django-react-templatetags/blob/cb781d6eaa7b19b49840543ee22f7bd243d97dec/django_react_templatetags/tests/test_ssr_hypernova_service.py#L205

    I found this issue automatically, see other issues here

    bug 
    opened by code-review-doctor 0
  • Who is using this library?

    Who is using this library?

    Not really an issue, just wanted to start a thread for projects and companies using this library.

    I found it super helpful for my own projects. And just want to help promote it.

    I can start:

    • Panelbear: Privacy focused analytics service.

    I actually mention the library in a blog post I just published describing the tech stack in case anyone is interested: https://panelbear.com/blog/tech-stack/

    Thanks a lot for building this, it has saved me a lot of work.

    question 
    opened by anthonynsimon 1
  • Hypernova SSR not propagating errors correctly

    Hypernova SSR not propagating errors correctly

    This problem might be with hypernova-python plugin. The error gets stuck inside "results" and not at the base dictionary. Eventhough I get the response that everything is OK, the SSR failed.

    This is a snippet of the JSON returned from https://github.com/ornj/hypernova-python/blob/master/hypernova/init.py#L79

    {
      "success": True,
      "error": "None",
      "results": {
        "Components.App": {
          "name": "Components.App",
          "html": "None",
          "meta": {
    
          },
          "duration": 310.156114,
          "statusCode": 500,
          "success": False,
          "error": {
            "name
            ":"
            ReferenceError ",
            "message": "window is not defined",
            "stack": [
              "ReferenceError: window is not defined",
              "at useMediaQuery (/mnt/persist/www/signalisten/shared/ssr/frontend/ssr_frontend/utils/useMediaQ
              uery.js: 37: 25)
            ",
            ]
    }
    
    
    bug 
    opened by rinti 1
Owner
Fröjd Agency
We create communication, experiences and services that activate and engage to make you successful in a digital world!
Fröjd Agency
Create a netflix-like service using Django, React.js, & More.

Create a netflix-like service using Django. Learn advanced Django techniques to achieve amazing results like never before.

Coding For Entrepreneurs 67 Dec 8, 2022
Django And React Notes App

Django & React Notes App Cloning the repository --> Clone the repository using the command below : git clone https://github.com/divanov11/Django-React

Dennis Ivy 136 Dec 27, 2022
Django React Flight Rezervation

Django Intro & Installation python -m venv venv source ./venv/Scripts/activate pip install Django pip install djangorestframework pip install python-d

HILMI SARIOGLU 2 May 26, 2022
Django React - Purity Dashboard (Open-Source) | AppSeed

Django React Purity Dashboard Start your Development with an Innovative Admin Template for Chakra UI and React. Purity UI Dashboard is built with over

App Generator 19 Sep 19, 2022
This is a simple Todo web application built Django (back-end) and React JS (front-end)

Django REST Todo app This is a simple Todo web application built with Django (back-end) and React JS (front-end). The project enables you to systemati

Maxim Mukhin 5 May 6, 2022
Automatic class scheduler for Texas A&M written with Python+Django and React+Typescript

Rev Registration Description Rev Registration is an automatic class scheduler for Texas A&M, aimed at easing the process of course registration by gen

Aggie Coding Club 21 Nov 15, 2022
Django React Project Setup

Django-React-Project-Setup INSTALLATION: python -m pip install drps USAGE: in your cmd: python -m drps Starting fullstack project with Django and Reac

Ghazi Zabalawi 7 Feb 6, 2022
React.JS - Django Application Template

OTS React.JS - DJango Web Application (UNTESTED) This repository servers as a template for creating React.JS - Django Web Applications. Note that the

Darryl See Wei Shen 5 Aug 19, 2022
Django Rest Framework + React application.

Django Rest Framework + React application.

null 2 Dec 19, 2022
This is a template tag project for django to calculate in templates , enjoy it

Calculator-Template-Django this is a template tag project for django to calculate in templates , enjoy it Get Started : 1 - Download Source Code 2 - M

null 1 Feb 1, 2022
Add Chart.js visualizations to your Django admin using a mixin class

django-admincharts Add Chart.js visualizations to your Django admin using a mixin class. Example from django.contrib import admin from .models import

Dropseed 22 Nov 22, 2022
Quick example of a todo list application using Django and HTMX

django-htmx-todo-list Quick example of a todo list application using Django and HTMX Background Modified & expanded from https://github.com/jaredlockh

Jack Linke 54 Dec 10, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
Add infinite scroll to any django app.

django-infinite-scroll Add infinite scroll to any django app. Features - Allows to add infinite scroll to any page.

Gustavo Teixeira 1 Dec 26, 2021
An app that allows you to add recipes from the dashboard made using DJango, JQuery, JScript and HTMl.

An app that allows you to add recipes from the dashboard. Then visitors filter based on different categories also each ingredient has a unique page with their related recipes.

Pablo Sagredo 1 Jan 31, 2022
Django API that scrapes and provides the last news of the city of Carlos Casares by semantic way (RDF format).

"Casares News" API Api that scrapes and provides the last news of the city of Carlos Casares by semantic way (RDF format). Usage Consume the articles

Andrés Milla 6 May 12, 2022
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Jan 7, 2023
A prettier way to see Django requests while developing

A prettier way to see Django requests while developing

Adam Hill 35 Dec 2, 2022
Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.

django-widget-tweaks Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is su

Jazzband 1.8k Jan 2, 2023