Tech Incent
django react

How to set up django react together ?

how-to-set-up-django-and-react

In this article, We will set up Django react together with building a business directory or listing application from scratch.

Note: I am using ubuntu terminal or code terminal for creating directory or files with terminal,  Your case may be different.

Before you go to create this project, don’t miss the table of content for the process of the tutorial.

Set up Django for back-end

  1. Create a project directory called ‘blisting’

    $ mkdir blisting && cd $_
  2. Set up the virtual environment

    if virtualenv is not installed in your machine  skip  this  step

    $ pip instll -g virtualenv
    $ virtualenv -p python3.7 venv
    $ source venv/bin/activate   # For linux and Mac
    $ venv/scripts/activate   # For window
  3. Install dependency and  start the project

    you must be in project root ‘blisting’ directory

    $ pip install django pillow
    $ django-admin start project blisting .
    $ python manage.py migrate
    $ python manage.py startapp listNow project look like this base-structure
  4. Install list app and add ‘BusinessList’ model in list/models.py files

    In blisting/settings.py files

    INSTALLED_APPS = [ 
        ... 
        'list', 
        ... 
    ]

    In list/models.py files

    from django.db import models
    from django.contrib.auth import get_user_model
    
    User = get_user_model()
    
    class BusinessList(models.Model):
        create_by = models.ForeignKey(User, on_delete=models.CASCADE)
        name = models.CharField(max_length=200)
        description = models.TextField(blank=True, null=True)
    
        create_at = models.DateTimeField(auto_now=True)
        update_at = models.DateTimeField(auto_now_add=True)
    
        def __str__(self):
            return self.name
  5. Make Migrate business Models

    $ python manage.py makemigrations
    $ python manage.py migrate
  6. Create a superuser

    $ python manage.py createsuperuser
    
    Username (leave blank to use 'pollexe'): admin
    Email address: [email protected]
    Password: 
    Password (again): 
    Superuser created successfully.
  7. Add some business list

    Add register BusinessList model in admin panel

    from django.contrib import admin
    from .models import BusinessList
    
    admin.site.register(BusinessList)

    Go admin panel and add some list
    add-list

Great, we have completed our back end setup.

Set up Back-end API

Django back-end API handles by Django Rest Framework. Django Cors Headers handle API permissions.

  1. Install and config dependencies for Rest-API

    $ pip install djangorestframeowork django-cors-header

    Install app in blisting/settings.py files

    INSTALLED_APPS = [
        ....
        'rest_framework',
        'corsheaders',
    ]

    In “blisting/settings.py” add rest-framework default config

    REST_FRAMEWORK = {
        # Use Django's standard `django.contrib.auth` permissions,
        # or allow read-only access for unauthenticated users.
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
        ],
        ## JSONRender for response only json for rest-api
        # 'DEFAULT_RENDERER_CLASSES': (
        #     'rest_framework.renderers.JSONRenderer',
        # )
    }

    In “blisting/settings.py add middleware for cors headers

    MIDDLEWARE = [ 
        ... 
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware', 
        ... 
    ]
    CORS_ORIGIN_WHITELIST = [
        "http://localhost:3000",
    ]

    Add more cors permission optional. if add this permission make sure, your all API starts with “yourdomain.com/api/**”

    CORS_URLS_REGEX = r'^/api/.*$'
  2. Create serializers.py file in “list” directory

    from rest_framework import serializers
    from django.contrib.auth import get_user_model
    
    from .models import BusinessList
    
    User = get_user_model()
    
    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ('first_name', 'last_name', 'email')
    
    
    class BusinessListSerializer(serializers.ModelSerializer):
        create_by = UserSerializer()
        class Meta:
            model = BusinessList
            fields = [
                'create_by', 'name', 'image', 'description', 'create_at', 'update_at'
            ]

    Edit list/views.py file

    from rest_framework.generics import ListAPIView
    from rest_framework.response import Response
    from rest_framework.permissions import AllowAny
    
    from .models import BusinessList
    from .serializers import BusinessListSerializer
    
    
    class BusinessListApiView(ListAPIView):
        serializer_class = BusinessListSerializer
        permission_classes = [AllowAny]
    
        def get_queryset(self):
            qs = BusinessList.objects.select_related('create_by').all()
            return qs
    
        def list(self, request, *args, **kwargs):
            queryset = self.get_queryset()
            serialize = BusinessListSerializer(self.filter_queryset(queryset), many=True)
            return Response(serialize.data, status=200)
    

     

    Edit add list/urls.py in list directory end edit it.

    from django.urls import path
    from .views import BusinessListApiView
    
    urlpatterns = [
        path('api/business-list', BusinessListApiView.as_view(), name='api_business_list')
    ]

    Edit blisting/urls.py files. it’s the main project 

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('list.urls'))
    ]
    $ python manage.py runserver

    Go to “http://127.0.0.1:8000/api/business-list” URLs
    api-business-list.png

Set up react for front-end

      1. Generate React App

        Make sure you are in the project root ‘blisting’  directory.
        create-react-app with react documentation

        $ npm create react-app frontend
        (venv) ubuntu:~/deploy-django-react-heroku/blisting$ tree -L 2 .
        .
        ├── blisting
        │   ├── asgi.py
        │   ├── __init__.py
        │   ├── __pycache__
        │   ├── settings.py
        │   ├── urls.py
        │   └── wsgi.py
        ├── db.sqlite3
        ├── frontend
        │   ├── node_modules
        │   ├── package.json
        │   ├── public
        │   ├── README.md
        │   ├── src
        │   └── yarn.lock
        ├── list
        │   ├── admin.py
        │   ├── apps.py
        │   ├── __init__.py
        │   ├── migrations
        │   ├── models.py
        │   ├── __pycache__
        │   ├── serializers.py
        │   ├── tests.py
        │   ├── urls.py
        │   └── views.py
        ├── manage.py
        └── venv
            ├── bin
            ├── include
            ├── lib
            └── share
        14 directories, 18 files

         

      2. Add some necessary dependency

        $ npm install react-router-dom axios

        # react-router-dom:  React router dom for routing app pages
        # Axios: HTTP Clint  for node.js with the response promise

      3. Edit App.js file

        import React from 'react';
        import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
        
        import BusinessList from './page/BusinessList';
        import Home from './page/Home'
        
        import './App.css';
        
        
        const styles = {
           container: {
              width: '100%',
              maxWidth: '1170px',
              margin: '0 auto'
           },
           row: { 
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center'
           }
        }
        
        
        function App() {
           return (
              <Router>
                 <div className="App">
                    <header className="App-header">
                       <div className="container" style={styles.container}>
                          <div className="row justify-content-between" style={styles.row}>
                             <Link to="/"><h2>Blisting</h2></Link>
                             <Link to='/list'>Business List</Link>
                          </div>
                       </div>
                    </header>
                    <Switch>
                       <Route path='/list' component={BusinessList} />
                       <Route path="/" exact component={Home} />
                    </Switch>
                 </div>
              </Router>
           );
        }
        
        export default App;
      4. Add src/page/Home.js

        import React, { Component } from 'react';
        import {Link} from 'react-router-dom';
        
        const styles = {
            textCenter: {
                'textAlign': 'center'
            }
        }
        
        class Home extends Component {
            render() {
                return (
                    <div>
                        <h2 style={styles.textCenter}>Hello Creative Developer, Browse <Link to='list'>Business Lists</Link></h2>
                    </div>
                );
            }
        }
        
        export default Home;
      5. Add src/page/BusinessList.js files and edit with this

        We are created an API request function fatchList in BsuinessList.js files.

        import React, { Component } from 'react';
        import axios from 'axios';
        
        
        const fatchList = async () => {
            let protocol = 'http:';
            let loc = window.location;
            if (loc.protocol === 'https:'){
                protocol = 'https:'
            }
            try{
                let {data} = await axios.get(`${protocol}//127.0.0.1:8000/business-list`);
                return data
            } catch(error) {
                //  console.log(error)
                return {error}
            }
        }
        
        const styles = {
            container: {
               width: '100%',
               maxWidth: '1170px',
               margin: '0 auto'
            },
            row: { 
               display: 'flex',
               justifyContent: 'space-between',
               alignItems: 'center',
               flexWrap: 'wrap'
            },
            card: {
                width: '100%',
                maxWidth: '50%'
            },
            textCenter: {
                'textAlign': 'center'
            }
         }
        
        class BusinessList extends Component {
            state = {
                list: {},
                loading: true
            }
            async componentDidMount(){
                let data = await fatchList();
                if(!data.hasOwnProperty('error')){
                    this.setState({list: data, loading: false})
                }
            }
        
            render() {
                const { list, loading } = this.state;
                return (
                    <div>                
                        <h2 style={styles.textCenter}>Business List With API Call</h2>
                        <div style={styles.container}>
                            <div style={styles.row}>
                                {loading ? <div>Loading</div>: (
                                    list.map(({name, create_by}, index) => {
                                        return <div className="card" style={styles.card} key={index}>
                                            <h3>{index}: {name}</h3>
                                            <h5>Create By: { create_by.email}</h5>
                                        </div>
                                    })
                                )}
                            </div>
                        </div>
                    </div>
                );
            }
        }
        
        export default BusinessList;
      6. Run Django server and react server

        $ python manage.py runserver

        make sure you are in ‘blisting/frontend” directory where you are start frontend react server

        $ yarn start

        businesslist

Download Source Code

https://github.com/sajalmia381/django-react-setup/archive/v1.0.tar.gz

Deployment

Django React deployment largely processes with different hosting types. Please check this I made simply deployment in Heroku

Related posts

How to work with django ajax requests ?

Sajal Mia

Django Send Email with AWS Simple Email Service(SES)

Sajal Mia

Django abstractuser with example

Sajal Mia

Leave a Comment