├── develop ├── develop │ ├── __init__.py │ ├── wsgi.py │ ├── urls.py │ └── settings.py ├── manage.py └── templates │ └── base.html ├── src └── reacttools │ ├── __init__.py │ ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ └── collectreact.py │ ├── migrations │ ├── __init__.py │ ├── 0004_auto_20190612_1923.py │ ├── 0003_reactappsettings_build_path.py │ ├── 0005_reactappsettings_build_cmd.py │ ├── 0007_auto_20190612_2059.py │ ├── 0011_reactappsettings_react_root.py │ ├── 0008_reactappsettings_static_path_prefix.py │ ├── 0002_auto_20190612_1911.py │ ├── 0010_auto_20190612_2123.py │ ├── 0012_auto_20210930_1120.py │ ├── 0006_auto_20190612_2054.py │ ├── 0001_initial.py │ └── 0009_auto_20190612_2113.py │ ├── tests.py │ ├── apps.py │ ├── urls.py │ ├── admin.py │ ├── templates │ └── reacttools │ │ ├── react_app_view.html │ │ └── index.html │ ├── models.py │ └── views.py ├── react-test-app ├── public │ ├── favicon.ico │ ├── manifest.json │ └── index.html ├── src │ ├── App.test.js │ ├── index.css │ ├── index.js │ ├── App.css │ ├── App.js │ ├── logo.svg │ └── serviceWorker.js ├── package.json └── README.md ├── tox.ini ├── requirements.txt ├── .bumpversion.cfg ├── .github ├── FUNDING.yml └── workflows │ ├── python-test.yml │ └── python-publish.yml ├── .travis.yml ├── README.md ├── pyproject.toml ├── LICENSE ├── .gitignore └── docs └── index.md /develop/develop/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/reacttools/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/reacttools/management/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/reacttools/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/reacttools/management/commands/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/reacttools/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /react-test-app/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/renderbox/django-react-tools/HEAD/react-test-app/public/favicon.ico -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 119 3 | exclude = .git,.tox,docs,venv,bin,lib,deps,build,*.egg 4 | ignore = E501,E402,W503,E731,E266 5 | -------------------------------------------------------------------------------- /src/reacttools/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ReacttoolsConfig(AppConfig): 5 | name = "reacttools" 6 | verbose_name = "React Tools" 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asgiref==3.8.1 2 | certifi==2024.12.14 3 | charset-normalizer==3.4.1 4 | Django==5.1.4 5 | idna==3.10 6 | requests==2.32.3 7 | sqlparse==0.5.3 8 | urllib3==2.3.0 9 | -------------------------------------------------------------------------------- /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.4.7 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:pyproject.toml] 7 | search = version = "{current_version}" 8 | replace = version = "{new_version}" 9 | -------------------------------------------------------------------------------- /src/reacttools/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path, re_path 2 | from reacttools import views 3 | from django.conf import settings 4 | 5 | urlpatterns = [ 6 | re_path("proxy/(\w.+)$", views.proxy, name="reacttools-proxy"), 7 | ] 8 | -------------------------------------------------------------------------------- /react-test-app/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /react-test-app/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/reacttools/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from reacttools.models import ReactAppSettings 4 | 5 | ############### 6 | # MODEL ADMINS 7 | ############### 8 | 9 | 10 | class ReactAppSettingsAdmin(admin.ModelAdmin): 11 | readonly_fields = ("slug",) 12 | 13 | 14 | ############### 15 | # REGISTRATION 16 | ############### 17 | 18 | admin.site.register(ReactAppSettings, ReactAppSettingsAdmin) 19 | -------------------------------------------------------------------------------- /react-test-app/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /develop/develop/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for develop project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "develop.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0004_auto_20190612_1923.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 19:23 2 | 3 | from django.db import migrations 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0003_reactappsettings_build_path"), 10 | ] 11 | 12 | operations = [ 13 | migrations.RenameField( 14 | model_name="reactappsettings", 15 | old_name="build_path", 16 | new_name="project_dir", 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /react-test-app/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0003_reactappsettings_build_path.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 19:22 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0002_auto_20190612_1911"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name="reactappsettings", 15 | name="build_path", 16 | field=models.CharField(blank=True, max_length=128), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0005_reactappsettings_build_cmd.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 20:46 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0004_auto_20190612_1923"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name="reactappsettings", 15 | name="build_cmd", 16 | field=models.CharField(blank=True, max_length=128), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /develop/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "develop.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /react-test-app/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 40vmin; 8 | pointer-events: none; 9 | } 10 | 11 | .App-header { 12 | background-color: #282c34; 13 | min-height: 100vh; 14 | display: flex; 15 | flex-direction: column; 16 | align-items: center; 17 | justify-content: center; 18 | font-size: calc(10px + 2vmin); 19 | color: white; 20 | } 21 | 22 | .App-link { 23 | color: #61dafb; 24 | } 25 | 26 | @keyframes App-logo-spin { 27 | from { 28 | transform: rotate(0deg); 29 | } 30 | to { 31 | transform: rotate(360deg); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0007_auto_20190612_2059.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 20:59 2 | 3 | from django.db import migrations 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0006_auto_20190612_2054"), 10 | ] 11 | 12 | operations = [ 13 | migrations.RenameField( 14 | model_name="reactappsettings", 15 | old_name="css", 16 | new_name="css_data", 17 | ), 18 | migrations.RenameField( 19 | model_name="reactappsettings", 20 | old_name="js", 21 | new_name="js_data", 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /react-test-app/src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import logo from './logo.svg'; 3 | import './App.css'; 4 | 5 | function App() { 6 | return ( 7 |
8 |
9 | logo 10 |

11 | Edit src/App.js and save to reload. 12 |

13 | 19 | Learn React 20 | 21 |
22 |
23 | ); 24 | } 25 | 26 | export default App; 27 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0011_reactappsettings_react_root.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.7 on 2019-11-20 20:24 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0010_auto_20190612_2123"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name="reactappsettings", 15 | name="react_root", 16 | field=models.CharField( 17 | blank=True, 18 | default="root", 19 | help_text="Defaults the DIV id to 'root' for attaching the React App to.", 20 | max_length=64, 21 | ), 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: realrenderbox 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0008_reactappsettings_static_path_prefix.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 21:06 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0007_auto_20190612_2059"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name="reactappsettings", 15 | name="static_path_prefix", 16 | field=models.CharField( 17 | blank=True, 18 | help_text="Tells collectreact wether or not to insert an extra directory into the static file path (js//main.chunk.js)", 19 | max_length=128, 20 | ), 21 | ), 22 | ] 23 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0002_auto_20190612_1911.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 19:11 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0001_initial"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterField( 14 | model_name="reactappsettings", 15 | name="css", 16 | field=models.TextField(blank=True), 17 | ), 18 | migrations.AlterField( 19 | model_name="reactappsettings", 20 | name="js", 21 | field=models.TextField(blank=True), 22 | ), 23 | migrations.AlterField( 24 | model_name="reactappsettings", 25 | name="manifest", 26 | field=models.CharField(blank=True, max_length=128), 27 | ), 28 | ] 29 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - '3.7' 4 | install: 5 | - pip install -e . 6 | - cd develop 7 | - python manage.py migrate 8 | script: 9 | - python manage.py test reacttools 10 | - cd .. 11 | deploy: 12 | provider: pypi 13 | user: __token__ 14 | password: 15 | secure: hnZok5fFSYQs1n5Q3Fz5QllGlqUf+DThhKsVe0mMVxmhio4416g4QBK54Ac5wovMVjGbqOZG5bwXQvJeYnqGUAbS2V1CwhVc5WE8MZeEXvat+5kygXWpaIntU7jd8zKj5LkTzXoQfvMl1z1GMTi7ru63J65ZhNOykhO9V/lFZy+dUM6l7n6ne8smjDSf/SexQuM8XvzuI348i7GexvxhaZKS0lptt+DaSM4IyA6xb/fEZrWyHRHuBWY9ZCvOnjcSzaoA1AiifqcTa9kZxrmI3mXPzCtGhBn1ng0xRfC455BfsHN/N6vFUlfO7za6A/YfFwXagtoePLvtzxM+GPY7EuCKDmxu5AX6c3J01Axukbau1BxMQAg3CLrOF706DSzQQV0N0W4hbcEcPcDIYcJcwi1u1B81tKqb1nFe5cvHfhSsNDk8lXavrhkC38JzVZ0Pj7MXqC3DURHW2ISrtV9XO/PkdjuQ7sl8wzZo8a81NTLgomgUJ4NAtG19WLXf/RiVWF2UVCwcpUwKn69wBW9W3FSpLYsFMV7eyK2wtlpw0AmEBncMRbMW6AkDoVjTivYHGAUyjVeyHbsdLeVNA+3Zb5z3J7u2Oj0kCPPcV+1MI4i6mdmoZKvLZAVeEFaImWA36X+rtbv2yGMH3dVtSH/NBJFMOjYPQqZ4Wr1yiImD5N0= 16 | -------------------------------------------------------------------------------- /react-test-app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-test-app", 3 | "version": "0.2.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.14.1", 7 | "@testing-library/react": "^13.0.0", 8 | "@testing-library/user-event": "^13.2.1", 9 | "react": "^18.2.0", 10 | "react-dom": "^18.2.0", 11 | "react-scripts": "5.0.1", 12 | "web-vitals": "^2.1.0" 13 | }, 14 | "scripts": { 15 | "start": "react-scripts start", 16 | "build": "react-scripts build", 17 | "test": "react-scripts test", 18 | "eject": "react-scripts eject" 19 | }, 20 | "eslintConfig": { 21 | "extends": [ 22 | "react-app", 23 | "react-app/jest" 24 | ] 25 | }, 26 | "browserslist": { 27 | "production": [ 28 | ">0.2%", 29 | "not dead", 30 | "not op_mini all" 31 | ], 32 | "development": [ 33 | "last 1 chrome version", 34 | "last 1 firefox version", 35 | "last 1 safari version" 36 | ] 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0010_auto_20190612_2123.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 21:23 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0009_auto_20190612_2113"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterField( 14 | model_name="reactappsettings", 15 | name="build_dir", 16 | field=models.CharField( 17 | blank=True, 18 | help_text="Default assumes that the build path is at the root of the project (i.e. project_dir/build/).", 19 | max_length=128, 20 | ), 21 | ), 22 | migrations.AlterField( 23 | model_name="reactappsettings", 24 | name="project_dir", 25 | field=models.CharField( 26 | help_text="This can be a relative path and will be expanded on use.", 27 | max_length=128, 28 | ), 29 | ), 30 | ] 31 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0012_auto_20210930_1120.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.0.7 on 2021-09-30 11:20 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0011_reactappsettings_react_root"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterField( 14 | model_name="reactappsettings", 15 | name="build_cmd", 16 | field=models.CharField( 17 | blank=True, 18 | help_text="Defaults to REACT_BUILD_COMMAND value in settings.py.", 19 | max_length=128, 20 | ), 21 | ), 22 | migrations.AlterField( 23 | model_name="reactappsettings", 24 | name="manifest", 25 | field=models.CharField( 26 | blank=True, 27 | help_text="Defaults to REACT_MANIFEST_FILE value in settings.py.", 28 | max_length=128, 29 | ), 30 | ), 31 | ] 32 | -------------------------------------------------------------------------------- /develop/develop/urls.py: -------------------------------------------------------------------------------- 1 | """develop URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | 17 | from django.contrib import admin 18 | from django.urls import include, path 19 | from reacttools.views import IndexView, ReactAppView 20 | 21 | urlpatterns = [ 22 | path("admin/", admin.site.urls), 23 | path("dev/", IndexView.as_view()), 24 | path("reacttools/", include("reacttools.urls")), 25 | path("", ReactAppView.as_view()), 26 | ] 27 | -------------------------------------------------------------------------------- /.github/workflows/python-test.yml: -------------------------------------------------------------------------------- 1 | name: Python Tests 2 | 3 | on: 4 | pull_request: 5 | branches: ["master", "develop"] 6 | 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | max-parallel: 4 12 | matrix: 13 | python-version: ["3.11", "3.12", "3.13"] 14 | 15 | steps: 16 | - name: Checkout repo 17 | uses: actions/checkout@v4 18 | 19 | - name: Set up Python ${{ matrix.python-version }} 20 | uses: actions/setup-python@v5 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | 24 | - name: Install Dependencies 25 | run: | 26 | python -m pip install -U pip 27 | python -m pip install -e ".[test]" 28 | 29 | - name: Check code with black 30 | run: | 31 | black . 32 | 33 | - name: Test with Django Test 34 | run: | 35 | cd develop 36 | python manage.py makemigrations --check --dry-run 37 | python manage.py test reacttools 38 | env: 39 | DJANGO_DEBUG: 1 40 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0006_auto_20190612_2054.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 20:54 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0005_reactappsettings_build_cmd"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterField( 14 | model_name="reactappsettings", 15 | name="build_cmd", 16 | field=models.CharField( 17 | blank=True, 18 | help_text="Defaults to 'npm run build' from the REACT_BUILD_COMMAND value in settings.py.", 19 | max_length=128, 20 | ), 21 | ), 22 | migrations.AlterField( 23 | model_name="reactappsettings", 24 | name="manifest", 25 | field=models.CharField( 26 | blank=True, 27 | help_text="Defaults to 'asset-manifest.json' from the REACT_MANIFEST_FILE value in settings.py.", 28 | max_length=128, 29 | ), 30 | ), 31 | ] 32 | -------------------------------------------------------------------------------- /src/reacttools/templates/reacttools/react_app_view.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load static %} 3 | {% load i18n %} 4 | 5 | {% block head_title %}React Application{% endblock %} 6 | 7 | {% block extra_css %} 8 | 9 | {% for manifest in react_manifest %} 10 | 11 | {% endfor %} 12 | 13 | {% for css in react_styles %} 14 | 15 | {% endfor %} 16 | 17 | 18 | {% endblock %} 19 | 20 | {% block extra_head_js %}{% endblock %} 21 | 22 | {% block react %} 23 | 24 | {% for root in react_root %} 25 |
26 | {% endfor %} 27 | {% endblock %} 28 | 29 | {% block extra_js %} 30 | 31 | 32 | 33 | 34 | {% for js in react_scripts %} 35 | 36 | {% endfor %} 37 | 38 | {% endblock %} 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-react-tools 2 | 3 | Django Tools for helping integrate ReactJS into your Django project. 4 | 5 | The current iteration of this tool adds a simple management command to your Django project that will build, copy to a Django static directory and rename accordingly. 6 | 7 | If you wish to contribute, please Fork the repo and then make a Pull Request. We're always open for people who want to help make this a better package. 8 | 9 | To get started just pip install the package: 10 | 11 | ```bash 12 | pip install django-react-tools 13 | ``` 14 | 15 | To read more about how to configure the project, go to the docs [here](https://github.com/renderbox/django-react-tools/blob/master/docs/index.md). 16 | 17 | We are in the process of making some updates to the package. If you come accross any issues please report them. 18 | 19 | [![Python Tests](https://github.com/renderbox/django-react-tools/actions/workflows/python-test.yml/badge.svg)](https://github.com/renderbox/django-react-tools/actions/workflows/python-test.yml) 20 | 21 | [![Upload Python Package](https://github.com/renderbox/django-react-tools/actions/workflows/python-publish.yml/badge.svg)](https://github.com/renderbox/django-react-tools/actions/workflows/python-publish.yml) 22 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-11 01:16 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name="ReactAppSettings", 15 | fields=[ 16 | ( 17 | "id", 18 | models.AutoField( 19 | auto_created=True, 20 | primary_key=True, 21 | serialize=False, 22 | verbose_name="ID", 23 | ), 24 | ), 25 | ( 26 | "name", 27 | models.CharField( 28 | help_text="The React App name you want to use.", 29 | max_length=32, 30 | verbose_name="React App Name", 31 | ), 32 | ), 33 | ("slug", models.SlugField(max_length=32)), 34 | ("js", models.TextField()), 35 | ("css", models.TextField()), 36 | ("manifest", models.CharField(max_length=128)), 37 | ("enabled", models.BooleanField(default=False, verbose_name="Enabled")), 38 | ], 39 | ), 40 | ] 41 | -------------------------------------------------------------------------------- /develop/templates/base.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {% block title %}{% endblock %} 15 | {% block extra_css %}{% endblock %} 16 | {% block extra_head_js %}{% endblock %} 17 | 18 | 19 | 20 |
21 | 22 | 25 |
26 | 27 | {% block content %} 28 | {% block react %} 29 | {% endblock %} 30 | {% endblock %} 31 | 32 | 33 | {% block extra_js %} 34 | {% endblock %} 35 | 36 | 37 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0.0", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [tool.distutils.bdist_wheel] 6 | universal = true 7 | 8 | [project] 9 | name = "django-react-tools" 10 | version = "0.4.7" 11 | 12 | authors = [ 13 | { name="Grant Viklund", email="renderbox@gmail.com" }, 14 | { name="Devon Jackson"} 15 | ] 16 | description = "Tools for helping integrate ReactJS into a Django project." 17 | readme = "README.md" 18 | requires-python = ">=3.11" 19 | classifiers = [ 20 | "Development Status :: 4 - Beta", 21 | "Intended Audience :: Developers", 22 | "Programming Language :: Python :: 3 :: Only", 23 | "Programming Language :: Python :: 3.11", 24 | "Programming Language :: Python :: 3.12", 25 | "Programming Language :: Python :: 3.13", 26 | ] 27 | keywords = ["django", "app"] 28 | dependencies = [ 29 | "Django>=4.1,<5.2", 30 | "requests", 31 | ] 32 | 33 | [project.optional-dependencies] 34 | dev = [ 35 | "black", 36 | "flake8", 37 | "flake8-black", 38 | "mypy", 39 | "bandit", 40 | "isort", 41 | "toml", 42 | ] 43 | docs= [ 44 | "coverage", 45 | ] 46 | test = [ 47 | "black", 48 | "flake8", 49 | "flake8-black", 50 | "mypy", 51 | "bandit", 52 | "isort", 53 | "coverage", 54 | ] 55 | 56 | [project.urls] 57 | "Homepage" = "https://github.com/renderbox/django-react-tools" 58 | "Bug Tracker" = "https://github.com/renderbox/django-react-tools/issues" 59 | -------------------------------------------------------------------------------- /src/reacttools/migrations/0009_auto_20190612_2113.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.9 on 2019-06-12 21:13 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ("reacttools", "0008_reactappsettings_static_path_prefix"), 10 | ] 11 | 12 | operations = [ 13 | migrations.AddField( 14 | model_name="reactappsettings", 15 | name="build_dir", 16 | field=models.CharField( 17 | blank=True, 18 | help_text="Note: makes the assumption that the build path is at the root of the project (i.e. project_dir/build/).", 19 | max_length=128, 20 | ), 21 | ), 22 | migrations.AlterField( 23 | model_name="reactappsettings", 24 | name="project_dir", 25 | field=models.CharField( 26 | blank=True, 27 | help_text="Note: makes the assumption that the build path is at the root of the project (i.e. project_dir/build/).", 28 | max_length=128, 29 | ), 30 | ), 31 | migrations.AlterField( 32 | model_name="reactappsettings", 33 | name="static_path_prefix", 34 | field=models.CharField( 35 | blank=True, 36 | help_text="Tells collectreact wether or not to insert an extra directory into the static file path (i.e. js/prefix/main.chunk.js). Blank is no prefix.", 37 | max_length=128, 38 | ), 39 | ), 40 | ] 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2019, Grant Viklund 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | * Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /react-test-app/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 22 | React App 23 | 24 | 25 | 26 |
27 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/reacttools/templates/reacttools/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | {% if react_manifest %} 13 | 14 | {% endif %} 15 | 16 | {% for css in react_styles %} 17 | 18 | {% endfor %} 19 | 28 | React App 29 | 30 | 31 | 34 |
35 | 45 | {% for js in react_scripts %} 46 | 47 | {% endfor %} 48 | 49 | 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | .vscode 107 | 108 | 109 | 110 | 111 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 112 | 113 | # dependencies 114 | /react-test-app/node_modules 115 | /react-test-app/.pnp 116 | .pnp.js 117 | 118 | # testing 119 | /react-test-app/coverage 120 | 121 | # production 122 | /react-test-app/build 123 | 124 | # misc 125 | .DS_Store 126 | .env.local 127 | .env.development.local 128 | .env.test.local 129 | .env.production.local 130 | 131 | npm-debug.log* 132 | yarn-debug.log* 133 | yarn-error.log* 134 | build_notes.txt 135 | -------------------------------------------------------------------------------- /react-test-app/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/reacttools/models.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.db import models 3 | from django.utils.translation import gettext_lazy as _ 4 | from django.utils.text import slugify 5 | from django.templatetags.static import static 6 | 7 | REACT_MANIFEST_FILE = getattr(settings, "REACT_MANIFEST_FILE", "asset-manifest.json") 8 | REACT_BUILD_COMMAND = getattr(settings, "REACT_BUILD_COMMAND", "npm run build") 9 | 10 | 11 | class ReactAppSettings(models.Model): 12 | 13 | name = models.CharField( 14 | _("React App Name"), 15 | max_length=32, 16 | help_text="The React App name you want to use.", 17 | ) 18 | slug = models.SlugField(max_length=32) 19 | js_data = models.TextField(blank=True) 20 | css_data = models.TextField(blank=True) 21 | static_path_prefix = models.CharField( 22 | max_length=128, 23 | blank=True, 24 | help_text="Tells collectreact wether or not to insert an extra directory into the static file path (i.e. js/prefix/main.chunk.js). Blank is no prefix.", 25 | ) 26 | manifest = models.CharField( 27 | max_length=128, 28 | blank=True, 29 | help_text="Defaults to REACT_MANIFEST_FILE value in settings.py.", 30 | ) 31 | build_cmd = models.CharField( 32 | max_length=128, 33 | blank=True, 34 | help_text="Defaults to REACT_BUILD_COMMAND value in settings.py.", 35 | ) 36 | project_dir = models.CharField( 37 | max_length=128, 38 | help_text="This can be a relative path and will be expanded on use.", 39 | ) 40 | build_dir = models.CharField( 41 | max_length=128, 42 | blank=True, 43 | help_text="Default assumes that the build path is at the root of the project (i.e. project_dir/build/).", 44 | ) 45 | react_root = models.CharField( 46 | max_length=64, 47 | blank=True, 48 | default="root", 49 | help_text="Defaults the DIV id to 'root' for attaching the React App to.", 50 | ) 51 | enabled = models.BooleanField( 52 | _("Enabled"), default=False 53 | ) # Is this location available? 54 | 55 | def __str__(self): 56 | return self.name 57 | 58 | def save(self, *args, **kwargs): 59 | 60 | if not self.manifest: 61 | self.manifest = REACT_MANIFEST_FILE 62 | 63 | self.slug = slugify(self.name) 64 | 65 | super().save(*args, **kwargs) 66 | 67 | @property 68 | def js(self): 69 | return str(self.js_data).split() 70 | 71 | @property 72 | def css(self): 73 | return str(self.css_data).split() 74 | 75 | def js_paths(self): 76 | if self.static_path_prefix: 77 | return [static("js/%s/%s" % (self.static_path_prefix, s)) for s in self.js] 78 | return [static("js/%s" % (s)) for s in self.js] 79 | 80 | def css_paths(self): 81 | if self.static_path_prefix: 82 | return [ 83 | static("css/%s/%s" % (self.static_path_prefix, s)) for s in self.css 84 | ] 85 | return [static("css/%s" % (s)) for s in self.css] 86 | -------------------------------------------------------------------------------- /react-test-app/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `npm run build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /develop/develop/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for develop project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = "g!4l3do!i8h3p_c^u#-)8p1nm$5k57m4i14)x9l^ybxmu1+#_8" 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | REACT_DEBUG = os.getenv("REACT_DEBUG", DEBUG) 29 | 30 | ALLOWED_HOSTS = [] 31 | 32 | # https://github.com/ottoyiu/django-cors-headers/#setup 33 | CORS_ORIGIN_ALLOW_ALL = True 34 | 35 | # Application definition 36 | 37 | INSTALLED_APPS = [ 38 | "django.contrib.admin", 39 | "django.contrib.auth", 40 | "django.contrib.contenttypes", 41 | "django.contrib.sessions", 42 | "django.contrib.messages", 43 | "django.contrib.staticfiles", 44 | "django.contrib.sites", 45 | "reacttools", 46 | ] 47 | 48 | MIDDLEWARE = [ 49 | "django.middleware.security.SecurityMiddleware", 50 | "django.contrib.sessions.middleware.SessionMiddleware", 51 | "corsheaders.middleware.CorsMiddleware", 52 | "django.middleware.common.CommonMiddleware", 53 | "django.middleware.csrf.CsrfViewMiddleware", 54 | "django.contrib.auth.middleware.AuthenticationMiddleware", 55 | "django.contrib.messages.middleware.MessageMiddleware", 56 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 57 | ] 58 | 59 | ROOT_URLCONF = "develop.urls" 60 | 61 | TEMPLATES = [ 62 | { 63 | "BACKEND": "django.template.backends.django.DjangoTemplates", 64 | "DIRS": [os.path.join(BASE_DIR, "templates")], 65 | "APP_DIRS": True, 66 | "OPTIONS": { 67 | "context_processors": [ 68 | "django.template.context_processors.debug", 69 | "django.template.context_processors.request", 70 | "django.contrib.auth.context_processors.auth", 71 | "django.contrib.messages.context_processors.messages", 72 | ], 73 | }, 74 | }, 75 | ] 76 | 77 | WSGI_APPLICATION = "develop.wsgi.application" 78 | 79 | DEFAULT_AUTO_FIELD = "django.db.models.AutoField" 80 | 81 | DATABASES = { 82 | "default": { 83 | "ENGINE": "django.db.backends.sqlite3", 84 | "NAME": "testdb", 85 | } 86 | } 87 | 88 | 89 | # Password validation 90 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 91 | 92 | AUTH_PASSWORD_VALIDATORS = [ 93 | { 94 | "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", 95 | }, 96 | { 97 | "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", 98 | }, 99 | { 100 | "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", 101 | }, 102 | { 103 | "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", 104 | }, 105 | ] 106 | 107 | 108 | # Internationalization 109 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 110 | 111 | LANGUAGE_CODE = "en-us" 112 | 113 | TIME_ZONE = "UTC" 114 | 115 | USE_I18N = True 116 | 117 | USE_L10N = True 118 | 119 | USE_TZ = True 120 | 121 | 122 | # Static files (CSS, JavaScript, Images) 123 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 124 | 125 | STATIC_URL = "/static/" 126 | 127 | STATIC_ROOT = os.path.join(BASE_DIR, "static") 128 | 129 | 130 | REACT_PROJECT_DIRECTORY = os.path.join(BASE_DIR, "../react-test-app") 131 | REACT_BUILD_COMMAND = "npm run build" 132 | REACT_DJANGO_DEST = os.path.join(BASE_DIR, "static_react") 133 | 134 | REACT_DEV_SERVER = "http://localhost:3000/" 135 | REACT_DEV_MODE = True 136 | 137 | SITE_ID = 1 138 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflows will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | push: 8 | branches: [master] 9 | 10 | jobs: 11 | bump-and-build: 12 | name: Bump and Build the package version 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout code 16 | uses: actions/checkout@v4 17 | with: 18 | persist-credentials: false 19 | 20 | - name: Set up Python 21 | uses: actions/setup-python@v5 22 | with: 23 | python-version: "3.10" 24 | 25 | - name: current_version 26 | run: echo "current_version=$(grep 'version = ' pyproject.toml | cut -d '=' -f2 | tr -d ' "')" >> $GITHUB_ENV 27 | 28 | - name: Install bump2version 29 | run: pip install bump2version 30 | 31 | - name: Bump version and commit changes 32 | run: | 33 | git config --global user.name 'github-actions[bot]' 34 | git config --global user.email 'github-actions[bot]@users.noreply.github.com' 35 | bump2version patch 36 | env: 37 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 38 | 39 | - name: new_version 40 | run: echo "new_version=$(grep 'version = ' pyproject.toml | cut -d '=' -f2 | tr -d ' "')" >> $GITHUB_ENV 41 | 42 | - name: Commit and Push Changes 43 | run: | 44 | git config user.email "github-actions[bot]@users.noreply.github.com" 45 | git config user.name "github-actions[bot]" 46 | git commit -am "Bump version [skip ci]" || echo "No changes to commit" 47 | git push https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git 48 | git push https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git --tags 49 | 50 | - name: Install Dependencies 51 | run: | 52 | python -m pip install -U pip 53 | python -m pip install build --user 54 | 55 | - name: Build a binary wheel and a source tarball 56 | run: python -m build 57 | 58 | - name: Store the distribution packages 59 | uses: actions/upload-artifact@v4 60 | with: 61 | name: python-package-distributions 62 | path: dist/ 63 | 64 | publish-to-pypi: 65 | name: >- 66 | Publish Python 🐍 distribution 📦 to PyPI 67 | needs: 68 | - bump-and-build 69 | runs-on: ubuntu-latest 70 | environment: 71 | name: pypi 72 | url: https://pypi.org/p/django-react-tools # PyPI project name 73 | permissions: 74 | id-token: write # IMPORTANT: mandatory for trusted publishing 75 | 76 | steps: 77 | - name: Download all the dists artifacts 78 | uses: actions/download-artifact@v4 79 | with: 80 | name: python-package-distributions 81 | path: dist/ 82 | 83 | - name: Publish distribution 📦 to PyPI 84 | uses: pypa/gh-action-pypi-publish@release/v1.12 85 | 86 | github-release: 87 | name: >- 88 | Sign the Python 🐍 distribution 📦 with Sigstore 89 | and upload them to GitHub Release 90 | needs: 91 | - publish-to-pypi 92 | runs-on: ubuntu-latest 93 | permissions: 94 | contents: write # IMPORTANT: mandatory for making GitHub Releases 95 | id-token: write # IMPORTANT: mandatory for sigstore 96 | 97 | steps: 98 | - name: Download all the dists 99 | uses: actions/download-artifact@v4 100 | with: 101 | name: python-package-distributions 102 | path: dist/ 103 | 104 | # Extract the version directly from a built .whl file 105 | - name: Extract version from Python package 106 | id: get_version 107 | run: | 108 | VERSION=$(ls dist/*.whl | head -n 1 | awk -F'-' '{print $2}') 109 | echo "PACKAGE_VERSION=$VERSION" >> $GITHUB_ENV 110 | 111 | - name: Sign the dists with Sigstore 112 | uses: sigstore/gh-action-sigstore-python@v2.1.1 113 | with: 114 | inputs: >- 115 | ./dist/*.tar.gz 116 | ./dist/*.whl 117 | 118 | - name: Create GitHub Release 119 | env: 120 | GITHUB_TOKEN: ${{ github.token }} 121 | run: >- 122 | gh release create 123 | "v${{ env.PACKAGE_VERSION }}" 124 | --repo '${{ github.repository }}' 125 | --title "Release v${{ env.PACKAGE_VERSION }}" 126 | --notes "Release for version ${{ env.PACKAGE_VERSION }}" 127 | 128 | - name: Upload artifact signatures to GitHub Release 129 | env: 130 | GITHUB_TOKEN: ${{ github.token }} 131 | # Upload to GitHub Release using the `gh` CLI. 132 | # `dist/` contains the built packages, and the 133 | # sigstore-produced signatures and certificates. 134 | run: >- 135 | gh release upload 136 | "v${{ env.PACKAGE_VERSION }}" dist/** 137 | --repo '${{ github.repository }}' 138 | -------------------------------------------------------------------------------- /react-test-app/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # Welcome to Django React Tools documentation! 2 | 3 | Django React Tools is for helping integrate ReactJS into your Django project. 4 | 5 | The current iteration of this tool adds a simple management command to your Django project that will build, copy to a Django static directory and rename accordingly. 6 | 7 | To start install the package in your project. 8 | 9 | ```bash 10 | > pip install django-react-tools 11 | ``` 12 | 13 | Next add ‘reacttools’ & 'django.contrib.sites' to your django project’s list of apps. 14 | 15 | The default destination location is the Static Root directory for your Django project. You can change it by modifying the setting variable. 16 | 17 | ```python 18 | REACT_DJANGO_DEST = settings.STATIC_ROOT 19 | ``` 20 | 21 | The default React Manifest file is set to "asset-manifest.json". If you are using a newer version of React (16.8+) you will want to change this value to "manifest.json" in your settings.py file. 22 | 23 | ```python 24 | REACT_MANIFEST_FILE = "asset-manifest.json" 25 | ``` 26 | 27 | By default the React project is buit using “yarn build”. If you want to change the command you can: 28 | 29 | ```python 30 | REACT_BUILD_COMMAND = "npm build" 31 | ``` 32 | 33 | **Updated in v0.2.0** 34 | 35 | Starting with v0.2.0 much of the configuration has been moved into Django models. This is so we can support multiple React projects within the same Django Project. 36 | 37 | To create the configurations, you need first migrate to create the tables: 38 | 39 | ```python 40 | ./manage.py migrate 41 | ``` 42 | 43 | In the admin panel, navigate to ReactTools > ReactAppSettings. 44 | 45 | Here, create a new React App Settings record. The only two required fields are the "React App Name" and "Project Dir". 46 | 47 | It's also reconmended that you make sure the settings are set to 'enabled'. This allows the 'collectreact' management command know which apps to look for. 48 | 49 | After you save your React App Settings, you will notice at the bottom of the page, the slug field. You will need this for your view class that hosts your app. 50 | 51 | The next step is to place the 'ReactEmbedMixin' view to the view controlling your React app. In there add the attribute: react_settings = "react-app-slug" to the view class. Notice that the value is for the slug from the model. This is so the view knows which React app to use. 52 | 53 | ```python 54 | from reacttools.views import ReactProxyMixin 55 | 56 | class MyAppView(ReactProxyMixin, TemplateView): 57 | template_name = "myapp/template.html" 58 | react_settings = "react-app-slug" 59 | ``` 60 | 61 | To run all you need to do is call the management command. 62 | 63 | ```bash 64 | > ./manage.py collectreact 65 | ``` 66 | 67 | This will find all the enabled react app settings and run the processing for each. 68 | 69 | If you want to skip the build you can run the comman this way: 70 | 71 | ```bash 72 | > ./manage.py collectreact --no-build 73 | ``` 74 | 75 | ## Experimental Features 76 | 77 | These features are a work in progress and do have some small known issues (like hot reload on Dev Server can lead to multiple reloads of JS files). If you have a suggestion on how to better aproach them, I'd love to hear from you. 78 | 79 | There are a couple of helpers for working with React running inside of a Django rendered page, refered to as a Hybrid App. 80 | 81 | To work with this we need include two more variables to help enable the features. 82 | 83 | ```bash 84 | REACT_DEV_SERVER = 'http://localhost:3000/' 85 | REACT_DEV_MODE = True 86 | ``` 87 | 88 | The REACT_DEV_SERVER defaults to 'http://localhost:3000/' so you only need to include it if you are using a different address and port. 89 | 90 | Setting REACT_DEV_MODE to True tells the ReactProxyMixin to use the proxy (REACT_DEV_SERVER) for finding the scripts instead of using the ones provided to a View using ReactProxyMixin in production. 91 | 92 | To make this all work in development, we end up proxying the JavaScript and manifest files through the Django Project from the Node Server. We do this so the App is loaded in the page's context while still letting the developer stay in managed mode from create-react-app so they can nearly hot-load their changes. 93 | 94 | ```python 95 | path('reacttools/', include('reacttools.urls')) 96 | ``` 97 | 98 | If you have a view that is hosting the Hybrid App, it's easiest to use a Generic Class Based View with the ReactProxyMixin also inherited. 99 | 100 | ```python 101 | class MyReactAppView(ReactProxyMixin, TemplateView): 102 | template_name = "reactapp/react_app_view.html" 103 | react_scripts = ['js/bundle.js', 'js/0.chunk.js', 'js/main.chunk.js'] # These are the production scripts 104 | react_styles = [] 105 | ``` 106 | 107 | In the above example, the react_scripts would be the scripts used in production. When you have REACT_DEV_MODE = True set, these are ignored and the mixin will query the server to get a list of JS files. 108 | 109 | To make this all show up properly, you will want to include these tags in your template. 110 | 111 | Put these in the to make sure to get the manifest and and CSS files. 112 | 113 | ```python 114 | {% if react_manifest %} 115 | 116 | {% endif %} 117 | 118 | {% for css in react_styles %} 119 | 120 | {% endfor %} 121 | ``` 122 | 123 | Put this at the bottom of your body, near the closing tag to include the JS files. 124 | 125 | ```python 126 | 127 | {% for js in react_scripts %} 128 | 129 | {% endfor %} 130 | ``` 131 | 132 | In case the proxy's resource name (URL / named path) is different than the default, the Attribute on ReactProxyMixin can be changed to reflect the new name. The default is 'reacttools-proxy'. 133 | 134 | ```python 135 | react_proxy_reverse_name = 'reacttools-proxy' 136 | ``` 137 | -------------------------------------------------------------------------------- /src/reacttools/management/commands/collectreact.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------- 2 | # Copyright 2013-2018, Grant Viklund 3 | # @Author: Grant Viklund 4 | # @Date: 2017-02-20 13:50:51 5 | # @Last Modified by: Grant Viklund 6 | # @Last Modified time: 2018-12-21 15:12:35 7 | # -------------------------------------------- 8 | import os 9 | import subprocess 10 | import json 11 | import fileinput 12 | 13 | from django.core.management.base import BaseCommand 14 | 15 | # from django.contrib.staticfiles.storage import staticfiles_storage # For future use 16 | # from django.core.files.storage import FileSystemStorage 17 | from django.conf import settings 18 | 19 | 20 | # Settings Variables 21 | 22 | REACT_PROJECT_DIRECTORY = getattr( 23 | settings, 24 | "REACT_PROJECT_DIRECTORY", 25 | os.path.join(settings.BASE_DIR, "..", "react-test-app"), 26 | ) 27 | REACT_BUILD_DIRECTORY = getattr( 28 | settings, "REACT_BUILD_DIRECTORY", os.path.join(REACT_PROJECT_DIRECTORY, "build") 29 | ) 30 | REACT_BUILD_COMMAND = getattr(settings, "REACT_BUILD_COMMAND", "yarn build") 31 | REACT_FILE_TYPES = getattr(settings, "REACT_FILE_TYPES", ["js", "css", "svg"]) 32 | REACT_DJANGO_DEST = getattr(settings, "REACT_DJANGO_DEST", settings.STATIC_ROOT) 33 | REACT_INCLUDE_MAP_FILES = getattr( 34 | settings, "REACT_INCLUDE_MAP_FILES", "map" in REACT_FILE_TYPES 35 | ) 36 | REACT_FILE_PREFIX = getattr(settings, "REACT_FILE_PREFIX", None) 37 | REACT_INCLUDED_NON_STATIC = getattr(settings, "REACT_INCLUDED_NON_STATIC", False) 38 | REACT_MANIFEST_FILE = getattr(settings, "REACT_MANIFEST_FILE", "asset-manifest.json") 39 | 40 | 41 | class Command(BaseCommand): 42 | 43 | help = "Collects the static files generated from a React project and moves them to the project's static directory" 44 | 45 | def add_arguments(self, parser): 46 | parser.add_argument( 47 | "--no-build", 48 | action="store_true", 49 | dest="no_build", 50 | help="Including this will skip the React build step.", 51 | ) 52 | parser.add_argument( 53 | "-n", 54 | "--dry-run", 55 | action="store_true", 56 | help="Do everything except modify the filesystem.", 57 | ) 58 | parser.add_argument( 59 | "--no-delete", 60 | action="store_true", 61 | dest="no_delete", 62 | help="Don't delete files in the destination directory before copying new ones.", 63 | ) 64 | 65 | def set_options(self, **options): 66 | """ 67 | Set instance variables based on an options dict 68 | """ 69 | self.nobuild = options["no_build"] 70 | self.nodelete = options["no_delete"] 71 | 72 | def handle(self, *args, **options): 73 | self.set_options(**options) 74 | 75 | try: 76 | # print("Done") 77 | self.process() 78 | 79 | except KeyboardInterrupt: 80 | print("\nExiting...") 81 | return 82 | 83 | def process(self): 84 | 85 | if self.nobuild: 86 | print("Skipping Build") 87 | else: 88 | print("Building React Project: '%s'" % REACT_BUILD_COMMAND) 89 | completed = subprocess.run( 90 | REACT_BUILD_COMMAND, shell=True, cwd=REACT_PROJECT_DIRECTORY 91 | ) 92 | print("returncode:", completed.returncode) 93 | 94 | asset_manifest = os.path.join(REACT_BUILD_DIRECTORY, REACT_MANIFEST_FILE) 95 | 96 | with open(asset_manifest) as json_file: 97 | manifest = json.load(json_file) 98 | 99 | if "files" in manifest: 100 | # Added to address the file change with the asset-manifest file structure 101 | files = manifest["files"].items() 102 | else: 103 | files = manifest.items() 104 | 105 | for key, value in files: 106 | 107 | if key.split(".")[-1] in REACT_FILE_TYPES: 108 | relative_value = value[1:] 109 | dest = self.destination_path(relative_value) 110 | 111 | if dest == None: # If the destination is not valid, it will return None 112 | continue 113 | 114 | # Check the destination folder exists 115 | dest_folder = os.path.dirname(dest) 116 | 117 | if not os.path.isdir(dest_folder): 118 | os.makedirs(dest_folder, exist_ok=True) 119 | else: 120 | if self.nodelete: 121 | print("Skipping delete of files in destination directory(s)") 122 | else: 123 | print("Deleting existing files in: %s" % (dest_folder)) 124 | subprocess.run("rm %s/*" % (dest_folder), shell=True) 125 | 126 | for key, value in files: 127 | 128 | if key.split(".")[-1] in REACT_FILE_TYPES: 129 | relative_value = value[1:] 130 | source = os.path.abspath( 131 | os.path.join(REACT_BUILD_DIRECTORY, relative_value) 132 | ) 133 | dest = self.destination_path(relative_value) 134 | 135 | if dest == None: # If the destination is not valid, it will return None 136 | continue 137 | 138 | print("Copying: %s -> %s" % (source, dest)) 139 | # Copy the files here and overwrite the old files 140 | # modify any text files here 141 | 142 | subprocess.run("cp %s %s" % (source, dest), shell=True) 143 | 144 | def destination_path(self, file_path): 145 | """ 146 | Returns the destination path or None. If it's None, that means 147 | the path is invalid and should be skipped. 148 | """ 149 | 150 | # Pop static 151 | path_parts = file_path.split("/") 152 | 153 | if path_parts[0] == "static": 154 | path_parts.pop(0) 155 | else: 156 | if not REACT_INCLUDED_NON_STATIC: 157 | return None 158 | 159 | path_parts[-1] = self.clean_name(path_parts[-1]) 160 | 161 | if REACT_FILE_PREFIX: 162 | path_parts[-1] = REACT_FILE_PREFIX + path_parts[-1] 163 | 164 | # FORCE FILES TO BE IN APROPRIATE DIRECTORIES? (for example: 'service-worker.js', 'precache-manifest.js' default to static root) 165 | 166 | dest_path = os.path.abspath(REACT_DJANGO_DEST) 167 | 168 | # MAKE SURE THE REACT_DJANGO_DEST PATH EXISTS... 169 | if not os.path.exists(dest_path): 170 | os.mkdir(dest_path) 171 | 172 | result = os.path.join(dest_path, *path_parts) 173 | 174 | return result 175 | 176 | def clean_name(self, file_name): 177 | 178 | parts = file_name.split(".") 179 | 180 | if len(parts) > 2: 181 | junk = parts.pop(1) 182 | 183 | if settings.DEBUG: 184 | print("Removing '%s' from '%s'" % (junk, file_name)) 185 | 186 | return ".".join(parts) 187 | -------------------------------------------------------------------------------- /src/reacttools/views.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | from django.urls import reverse_lazy 4 | from django import http 5 | from django.conf import settings 6 | from django.views.generic import TemplateView 7 | from django.shortcuts import render 8 | from django.template import engines 9 | from django.templatetags.static import static 10 | 11 | from html.parser import HTMLParser 12 | from reacttools.models import ReactAppSettings 13 | 14 | REACT_DEV_MODE = getattr(settings, "REACT_DEV_MODE", False) 15 | REACT_DEV_SERVER = getattr(settings, "REACT_DEV_SERVER", "http://localhost:3000/") 16 | 17 | """ 18 | Sample React Node Server Data: 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 31 | 32 | 33 | 42 | React App 43 | 44 | 45 | 48 |
49 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | """ 66 | 67 | 68 | class ReactHTMLParser(HTMLParser): 69 | """ 70 | This is a very targeted to extract what is needed when developing a hybrid app. 71 | """ 72 | 73 | in_head = False 74 | in_body = False 75 | data = {"react_scripts": [], "react_manifest": None} 76 | 77 | def handle_starttag(self, tag, attrs): 78 | 79 | if tag == "head": 80 | self.in_head = True 81 | 82 | if tag == "body": 83 | self.in_body = True 84 | 85 | if tag == "script" and self.in_body: # Extract the Script Tags 86 | for attr in attrs: 87 | if attr[0] == "src": 88 | self.data["react_scripts"].append( 89 | attr[1][1:] 90 | ) # Strips off the leading "/" 91 | 92 | if tag == "link" and self.in_head: # Extract the Manifest Tags 93 | manifest_tag = False 94 | for attr in attrs: 95 | if manifest_tag and attr[0] == "href": 96 | self.data["react_manifest"] = attr[1][ 97 | 1: 98 | ] # Strips off the leading "/" 99 | manifest_tag = False 100 | if attr[0] == "rel" and attr[1] == "manifest": 101 | manifest_tag = True 102 | 103 | def handle_endtag(self, tag): 104 | 105 | if tag == "head": 106 | self.in_head = False 107 | 108 | if tag == "body": 109 | self.in_body = False 110 | 111 | 112 | # -------------- 113 | # MIXINS 114 | # -------------- 115 | 116 | 117 | class ReactEmbedMixin(object): 118 | 119 | react_dev_server = REACT_DEV_SERVER # todo: Figure out way to support different servers at the same time in the proxy 120 | react_settings = None 121 | 122 | def get_context_data(self, **kwargs): 123 | 124 | kwargs = super().get_context_data(**kwargs) 125 | 126 | if REACT_DEV_MODE: 127 | # Query the server for the scripts to proxy 128 | response = requests.get(self.react_dev_server) 129 | content = engines["django"].from_string(response.text).render() 130 | 131 | parser = ReactHTMLParser() 132 | parser.feed(content) 133 | 134 | kwargs["react_root"] = [] 135 | kwargs["react_styles"] = [] 136 | kwargs["react_scripts"] = [ 137 | "%s%s" % (self.react_dev_server, p) 138 | for p in parser.data["react_scripts"] 139 | ] 140 | kwargs["react_manifest"] = "%s%s" % ( 141 | self.react_dev_server, 142 | parser.data["react_manifest"], 143 | ) 144 | else: 145 | kwargs["react_root"] = [] 146 | kwargs["react_scripts"] = [] 147 | kwargs["react_styles"] = [] 148 | kwargs["react_manifest"] = [] 149 | 150 | for config in ReactAppSettings.objects.filter(slug=self.react_settings): 151 | kwargs["react_root"].append(config.react_root) 152 | kwargs["react_scripts"].extend(config.js_paths()) 153 | kwargs["react_styles"].extend(config.css_paths()) 154 | kwargs["react_manifest"].append(config.manifest) 155 | 156 | return kwargs 157 | 158 | 159 | class ReactProxyMixin(object): 160 | 161 | react_dev_server = REACT_DEV_SERVER # todo: Figure out way to support different servers at the same time in the proxy 162 | react_proxy_resource_name = "reacttools-proxy" 163 | react_settings = None 164 | 165 | def get_context_data(self, **kwargs): 166 | 167 | kwargs = super().get_context_data(**kwargs) 168 | 169 | if REACT_DEV_MODE: 170 | # Query the server for the scripts to proxy 171 | response = requests.get(self.react_dev_server) 172 | content = engines["django"].from_string(response.text).render() 173 | 174 | parser = ReactHTMLParser() 175 | parser.feed(content) 176 | 177 | kwargs["react_styles"] = [] 178 | kwargs["react_scripts"] = [ 179 | reverse_lazy(self.react_proxy_resource_name, args=(p,)) 180 | for p in parser.data["react_scripts"] 181 | ] 182 | kwargs["react_manifest"] = reverse_lazy( 183 | self.react_proxy_resource_name, args=(parser.data["react_manifest"],) 184 | ) 185 | else: 186 | config = ReactAppSettings.objects.get(slug=self.react_settings) 187 | kwargs["react_scripts"] = config.js_paths() 188 | kwargs["react_styles"] = config.css_paths() 189 | kwargs["react_manifest"] = config.manifest 190 | 191 | return kwargs 192 | 193 | 194 | # -------------- 195 | # VIEWS 196 | # -------------- 197 | 198 | 199 | class IndexView(ReactEmbedMixin, TemplateView): 200 | template_name = "reacttools/index.html" 201 | 202 | 203 | # import requests 204 | # from django import http 205 | # from django.conf import settings 206 | # from django.template import engines 207 | # from django.shortcuts import render 208 | # from django.views.generic import TemplateView 209 | # from django.contrib.auth.mixins import LoginRequiredMixin 210 | 211 | # -------------- 212 | # BASE VIEWS - Any base level views you will inherit in your views 213 | # -------------- 214 | 215 | 216 | # -------------- 217 | # MIXINS - Local Mixins that you create 218 | # -------------- 219 | 220 | 221 | # -------------- 222 | # VIEWS - Views for your app 223 | # -------------- 224 | 225 | 226 | class ReactAppView(TemplateView): 227 | """ 228 | View for serving React apps using the App config model. 229 | """ 230 | 231 | template_name = "reacttools/react_app_view.html" 232 | react_settings = "react-app" 233 | 234 | def get_context_data(self, **kwargs): 235 | ctx = super().get_context_data(**kwargs) 236 | ctx["js_debug"] = settings.REACT_DEBUG 237 | 238 | ctx["react_root"] = [] 239 | ctx["react_scripts"] = [] 240 | ctx["react_styles"] = [] 241 | ctx["react_manifest"] = [] 242 | 243 | for config in ReactAppSettings.objects.filter(slug=self.react_settings): 244 | ctx["react_root"].append(config.react_root) 245 | ctx["react_scripts"].extend(config.js_paths()) 246 | ctx["react_styles"].extend(config.css_paths()) 247 | ctx["react_manifest"].append(config.manifest) 248 | 249 | return ctx 250 | 251 | 252 | def proxy(request, path): 253 | """ 254 | Based on the guide from Aymeric Augustin 255 | https://fractalideas.com/blog/making-react-and-django-play-well-together-hybrid-app-model/ 256 | """ 257 | 258 | if settings.DEBUG: 259 | print("PROXY-ING: %s" % (REACT_DEV_SERVER + path)) # todo: move to logger? 260 | 261 | response = requests.get(REACT_DEV_SERVER + path) 262 | content_type = response.headers.get("Content-Type") 263 | 264 | # print(request.META) 265 | 266 | if ( 267 | request.META.get("HTTP_UPGRADE", "").lower() == "websocket" 268 | ): # REDIRECT TO NODE SERVER 269 | # return http.HttpResponse( 270 | # content="WebSocket connections aren't supported", 271 | # status=501, 272 | # reason="Not Implemented" 273 | # ) 274 | return http.HttpResponseRedirect(REACT_DEV_SERVER + path) # This might work 275 | 276 | elif content_type == "text/html; charset=UTF-8": 277 | result = http.HttpResponse( 278 | content=engines["django"].from_string(response.text).render(), 279 | status=response.status_code, 280 | reason=response.reason, 281 | ) 282 | 283 | else: 284 | return http.StreamingHttpResponse( 285 | streaming_content=response.iter_content(2**12), 286 | content_type=content_type, 287 | status=response.status_code, 288 | reason=response.reason, 289 | ) 290 | 291 | # set headers to NOT cache so the scripts are always live 292 | # header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1 293 | # header("Pragma: no-cache"); //HTTP 1.0 294 | # header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past 295 | 296 | result["Cache-Control"] = "no-cache, must-revalidate" 297 | result["Pragma"] = "no-cache" 298 | 299 | return result 300 | --------------------------------------------------------------------------------