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
-
Create a project directory called ‘blisting’
$ mkdir blisting && cd $_
-
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
-
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 list
Now project look like this -
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
-
Make Migrate business Models
$ python manage.py makemigrations
$ python manage.py migrate -
Create a superuser
$ python manage.py createsuperuser Username (leave blank to use 'pollexe'): admin Email address: [email protected] Password: Password (again): Superuser created successfully.
-
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
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.
-
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/.*$'
-
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
Set up react for front-end
-
-
-
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
-
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 -
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;
-
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;
-
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;
-
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
-
-
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
21 comments
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
Pretty! This was a really wonderful post. Thank yoou for supplying this info. Ina Yehudit Lombardo
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
Thank you ever so for you article. Really thank you! Really Great. Korry Cesare Gorey
I am truly glad to read this web site posts which contains plenty of helpful information, thanks for providing such statistics. Aleen Arman Yurt
Very nice article, learnt a lot, I have. The future of machine learning, these algorithms are. With you force be. Anstice Payton Spaulding
Your style is so unique compared to other folks I have read stuff from. Jewell Arney Harvison
Hiya very cool web site!! Man .. Excellent .. Superb .. Jazmin Sansone Clorinda
I conceive you have observed some very interesting details, regards for the post. Elana Jarrid Amero
Thanks again for the article post. Really thank you! Awesome. Gavrielle Brandtr Shoemaker
Hi there, its pleasant article concerning media print, we all know media is a
fantastic source of data.
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!
Its good as your other content :D, regards for putting up. Jessie Ennis Zhang
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.
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
Paragraph writing is also a excitement, if you be acquainted with afterward you
can write otherwise it is difficult to write.
What’s up, I read your blogs daily. Your story-telling
style is awesome, keep doing what you’re doing!
“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
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
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
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.