Skip to content

Instantly share code, notes, and snippets.

@mikamboo
Last active October 26, 2020 11:41
Show Gist options
  • Save mikamboo/1002f2057b4dc38298a6a3cc1a69bc23 to your computer and use it in GitHub Desktop.
Save mikamboo/1002f2057b4dc38298a6a3cc1a69bc23 to your computer and use it in GitHub Desktop.
Django : Quick start project with React

Django Quick Start

Summary based on official intro tuto doc : https://docs.djangoproject.com/fr/3.1/intro/tutorial01

Requirements

  • python 3
  • pipenv : pip install pipenv

Create project

pipenv shell
pip install Django==3.1.2
django-admin startproject mysite

Add app to project

cd mysite
python manage.py startapp polls

Grenerate requirements.txt file

pip freeze > requirements.txt

Start

python manage.py migrate
python manage.py runserver 8080

Création fichiers migration ... et application

python manage.py makemigrations polls

# Check what Django will apply
python manage.py sqlmigrate polls 0001

# Check issues
python manage.py check

# Apply migration
python manage.py migrate

Shell interractif

python manage.py shell

Exemple commandes :

>>> from polls.models import Choice, Question  # Import the model classes we just wrote.
>>> Question.objects.all()
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()

# Now it has an ID.
>>> q.id
>>> Question.objects.all()
>>> Question.objects.filter(id=1)

Admin

Create

python manage.py createsuperuser

Polls

Polls is a Django app to conduct Web-based polls. For each question, visitors can choose between a fixed number of answers.

Detailed documentation is in the "docs" directory.

Quick start

  1. Add "polls" to your INSTALLED_APPS setting like this:

    INSTALLED_APPS = [
        ...
        'polls',
    ]
    
  2. Include the polls URLconf in your project urls.py like this:

    path('polls/', include('polls.urls')),
    
  3. Run python manage.py migrate to create the polls models.

  4. Start the development server and visit http://127.0.0.1:8000/admin/ to create a poll (you'll need the Admin app enabled).

  5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.

import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<>
<h2>Hello React !</h2>
</>
);
}
}
export default App;

React frontend with Django

We chose to integrate React as Django project application.

More approaches detailed here : https://www.valentinog.com/blog/drf/#django-rest-with-react-setting-up-the-controll-ehm-the-views

Pre-requistes

  • A working Dgango project

Create React frontend app

From Danjo project root directory run :

django-admin startapp frontend

mkdir -p ./frontend/src/components
mkdir -p ./frontend/{static,templates}/frontend

touch ./frontend/src/index.js
touch ./frontend/src/components/App.js
touch ./frontend/views.py
touch ./frontend/static/frontend/index.html
touch ./frontend/templates/frontend/index.html

Install frontent dev dependencies

cd frontend && npm init -y

# Get Webpack
yarn add  webpack webpack-cli webpack-dev-server --dev

# Get babel for transpiling our code
yarn add @babel/core babel-loader @babel/preset-env @babel/preset-react --dev

# Get React
yarn add react react-dom --dev

# Create config files
touch .babelrc webpack.config.js

Add react build commands in ./frontend/package.json :

"scripts": {
  "serve": "webpack serve --mode development --watch",
  "start": "webpack --mode development",
  "build": "webpack --mode production"
}

Configure babel in ./frontend/.babelrc :

{
  "presets": [
    "@babel/preset-env", "@babel/preset-react"
  ]
}

Configure webpack in ./frontend/webpack.config.js :

const path = require('path');

module.exports = {
  output: {
    filename: 'main.js',
    path: path.join(__dirname, 'static/frontend')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  devServer: {
    publicPath: '/static/frontend/',
    contentBase: path.join(__dirname, 'static/frontend'),
    compress: true,
    port: 9000,
    proxy: {
      '*': 'http://localhost:8000',
    }
  }
};

NB : We use webpack-dev-server to enable livereload for react frontend at : http://localhost:9000

  • We add following content in ./frontend/templates/frontend/index.html for React devServer :
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django REST with React</title>
    <link rel="icon" type="image/ico" href="/static/frontend/assets/favicon.ico">
  </head>
  <body>
  <div id="root">
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <!-- React will load here -->
  </div>
  </body>
  <script src="/static/frontend/main.js"></script>
</html>

This html page is used to have the live reload capability when editing the React.

Render Django frontend view

  • Add the view in ./frontend/views.py :
from django.shortcuts import render

def index(request):
    return render(request, 'frontend/index.html')
  • Then create a template in ./frontend/templates/frontend/index.html :
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Django REST with React</title>
</head>
<body>
<div id="app">
    <!-- React will load here -->
</div>
</body>
{% load static %}
<script src="{% static "frontend/main.js" %}"></script>
</html>
  • Create frontend module URLs :
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index ),
]
  • Register frontend app URL's into the project .settings.py :
urlpatterns = [
  #... others paths
  path('', include('frontend.urls')),
]
  • Finally enable the frontend app in project .settings.py :
INSTALLED_APPS = [
  # omitted for brevity
  'rest_framework',
  'frontend.apps.FrontendConfig', # <-- enable the frontend app
]

Basic React app

  1. Fill ./frontend/src/components/App.js with : https://gist.github.com/mikamboo/1002f2057b4dc38298a6a3cc1a69bc23#file-app-js
  2. Fill ./frontend/src/components/index.js with : https://gist.github.com/mikamboo/1002f2057b4dc38298a6a3cc1a69bc23#file-index-js

Run application

import ReactDOM from "react-dom";
import App from "./components/App";
ReactDOM.render(
<App />,
document.getElementById('app')
);
@mikamboo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment