Sunday, July 26, 2020

How I Made the Django React and Redux Blog

How I Made the Django React Blog


In this blog, I will show you how I made a Blog website with Django, React, and Redux.

Source Code: Github

 

Before starting I want to talk about What is Django, What is React Js and What is Redux.

 

What is Django?

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. Django was designed to help developers take applications from concept to completion as quickly as possible. Django includes dozens of extras you can use to handle common Web development tasks. Django takes care of user authentication, content administration, site maps, RSS feeds, and many more tasks — right out of the box. Django takes security seriously and helps developers avoid many common security mistakes, such as SQL injection, cross-site scripting, cross-site request forgery, and clickjacking. Its user authentication system provides a secure way to manage user accounts and passwords. Some of the busiest sites on the planet use Django’s ability to quickly and flexibly scale to meet the heaviest traffic demands. (from Django Docs)

 

What is React Js?

A JavaScript library for building user interfaces React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable and easier to debug. Build encapsulated components that manage their own state, then compose them to make complex UIs. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep the state out of the DOM. We don’t make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting the existing code.

 

A Simple Component

React components implement a render() method that takes input data and returns what to display. This example uses an XML-like syntax called JSX. Input data that is passed into the component can be accessed by render() via this.props.

class App extends React.Component {

render() {

return (

<div>

Hello {this.props.name}

</div>

);

}

}

ReactDOM.render(

<App name=”Subham” />,

document.getElementById(‘hello-example’)

);

 

Output:

Hello Subham

 

What is Redux?

A Predictable State Container for JS Apps. Redux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Centralizing your application’s state and logic enables powerful capabilities like undo/redo, state persistence, and much more. The Redux DevTools make it easy to trace when, where, why, and how your application’s state changed. Redux’s architecture lets you log changes, use “time-travel debugging”, and even send complete error reports to a server. Redux works with any UI layer and has a large ecosystem of add-ons to fit your needs.

 

Setup the Project Folder

 

 

Frontend (React Js)

Go to frontend folder and open our Command Prompt (Terminal for Mac and Linux). And type

npx create-react-app <app_name>

 (for npx you need node. Download node here)

After download Node, you will have npm the NODE PACKAGE MANAGER. With the help of npm we can install the dependencies.

Then go to your project folder:

Cd <app_name>

Now need to install dependencies.

npm i axios // for network requests

npm i react-router-dom // routing (Navigation)

npm install react-redux // Using the Redux

npm i react-html-parser // for converting HTML strings into React components (Backend to Frontend)

npm i redux-thunk // For middleware

 

Frontend Folder Structure

 


Node_module => It has all node modules which we will use.

Public => It has the public files like Html, favicon.ico etc

Src => This is the main folder where we will work

package.json => It has the packages which we installed previously.

 

In src folder



Ultimate Folder Structure (Frontend)

 


Frontend Routes (Web Routes)


In route.js

import React from 'react'

import { Route } from 'react-router-dom'

import ArticleListView from './containers/ArticleListView'

import ArticleDetails from './containers/ArticleDetailsView'

import CustomForm from './components/CreateUpdateForm'

import Signup from './components/Signup'

import Signin from './components/Signin'

import Search from './components/Search'

import About from './containers/About'

import Contact from './containers/Contact'

 

export default function BaseRoute() {

    return (

        <div>

            <Route exact path="/" component={ArticleListView} />

            <Route path="/post/:slug/" component={ArticleDetails} />

            <Route path="/create/" component={CustomForm} />

            <Route path="/post/update/:articleId/" component={CustomForm} />

            <Route path="/signup/" component={Signup} />

            <Route path="/signin/" component={Signin} />

            <Route path="/search/:query/" component={Search} />

            <Route path="/about/" component={About} />

            <Route path="/contact/" component={Contact} />

        </div>

    )

}

 


Send Data From Front End(React js) to Backend (Django)

 

Container/ArticleListView.js

 

    state = {

        articles : [],

        dateTime : []

    }

 

    componentDidMount(){

        Axios.get('http://127.0.0.1:8000/api/allpost/')

        .then((res)=>{

            console.log(res.data.message);

            const timeAndDateArr = []

            res.data.data.map((item)=>{

 

                let a = item.created_at

                let date_time = a.split("T")

 

                let date = date_time[0].split("-")

                let year = date[0]

                let month = date[1]

                let day = date[2]

 

                date = `${day}-${month}-${year}`

                var H = +date_time[1].substr(02);

                var h = H % 12 || 12;

                var ampm = (H < 12 || H === 24? "AM" : "PM";

                var timeString = h + date_time[1].substr(23+ ampm;

 

                let obj = {

                    time: timeString,

                    date: date

                }

 

                timeAndDateArr.push(obj)

 

            })

 

            console.log(timeAndDateArr);

 

            this.setState({

                articles : res.data.data,

                dateTime : timeAndDateArr

            })

        })

    }

 

 

Backend (Django)

 

Folder Structure

 


Create Environment

pip install --user virtualenv

 

Activate the Virtual Environment

.\env\Scripts\activate //windows

source env/bin/activate //macOs and Linux

 

Create the Django Project

django-admin startproject blog_api

cd blog_api

 


Run the Server

python manage.py runserver

 

Backend API End Points (API Routes)

Blog_api/urls.py (Main Routes)

from django.contrib import admin

from django.urls import path, include

from django.conf import settings

from django.conf.urls.static import static

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('api/'include('blog.urls')),

    path('api/account/'include('account.urls')),

]+ static(settings.MEDIA_URLdocument_root=settings.MEDIA_ROOT+ static(settings.STATIC_URLdocument_root=settings.STATIC_ROOT)

 

 

blog/urls.py (Blog app è python manage.py startapp blog)

from django.contrib import admin

from django.urls import path, include

from blog import views

 

urlpatterns = [

    path('allpost/', views.allpost, name='allpost'),

    path('addarticle/', views.addArticle, name='addarticle'),

    path('update/<int:id>/', views.update_article, name='update'),

    path('post/<slug:slug>/', views.articleDetails, name='articleDetails'),

    path('search/', views.search, name='search'),

    path('addcomment/', views.addcomment, name='addcomment'),

    path('fetchcomments/', views.fetchAllComments, name='fetchAllComments'),

]

 

 

account/urls.py (For Login Functionality)

from django.contrib import admin

from django.urls import path, include

from account import views

 

urlpatterns = [

    path('signup/', views.signup, name='signup'),

    path('signin/', views.signin, name='signin'),

]

 

Install Apps in Django


Blog_api/ settings.py

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

 

    'corsheaders',

 

    'blog',

    'account',

]

 

 

Middleware

 MIDDLEWARE = [

    'corsheaders.middleware.CorsMiddleware',

    'django.middleware.security.SecurityMiddleware',

    'django.contrib.sessions.middleware.SessionMiddleware',

    'django.middleware.common.CommonMiddleware',

    'django.middleware.csrf.CsrfViewMiddleware',

    'django.contrib.auth.middleware.AuthenticationMiddleware',

    'django.contrib.messages.middleware.MessageMiddleware',

    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

 

 

Receive the Data From Front End to Back End

def articleDetails(requestslug):

    try:

        # print(id)

        articleDetails = Article.objects.filter(slug=slug)

        if len(articleDetails) == 0:

            return JsonResponse({'err':'true''message':'Article Not Found'})

        else:

            # print(articleDetails.values())

            details = list(articleDetails.values())

            return JsonResponse({'err':'false''message':'Article Found''data':details})

    except Exception as err:

        errMessage = f"Oops! {sys.exc_info()[1]}"

        return JsonResponse({'err':'true''message' : errMessage})

 

API Documentation

http://127.0.0.1:8000/api/allpost/ (GET è Fetch All Posts)

http://127.0.0.1:8000/api/post/<slug>/ (GET è Get the Particular Post Details)

http://127.0.0.1:8000/api/account/signup/ (POST è User Sign Up)

body è {

    "first_name" : "Subham",

    "last_name" : "Roy",

    "email" : "shubham021@gmail.com",

    "username" : "subham",

    "phone" : "121526412",

    "password" : "nopass"

}

 

http://127.0.0.1:8000/api/account/signin/ (POST è User Sign In)

body è {

    "username" : "subham",

    "password" : "nopass"

}

 

http://127.0.0.1:8000/api/search/ (GET è Search Post)

http://127.0.0.1:8000/api/addcomment/ (POST è Add the Comments in Posts)

body è {

    "comment" : "new comment"

}

 

http://127.0.0.1:8000/api/fetchcomments/ (GET è Fetch Comments)

 

Django with React: conclusions

In this the tutorial we built a simple Django and React project.

Feel free to experiment by adding more features to the project (like authentication).

The approach we took when connecting the React frontend to Django was a bit simplistic, but represent a strong foundation of what you'll do in the real world.

Thanks for reading!

5 comments:

  1. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Data Science Course Hyderabad

    ReplyDelete
  2. Along with it also has a live casino 24 hours a day. สมัคร ufa Bet online gambling website is available to play with all casinos, baccarat, slots, roulette, dice and many other card games. We have gathered it here. With many promotions Apply for UEFA Bet now, we are happy to serve you all. With a professional team ready to solve problems And serve all of you There is a team to support the service. And answer your questions 24 hours a day.

    ReplyDelete
  3. If you are looking for a good website, ufa, UEFA BET casino site. Which can be played as a complete solution, able to answer Both in terms of quality and performance that are quite diverse It is best to have a lot of these things.

    ReplyDelete
  4. ufabet Parent company, the most popular online gambling website, whether it is online football betting Online casinos Baccarat online All of them were not less popular than each other. Become a member of UEFA Bet Playing with the parent company Did not pass agent Bet on a variety of casino games Especially the gambler who likes to Online football betting Our website provides 4 football odds, football betting, a minimum of 10 baht , betting is easy

    ReplyDelete
  5. แทงบอล กับ i99CLUB เว็บแทงบอล ที่ตอบโจทย์ให้กับคุณได้อย่างดีเยี่ยมที่สุด เท่าที่จะเป็นไปได้แล้วก็บอกได้เลยว่าการทำเงินตรงจุดนี้ เป็นอีกหนึ่งทางเลือกที่ข้างๆ ที่จะการันตีได้อย่างชัดเจนแล้วว่า เป็นสิ่งที่ดีที่สุดและทรงประสิทธิภาพมากที่สุด เท่าที่จะเป็นไปได้และเชื่อได้เลยว่า มันจะเป็นอีกหนึ่งตัวเลือกที่พร้อมจะเปิดกว้างให้กับคุณได้ อย่างมั่นคงและทรงประสิทธิภาพมากที่สุด

    ReplyDelete