├── README.md ├── db.sqlite3 ├── django_react_proj ├── .gitignore ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py ├── students-fe ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt ├── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── components │ │ ├── ConfirmRemovalModal.js │ │ ├── Header.js │ │ ├── Home.js │ │ ├── NewStudentForm.js │ │ ├── NewStudentModal.js │ │ └── StudentList.js │ ├── constants │ │ └── index.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ └── serviceWorker.js └── yarn.lock └── students ├── .gitignore ├── __init__.py ├── admin.py ├── apps.py ├── migrations ├── 0001_initial.py ├── 0002_students.py └── __init__.py ├── models.py ├── serializers.py ├── tests.py └── views.py /README.md: -------------------------------------------------------------------------------- 1 | # React App + Django API 2 | 3 | A simple integration between a Django API and a React App as a result of my article: [Creating an app with React and Django](https://blog.logrocket.com/creating-an-app-with-react-and-django/). 4 | 5 | This project consists of two internal projects: 6 | 7 | - *students*: the Django project containing the REST API along with all the backend code; 8 | - *students-fe*: the React project with all the Node dependencies, settings and things related to the frontend. 9 | 10 | ## Run it locally 11 | 12 | In order to run the projects locally you need to have Node, npm and `python3` installed on your machine. 13 | 14 | ### Running the Django project 15 | 16 | First, create a Python virtual environment to isolate the projects: 17 | 18 | ```bash 19 | python3 -m venv logrocket_env 20 | ``` 21 | 22 | Then, activate it: 23 | 24 | ```bash 25 | source logrocket_env/bin/activate 26 | ``` 27 | 28 | `cd` into the _venv_ and clone the project from GitHub: 29 | 30 | ```bash 31 | git clone https://github.com/diogosouza/django-react-logrocket.git 32 | ``` 33 | 34 | Add the Django dependencies: 35 | 36 | ```bash 37 | pip install django djangorestframework django-cors-headers 38 | ``` 39 | 40 | Finally, `cd` into the _django-react-logrocket_ folder and run the project: 41 | 42 | ```bash 43 | python manage.py runserver 44 | ``` 45 | 46 | That's it! 47 | 48 | Access the address http://localhost:8000/api/students/ and check if the API is up. 49 | 50 | ### Running the React project 51 | 52 | First, `cd` the _students-fe_ directory and run: 53 | 54 | ```bash 55 | npm install 56 | npm start 57 | ``` 58 | -------------------------------------------------------------------------------- /db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diogosouza/django-react-example/67411b3f7d33e1a0ecd6cb4be0ebeea2352674dc/db.sqlite3 -------------------------------------------------------------------------------- /django_react_proj/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io 2 | 3 | ### OSX ### 4 | .DS_Store 5 | .AppleDouble 6 | .LSOverride 7 | 8 | # Icon must end with two \r 9 | Icon 10 | 11 | 12 | # Thumbnails 13 | ._* 14 | 15 | # Files that might appear on external disk 16 | .Spotlight-V100 17 | .Trashes 18 | 19 | # Directories potentially created on remote AFP share 20 | .AppleDB 21 | .AppleDesktop 22 | Network Trash Folder 23 | Temporary Items 24 | .apdisk 25 | 26 | 27 | ### Python ### 28 | # Byte-compiled / optimized / DLL files 29 | __pycache__/ 30 | *.py[cod] 31 | 32 | # C extensions 33 | *.so 34 | 35 | # Distribution / packaging 36 | .Python 37 | env/ 38 | build/ 39 | develop-eggs/ 40 | dist/ 41 | downloads/ 42 | eggs/ 43 | lib/ 44 | lib64/ 45 | parts/ 46 | sdist/ 47 | var/ 48 | *.egg-info/ 49 | .installed.cfg 50 | *.egg 51 | 52 | # PyInstaller 53 | # Usually these files are written by a python script from a template 54 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 55 | *.manifest 56 | *.spec 57 | 58 | # Installer logs 59 | pip-log.txt 60 | pip-delete-this-directory.txt 61 | 62 | # Unit test / coverage reports 63 | htmlcov/ 64 | .tox/ 65 | .coverage 66 | .cache 67 | nosetests.xml 68 | coverage.xml 69 | 70 | # Translations 71 | *.mo 72 | *.pot 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | target/ 79 | 80 | 81 | ### Django ### 82 | *.log 83 | *.pot 84 | *.pyc 85 | __pycache__/ 86 | local_settings.py 87 | 88 | .env 89 | db.sqlite3 90 | 91 | -------------------------------------------------------------------------------- /django_react_proj/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diogosouza/django-react-example/67411b3f7d33e1a0ecd6cb4be0ebeea2352674dc/django_react_proj/__init__.py -------------------------------------------------------------------------------- /django_react_proj/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for django_react_proj project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/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.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'jg^$(lbjb*3-+cv(88ngpb4xb=6vbvxj*1i)%m!*c2(e_i6%b8' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'rest_framework', 41 | 'corsheaders', 42 | 'students' 43 | ] 44 | 45 | MIDDLEWARE = [ 46 | 'django.middleware.security.SecurityMiddleware', 47 | 'django.contrib.sessions.middleware.SessionMiddleware', 48 | 'django.middleware.common.CommonMiddleware', 49 | 'django.middleware.csrf.CsrfViewMiddleware', 50 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 51 | 'django.contrib.messages.middleware.MessageMiddleware', 52 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 53 | 'corsheaders.middleware.CorsMiddleware', 54 | 'django.middleware.common.CommonMiddleware', 55 | ] 56 | 57 | CORS_ORIGIN_ALLOW_ALL = True 58 | 59 | ROOT_URLCONF = 'django_react_proj.urls' 60 | 61 | TEMPLATES = [ 62 | { 63 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 64 | 'DIRS': [], 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 = 'django_react_proj.wsgi.application' 78 | 79 | 80 | # Database 81 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 82 | 83 | DATABASES = { 84 | 'default': { 85 | 'ENGINE': 'django.db.backends.sqlite3', 86 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 87 | } 88 | } 89 | 90 | 91 | # Password validation 92 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 93 | 94 | AUTH_PASSWORD_VALIDATORS = [ 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 103 | }, 104 | { 105 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 106 | }, 107 | ] 108 | 109 | 110 | # Internationalization 111 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 112 | 113 | LANGUAGE_CODE = 'en-us' 114 | 115 | TIME_ZONE = 'UTC' 116 | 117 | USE_I18N = True 118 | 119 | USE_L10N = True 120 | 121 | USE_TZ = True 122 | 123 | 124 | # Static files (CSS, JavaScript, Images) 125 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 126 | 127 | STATIC_URL = '/static/' 128 | -------------------------------------------------------------------------------- /django_react_proj/urls.py: -------------------------------------------------------------------------------- 1 | """django_react_proj URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/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 | from django.contrib import admin 17 | from django.urls import path, re_path 18 | from students import views 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | re_path(r'^api/students/$', views.students_list), 23 | re_path(r'^api/students/(?P[0-9]+)$', views.students_detail), 24 | ] 25 | -------------------------------------------------------------------------------- /django_react_proj/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_react_proj 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.2/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', 'django_react_proj.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_react_proj.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /students-fe/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /students-fe/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 | ### `yarn 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 | ### `yarn 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 | ### `yarn 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 | ### `yarn 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 | ### `yarn 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 | -------------------------------------------------------------------------------- /students-fe/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "students-fe", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "axios": "^0.21.1", 7 | "bootstrap": "^4.4.1", 8 | "react": "^16.12.0", 9 | "react-dom": "^16.12.0", 10 | "react-scripts": "^3.3.1", 11 | "reactstrap": "^8.1.1" 12 | }, 13 | "scripts": { 14 | "start": "react-scripts start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /students-fe/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diogosouza/django-react-example/67411b3f7d33e1a0ecd6cb4be0ebeea2352674dc/students-fe/public/favicon.ico -------------------------------------------------------------------------------- /students-fe/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /students-fe/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diogosouza/django-react-example/67411b3f7d33e1a0ecd6cb4be0ebeea2352674dc/students-fe/public/logo192.png -------------------------------------------------------------------------------- /students-fe/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diogosouza/django-react-example/67411b3f7d33e1a0ecd6cb4be0ebeea2352674dc/students-fe/public/logo512.png -------------------------------------------------------------------------------- /students-fe/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 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /students-fe/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /students-fe/src/App.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diogosouza/django-react-example/67411b3f7d33e1a0ecd6cb4be0ebeea2352674dc/students-fe/src/App.css -------------------------------------------------------------------------------- /students-fe/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component, Fragment } from "react"; 2 | import Header from "./components/Header"; 3 | import Home from "./components/Home"; 4 | 5 | class App extends Component { 6 | render() { 7 | return ( 8 | 9 |
10 | 11 | 12 | ); 13 | } 14 | } 15 | 16 | export default App; 17 | -------------------------------------------------------------------------------- /students-fe/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 | -------------------------------------------------------------------------------- /students-fe/src/components/ConfirmRemovalModal.js: -------------------------------------------------------------------------------- 1 | import React, { Component, Fragment } from "react"; 2 | import { Modal, ModalHeader, Button, ModalFooter } from "reactstrap"; 3 | 4 | import axios from "axios"; 5 | 6 | import { API_URL } from "../constants"; 7 | 8 | class ConfirmRemovalModal extends Component { 9 | state = { 10 | modal: false 11 | }; 12 | 13 | toggle = () => { 14 | this.setState(previous => ({ 15 | modal: !previous.modal 16 | })); 17 | }; 18 | 19 | deleteStudent = pk => { 20 | axios.delete(API_URL + pk).then(() => { 21 | this.props.resetState(); 22 | this.toggle(); 23 | }); 24 | }; 25 | 26 | render() { 27 | return ( 28 | 29 | 32 | 33 | 34 | Do you really wanna delete the student? 35 | 36 | 37 | 38 | 41 | 48 | 49 | 50 | 51 | ); 52 | } 53 | } 54 | 55 | export default ConfirmRemovalModal; 56 | -------------------------------------------------------------------------------- /students-fe/src/components/Header.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | class Header extends Component { 4 | render() { 5 | return ( 6 |
7 | 13 |
14 |
15 | presents 16 |
17 |

App with React + Django

18 |
19 | ); 20 | } 21 | } 22 | 23 | export default Header; 24 | -------------------------------------------------------------------------------- /students-fe/src/components/Home.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Col, Container, Row } from "reactstrap"; 3 | import StudentList from "./StudentList"; 4 | import NewStudentModal from "./NewStudentModal"; 5 | 6 | import axios from "axios"; 7 | 8 | import { API_URL } from "../constants"; 9 | 10 | class Home extends Component { 11 | state = { 12 | students: [] 13 | }; 14 | 15 | componentDidMount() { 16 | this.resetState(); 17 | } 18 | 19 | getStudents = () => { 20 | axios.get(API_URL).then(res => this.setState({ students: res.data })); 21 | }; 22 | 23 | resetState = () => { 24 | this.getStudents(); 25 | }; 26 | 27 | render() { 28 | return ( 29 | 30 | 31 | 32 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | ); 45 | } 46 | } 47 | 48 | export default Home; 49 | -------------------------------------------------------------------------------- /students-fe/src/components/NewStudentForm.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Button, Form, FormGroup, Input, Label } from "reactstrap"; 3 | 4 | import axios from "axios"; 5 | 6 | import { API_URL } from "../constants"; 7 | 8 | class NewStudentForm extends React.Component { 9 | state = { 10 | pk: 0, 11 | name: "", 12 | email: "", 13 | document: "", 14 | phone: "" 15 | }; 16 | 17 | componentDidMount() { 18 | if (this.props.student) { 19 | const { pk, name, document, email, phone } = this.props.student; 20 | this.setState({ pk, name, document, email, phone }); 21 | } 22 | } 23 | 24 | onChange = e => { 25 | this.setState({ [e.target.name]: e.target.value }); 26 | }; 27 | 28 | createStudent = e => { 29 | e.preventDefault(); 30 | axios.post(API_URL, this.state).then(() => { 31 | this.props.resetState(); 32 | this.props.toggle(); 33 | }); 34 | }; 35 | 36 | editStudent = e => { 37 | e.preventDefault(); 38 | axios.put(API_URL + this.state.pk, this.state).then(() => { 39 | this.props.resetState(); 40 | this.props.toggle(); 41 | }); 42 | }; 43 | 44 | defaultIfEmpty = value => { 45 | return value === "" ? "" : value; 46 | }; 47 | 48 | render() { 49 | return ( 50 |
51 | 52 | 53 | 59 | 60 | 61 | 62 | 68 | 69 | 70 | 71 | 77 | 78 | 79 | 80 | 86 | 87 | 88 |
89 | ); 90 | } 91 | } 92 | 93 | export default NewStudentForm; 94 | -------------------------------------------------------------------------------- /students-fe/src/components/NewStudentModal.js: -------------------------------------------------------------------------------- 1 | import React, { Component, Fragment } from "react"; 2 | import { Button, Modal, ModalHeader, ModalBody } from "reactstrap"; 3 | import NewStudentForm from "./NewStudentForm"; 4 | 5 | class NewStudentModal extends Component { 6 | state = { 7 | modal: false 8 | }; 9 | 10 | toggle = () => { 11 | this.setState(previous => ({ 12 | modal: !previous.modal 13 | })); 14 | }; 15 | 16 | render() { 17 | const create = this.props.create; 18 | 19 | var title = "Editing Student"; 20 | var button = ; 21 | if (create) { 22 | title = "Creating New Student"; 23 | 24 | button = ( 25 | 33 | ); 34 | } 35 | 36 | return ( 37 | 38 | {button} 39 | 40 | {title} 41 | 42 | 43 | 48 | 49 | 50 | 51 | ); 52 | } 53 | } 54 | 55 | export default NewStudentModal; 56 | -------------------------------------------------------------------------------- /students-fe/src/components/StudentList.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Table } from "reactstrap"; 3 | import NewStudentModal from "./NewStudentModal"; 4 | 5 | import ConfirmRemovalModal from "./ConfirmRemovalModal"; 6 | 7 | class StudentList extends Component { 8 | render() { 9 | const students = this.props.students; 10 | return ( 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | {!students || students.length <= 0 ? ( 24 | 25 | 28 | 29 | ) : ( 30 | students.map(student => ( 31 | 32 | 33 | 34 | 35 | 36 | 37 | 49 | 50 | )) 51 | )} 52 | 53 |
NameEmailDocumentPhoneRegistration
26 | Ops, no one here yet 27 |
{student.name}{student.email}{student.document}{student.phone}{student.registrationDate} 38 | 43 |    44 | 48 |
54 | ); 55 | } 56 | } 57 | 58 | export default StudentList; 59 | -------------------------------------------------------------------------------- /students-fe/src/constants/index.js: -------------------------------------------------------------------------------- 1 | export const API_URL = "http://localhost:8000/api/students/"; 2 | -------------------------------------------------------------------------------- /students-fe/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 | 15 | .btn-primary, .btn-primary:hover, .btn-primary:active, .btn-primary:visited { 16 | background-color: #764abc !important; 17 | border: none !important; 18 | } -------------------------------------------------------------------------------- /students-fe/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 'bootstrap/dist/css/bootstrap.min.css'; 6 | import * as serviceWorker from './serviceWorker'; 7 | 8 | ReactDOM.render(, document.getElementById('root')); 9 | 10 | // If you want your app to work offline and load faster, you can change 11 | // unregister() to register() below. Note this comes with some pitfalls. 12 | // Learn more about service workers: https://bit.ly/CRA-PWA 13 | serviceWorker.unregister(); 14 | -------------------------------------------------------------------------------- /students-fe/src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /students-fe/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 | -------------------------------------------------------------------------------- /students/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io 2 | 3 | ### OSX ### 4 | .DS_Store 5 | .AppleDouble 6 | .LSOverride 7 | 8 | # Icon must end with two \r 9 | Icon 10 | 11 | 12 | # Thumbnails 13 | ._* 14 | 15 | # Files that might appear on external disk 16 | .Spotlight-V100 17 | .Trashes 18 | 19 | # Directories potentially created on remote AFP share 20 | .AppleDB 21 | .AppleDesktop 22 | Network Trash Folder 23 | Temporary Items 24 | .apdisk 25 | 26 | 27 | ### Python ### 28 | # Byte-compiled / optimized / DLL files 29 | __pycache__/ 30 | *.py[cod] 31 | 32 | # C extensions 33 | *.so 34 | 35 | # Distribution / packaging 36 | .Python 37 | env/ 38 | build/ 39 | develop-eggs/ 40 | dist/ 41 | downloads/ 42 | eggs/ 43 | lib/ 44 | lib64/ 45 | parts/ 46 | sdist/ 47 | var/ 48 | *.egg-info/ 49 | .installed.cfg 50 | *.egg 51 | 52 | # PyInstaller 53 | # Usually these files are written by a python script from a template 54 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 55 | *.manifest 56 | *.spec 57 | 58 | # Installer logs 59 | pip-log.txt 60 | pip-delete-this-directory.txt 61 | 62 | # Unit test / coverage reports 63 | htmlcov/ 64 | .tox/ 65 | .coverage 66 | .cache 67 | nosetests.xml 68 | coverage.xml 69 | 70 | # Translations 71 | *.mo 72 | *.pot 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | target/ 79 | 80 | 81 | ### Django ### 82 | *.log 83 | *.pot 84 | *.pyc 85 | __pycache__/ 86 | local_settings.py 87 | 88 | .env 89 | db.sqlite3 90 | 91 | -------------------------------------------------------------------------------- /students/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diogosouza/django-react-example/67411b3f7d33e1a0ecd6cb4be0ebeea2352674dc/students/__init__.py -------------------------------------------------------------------------------- /students/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /students/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class StudentsConfig(AppConfig): 5 | name = 'students' 6 | -------------------------------------------------------------------------------- /students/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.7 on 2019-11-29 13:46 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Student', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('name', models.CharField(max_length=240, verbose_name='Name')), 19 | ('email', models.EmailField(max_length=254)), 20 | ('document', models.CharField(max_length=20, verbose_name='Document')), 21 | ('phone', models.CharField(max_length=20)), 22 | ('registrationDate', models.DateField(auto_now_add=True, verbose_name='Registration Date')), 23 | ], 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /students/migrations/0002_students.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.7 on 2019-11-29 13:47 2 | 3 | from django.db import migrations 4 | 5 | def create_data(apps, schema_editor): 6 | Student = apps.get_model('students', 'Student') 7 | Student(name="Joe Silver", email="joe@email.com", document="22342342", phone="00000000").save() 8 | 9 | class Migration(migrations.Migration): 10 | 11 | dependencies = [ 12 | ('students', '0001_initial'), 13 | ] 14 | 15 | operations = [ 16 | migrations.RunPython(create_data), 17 | ] 18 | -------------------------------------------------------------------------------- /students/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diogosouza/django-react-example/67411b3f7d33e1a0ecd6cb4be0ebeea2352674dc/students/migrations/__init__.py -------------------------------------------------------------------------------- /students/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | class Student(models.Model): 4 | name = models.CharField("Name", max_length=240) 5 | email = models.EmailField() 6 | document = models.CharField("Document", max_length=20) 7 | phone = models.CharField(max_length=20) 8 | registrationDate = models.DateField("Registration Date", auto_now_add=True) 9 | 10 | def __str__(self): 11 | return self.name -------------------------------------------------------------------------------- /students/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework import serializers 2 | from .models import Student 3 | 4 | class StudentSerializer(serializers.ModelSerializer): 5 | 6 | class Meta: 7 | model = Student 8 | fields = ('pk', 'name', 'email', 'document', 'phone', 'registrationDate') 9 | -------------------------------------------------------------------------------- /students/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /students/views.py: -------------------------------------------------------------------------------- 1 | from rest_framework.response import Response 2 | from rest_framework.decorators import api_view 3 | from rest_framework import status 4 | 5 | from .models import Student 6 | from .serializers import * 7 | 8 | @api_view(['GET', 'POST']) 9 | def students_list(request): 10 | if request.method == 'GET': 11 | data = Student.objects.all() 12 | 13 | serializer = StudentSerializer(data, context={'request': request}, many=True) 14 | 15 | return Response(serializer.data) 16 | 17 | elif request.method == 'POST': 18 | serializer = StudentSerializer(data=request.data) 19 | if serializer.is_valid(): 20 | serializer.save() 21 | return Response(status=status.HTTP_201_CREATED) 22 | 23 | return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 24 | 25 | @api_view(['PUT', 'DELETE']) 26 | def students_detail(request, pk): 27 | try: 28 | student = Student.objects.get(pk=pk) 29 | except Student.DoesNotExist: 30 | return Response(status=status.HTTP_404_NOT_FOUND) 31 | 32 | if request.method == 'PUT': 33 | serializer = StudentSerializer(student, data=request.data,context={'request': request}) 34 | if serializer.is_valid(): 35 | serializer.save() 36 | return Response(status=status.HTTP_204_NO_CONTENT) 37 | return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 38 | 39 | elif request.method == 'DELETE': 40 | student.delete() 41 | return Response(status=status.HTTP_204_NO_CONTENT) --------------------------------------------------------------------------------