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!

11 comments:

  1. It's very useful blog post with informative and insightful content and i had good experience with this information.I have gone through CRS Info Solutions Home which really nice. Learn more details About Us of CRS info solutions. Here you can see the Courses CRS Info Solutions full list. Find Student Registration page and register now. Go through Blog post of crs info solutions. I just read these Reviews of crs really great. You can now Contact Us of crs info solutions. You enroll for Pega Training at crs info solutions.

    ReplyDelete
  2. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

    Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.


    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.


    The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete
  3. 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
  4. MAJOR168 is open for football betting today. There are many big camps together BTi SBOBET IBCBET CMD365 if you are looking for a football betting website. Do not miss this site, there is football, there are all sports in the world. คาสิโนออนไลน์. Betting is available 24 hours a day with the best odds per pair in Thailand. Guaranteed automatic deposit and withdrawal system 10 seconds.

    Live sports betting Online football betting Good price with every football match open for today online football betting SAGAME88 There are many big camps together, SBOBET IBCBET BTi CMD365, the only website complete in online football betting คาสิโนออนไลน์. There is every sport on the planet in here. With the automatic deposit and withdrawal system for 10 seconds, we have a live football system to watch every night.


    We offer a wide variety of services. Called him the only player to finish with everything else does not have to go to the web preview ufabet as online. Online casinos Baccarat online Online betting games, Slot online, and with new technology, you can play ufabet via mobile phone today. Mobile Baccarat, play online via the website


    Ufabet1688 of us again the way we are websites directly, not through a General Services, where customers will know it absolutely was extremely really no cheating possible on-site gambling online, it is ufabet1688 of us will hit prices.

    ReplyDelete
  5. 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
  6. สล็อตออนไลน์ (Slot Online) คือการนำเครื่องเล่นพนัน ตู้สล็อตแมชชีน ที่กล่าวมาข้างต้นนี้ นำมาทำเป็นเกมอิเล็กทรอนิกส์ที่เรียกกันว่า สล็อตออนไลน์ เนื่องด้วยยุคสมัยพัฒนาคนหันมานิยมเล่นพนันกันผ่านคอมพิวเตอร์ จะได้นำเกมสล็อตมาทำเป็นเกมพนันออนไลน์ ผ่านระบบเครื่อข่ายอินเตอร์เน็ต ซึ่งผู้เล่นสามารถเล่นแบบผ่าน โปรแกรมสล็อต ก็ได้หรือจะเป็นการเข้าเล่น Slots ผ่านหน้าเว็บไซต์ผู้ให้บริการ ซึ่งบริการเกม สล็อตออนไลน์ นั้นก็มีรูปแบบของกติกาการเล่น คล้ายกันกับการเล่นบนตู้สล็อตแมชชีน ทั้งภาพและเสียงสมจริงเร้าใจไม่แพ้กันกับไปนั่งเล่นในคาสิโนเลยทีเดียว.

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

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

    ReplyDelete
  11. บาคาร่าออนไลน์ ถือว่าเป็น เว็บบาคาร่าออนไลน์ ที่นอกจากทำการรวบรวมเหล่า เกมคาสิโนออนไลน์ที่ดีที่สุด 2021 ทุกรูปแบบที่มีแล้วนั้น ทางเว็บเรา ยังพร้อมมอบสิทธิพิเศษ และผลประโยชน์ต่าง ๆ มากมาย เพื่อคืนกำไร และเอื้อสิทธิผลประโยชน์ที่ผู้เล่นควรได้รับ ไม่ว่าจะเป็นสมาชิกเก่าหรือใหม่ก็ตาม อาทิเช่น โปรโมชั่นแรกเข้า 30% ทันที โปรโมชั่นแนะนำเพื่อนรับ 20% และ โปรโมชั่นคืนยอดเสียที่ผู้เล่นสามารถกดรับได้ในทุก ๆ เดือน 5 % อีกทั้งทางเว็บไซต์ยังได้พัฒนาระบบทางการเงิน เข้าสู่รูปแบบออโต้ หรืออัตโนมัติ เพื่อความปลอดภัยและมั่นคงในธุรกรรมทางการเงินของเหล่าสมาชิก รวมไปถึงการให้บริการติดต่อสอบถามตลอด 24 ชม. กับทีมงานเจ้าหน้าที่มืออาชีพ บาทคาร่าออนไลน์ ที่พร้อมให้คำปรึกษาด้วยเช่นกันนั่นเอง.

    ReplyDelete