secure react.js, django, webpack, babel config with dynamic output without DRF (Part II)
Email: m2khosravizadeh@gmail.com
In the previouse part I write about "Configuring Django2 with React.js by webpack4".
in this section I write about "secure react django webpack config with dynamic output without Django Rest Framework".
in django settings.py:
MEDIA_ROOT is the folder where files uploaded using FileField will go.
STATIC_ROOT is the folder where static files will be stored after using manage.py collectstatic.
STATICFILES_DIRS is the list of folders where Django will search for additional static files aside from the static folder of each app installed.
so in setting.py we have:
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
],
},
},
]
STATIC_URL = '/static/'
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
}
}
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static/bundles')
craete new app in your Django project main root:
python3.6 manage.py startapp newTakjoyApp cd newTakjoyApp
in model.py:
nano model.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
ctrl + x
in urls.py:
nano urls.py
from django.urls import path
from . import views
urlpatterns = [
path('questions/', views.PollQuestions.as_view(), name='questions')
]
ctrl + x
and finally in views.py:
from django.shortcuts import render
from django.views import View
from .models import Question
def index(request):
return render(request, 'takjoyTemplate/question.html', {})
class PollQuestions(View):
title = "Questions"
template = 'takjoyTemplate/question.html'
def get(self, request):
questions = list(Question.objects.values('pk', 'question_text'))
context = {
'question_text': self.title,
'props': questions,
}
return render(request, self.template, context)
in templates folder:
cd ../templates
make takjoyTemplate direction:
mkdir takjoyTemplate
in takjoyTemplate, create question html file:
nano takjoyTemplate/question.html
in this file:
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>changes</title>
</head>
<body>
<h1>Questions</h1>
<div>{{ props|safe }}</div>
<div id="react"></div>
<script>
window.props = {{ props|safe }};
window.react_mount = document.getElementById('react');
</script>
{% render_bundle 'question' %}
</body>
</html>
in project app:
cd ../takjoySite
in settings.py:
nano settings.py
INSTALLED_APPS = [
...
'newTakjoyApp.apps.NewtakjoyappConfig',
]
press ctrl + x and exit.
in urls.py:
nano urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('questions/', include('inventory.urls')),
]
in main project root open react.js file direction:
cd assets
create new .jsx file:
nano question.jsx
in this file:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Test extends React.Component {
render() {
var list = window.props;
return (<div><div>test accepted!!!</div>{list.map(item => <TestChild key={item.pk}
question={item.question_text}/> )}</div>);
}
}
class TestChild extends React.Component {
render() {
return <li><b>{this.props.question}</b></li>;
}
}
ReactDOM.render(
<Test/>,
window.react_mount,
);
in webpack.config.js:
nano webpack.config.js
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
context: __dirname,
entry: {'question': './assets/js/question',
'body': './assets/js/body'},
mode: 'production',
output: {
path: path.resolve('./assets/bundles'),
filename: "[name]-[hash].js",
},
plugins: [
new HtmlWebPackPlugin({
hash: true,
filename: "index.html", //target html
template: "./assets/src/public/index.html" //source html
}),
/*new ExtractTextPlugin({ filename: 'css/style.css' }),*/
new BundleTracker({filename: './webpack-stats.json'}),
new MiniCssExtractPlugin({filename: '[name]-[hash].css'}),
],
module: {
rules: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.css$/, loader: ['style-loader', 'css-loader'] },
{ test: /\.(sass|scss)$/, use: [MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 2, sourceMap: true }},
{ loader: 'postcss-loader', options: { plugins: () => [ require('autoprefixer') ], sourceMap: true }},
{ loader: 'sass-loader', options: { sourceMap: true }}
]
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx']
}
}
now config webpack:
sudo ./node_modules/.bin/webpack --config webpack.config.js --watch
ok? press ctrl + c
then run:
python3.6 manage.py migrate python3.6 manage.py makemigrations python3.6 manage.py collectstatic python3.6 manage.py runserver 0.0.0.0:8080
then check your ip:8080.