Tech Incent
DjangoReact

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 add bootstrap in react?

Tech Incent

How to create Django form?

Sajal Mia

Django Send Email with AWS Simple Email Service(SES)

Sajal Mia

Understanding Django and django design principles

Tech Incent

How to optimize your Django application for more speed with ORM?

Sajal Mia

How to work with django ajax requests ?

Sajal Mia

21 comments

altyazili 19/12/2020 at 5:50 PM

Way cool! Some very valid points! I appreciate you writing this post and also the rest of the website is really good. Sileas Dino Pentheas

turkce 19/12/2020 at 8:53 PM

Pretty! This was a really wonderful post. Thank yoou for supplying this info. Ina Yehudit Lombardo

altyazili 20/12/2020 at 1:25 AM

Way cool! Some extremely valid points! I appreciate you penning this post and also the rest of the site is very good. Nickie Quincy Filia

720p 20/12/2020 at 3:53 AM

Thank you ever so for you article. Really thank you! Really Great. Korry Cesare Gorey

ucretsiz 20/12/2020 at 5:30 AM

I am truly glad to read this web site posts which contains plenty of helpful information, thanks for providing such statistics. Aleen Arman Yurt

ucretsiz 23/12/2020 at 6:54 AM

Very nice article, learnt a lot, I have. The future of machine learning, these algorithms are. With you force be. Anstice Payton Spaulding

bedava 23/12/2020 at 8:48 AM

Your style is so unique compared to other folks I have read stuff from. Jewell Arney Harvison

bedava 23/12/2020 at 10:31 AM

Hiya very cool web site!! Man .. Excellent .. Superb .. Jazmin Sansone Clorinda

yify 23/12/2020 at 12:06 PM

I conceive you have observed some very interesting details, regards for the post. Elana Jarrid Amero

yify 24/12/2020 at 4:13 AM

Thanks again for the article post. Really thank you! Awesome. Gavrielle Brandtr Shoemaker

cheap flights 29/01/2021 at 4:42 AM

Hi there, its pleasant article concerning media print, we all know media is a
fantastic source of data.

cheap flights 29/01/2021 at 11:12 AM

Heya! I’m at work browsing your blog from my new apple iphone!
Just wanted to say I love reading your blog and look forward to all your posts!
Keep up the great work!

avengers endgame izle 29/01/2021 at 3:14 PM

Its good as your other content :D, regards for putting up. Jessie Ennis Zhang

cheap flights 29/01/2021 at 9:13 PM

It’s remarkable to visit this site and reading the views of all colleagues about this paragraph, while I am also eager of getting experience.

dublaj 30/01/2021 at 12:56 AM

Howdy! I simply want to offer you a big thumbs up for the great info you have here on this post. I am coming back to your website for more soon. Nydia Chrotoem Fanchette

cheap flights 30/01/2021 at 7:59 AM

Paragraph writing is also a excitement, if you be acquainted with afterward you
can write otherwise it is difficult to write.

tuvalet kabin 29/03/2021 at 7:39 PM

What’s up, I read your blogs daily. Your story-telling
style is awesome, keep doing what you’re doing!

דירות דיסקרטיות בחיפה 05/04/2021 at 8:33 AM

“Nice post. I learn something new and challenging on sites I stumbleupon every day. It will always be interesting to read content from other authors and use something from their websites.”
456854

0mniartist 09/04/2021 at 5:51 AM

fantastic issues altogether, you simply won a new reader.
What could you suggest about your post that you made
some days ago? Any positive? 0mniartist asmr

0mniartist 09/04/2021 at 1:30 PM

It’s very simple to find out any matter on web as compared to books, as
I found this paragraph at this website. 0mniartist asmr

cnc manufacturing services 27/04/2021 at 9:13 PM

Simply wish to say your article is as astonishing.
The clearness in your post is just great and i can assume you’re
an expert on this subject. Fine with your permission allow me to
grab your RSS feed to keep up to date with forthcoming post.
Thanks a million and please keep up the gratifying work.

Comments are closed.