I'm working on a small application using Vue.js and Django on Digitalocean, so I have installed Django Webpack loader and the tracker also, now I have executed my Django server and my vue.js also using npm run serve and when I access to my webpage localhost:8000 I see only a blank page since everything is installed correctly, This is my HTML page ( when I inspect on chrome browser )
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="http://0.0.0.0:8080/js/app.js"></script>
</body>
</html>
PS : i think the problem is in app.js ( because i follow the link and i get an error )
This site can’t be reachedThe webpage at http://0.0.0.0:8080/js/app.js might be temporarily down or it may have moved permanently to a new web address.
ERR_ADDRESS_INVALID
you should config your vue application first creating vue.config.js file.
vue.config.js:
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
// on Windows you might want to set publicPath: "http://127.0.0.1:8080/"
publicPath: "http://0.0.0.0:8080/",
outputDir: "./dist/",
chainWebpack: (config) => {
config
.plugin("BundleTracker")
.use(BundleTracker, [{ filename: "./webpack-stats.json" }]);
config.output.filename("bundle.js");
config.optimization.splitChunks(false);
config.resolve.alias.set("__STATIC__", "static");
config.devServer
// the first 3 lines of the following code have been added to the configuration
.public("http://127.0.0.1:8080")
.host("127.0.0.1")
.port(8080)
.hotOnly(true)
.watchOptions({ poll: 1000 })
.https(false)
.disableHostCheck(true)
.headers({ "Access-Control-Allow-Origin": ["*"] });
}
// uncomment before executing 'npm run build'
// css: {
// extract: {
// filename: 'bundle.css',
// chunkFilename: 'bundle.css',
// },
// }
};
Then load render_bundle from webpack_loader. Your django template will be like:
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- This part is in the screenshot at the bottom! -->
<h1>Vue JS</h1>
<div id="app"></div>
{% render_bundle 'app' %}
</body>
</html>
Make Sure you are using webpack-bundle-tracker of version #0.4.3
You can follow this link for step by step tutorial.
Related
Is it possible to include snippets of shared HTML using Vite (vanilla)? I'm looking for a way to have the HTML prerendered without injecting via JS.
Something like:
<html>
<head>
{ include 'meta-tags' }
</head>
<body>
{ include 'nav' }
<h1>Hello World</h1>
<body>
</html>
vite-plugin-handlebars was the solution I was looking for. Partials were super easy to set up with this package:
Setup:
// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';
export default {
plugins: [
handlebars({
partialDirectory: resolve(__dirname, 'partials'),
}),
],
};
File where you want to include partial:
<!-- index.html -->
{{> header }}
<h1>The Main Page</h1>
Rendered output:
<header>My Website</header>
<h1>The Main Page</h1>
You could use the vite-plugin-html that enables EJS templates in index.html:
// vite.config.js
import { defineConfig } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
plugins: [
createHtmlPlugin({
entry: 'main.js',
/**
* Data that needs to be injected into the index.html ejs template
*/
inject: {
data: {
metaTags: `<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />`,
nav: `<nav>
Google |
Apple
</nav>`,
},
},
}),
],
})
<!-- index.html -->
<html>
<head>
<%- metaTags %>
</head>
<body>
<%- nav %>
<h1>Hello World</h1>
<body>
</html>
demo
I am wanting to host an Angular 6 application in Django, how do I do this?
Integrating Angular 8 and django 2.2
Used Visual Studio for Django 2.2 and Visual Studio Code for Angular 8
I tweaked the above solution and it ultimately worked. devised a simpler solution using some additional references (listed at the end) on top of the above solution.
Assuming:
angular is setup at: example/angular
django is setup at: example/django
Distribute angular files directly to django static folder
This is #1 key, the rest is glue (somewhat ugly) code to stitch the frameworks together as painless as possible.
At the console:
cd example/angular
ng build --prod --output-path ..\django\mysite\mysite\app\static\angular --output-hashing none --watch
Check Angular/CLI for command line switches and their use, the key here that the output of angular compilation goes directly to Django, no need for a middle man.
Maintain independent FE and BE for development and testing
Note: this is optional, you could "ruin" your angular development environment and put all django tags and attributes directly in angular, at the cost of losing FE - BE independence.
The index.html distributed in angular cannot be used "as is" in Django.
Here is such an example call it angular.html:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mysite</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="{% static 'angular/favicon.ico' %}">
<link rel="stylesheet" href="{% static 'angular/styles.css' %}">
</head>
<body>
<app-root></app-root>
<script src="{% static 'angular/runtime.js' %}"></script>
<script src="{% static 'angular/polyfills-es5.js' %}"></script>
<script src="{% static 'angular/polyfills.js' %}"></script>
<script src="{% static 'angular/main.js' %}"></script>
</body>
</html>
Note: using only Django native language
Serve it in django like any other html
What else
Two way routing between django and angular
Sharing packages like bootstrap
Strongly recommend django-rest-frame-work as a starting point
BUILDING A WEB APP WITH ANGULAR, DJANGO AND DJANGO REST a more complex example putting it all together, I would keep the above simplified django and angular gluing mechanism.
angular8 django
Assumption: That django site is already running
Things needed to set up Angular 6 locally
Install Node Js.
https://nodejs.org/en/download/
Install Angular cli Globally
npm install -g #angular/cli
Navigate to angular on the repo
dir\angular
Install the npm's [libraries]
npm install
Serve the site
npm serve [-o]
Navigate to the hosted site
http://localhost:4200/
Angular Libraries needed to support Django
npm install #angular-devkit/custom-webpack --save
npm install #angular-builders/custom-webpack --save
npm install webpack-bundle-tracker --save
Django Libraries needed to support Angular
pip install django-webpack-loader
File Architecture - I put my angular project within the djangodir off root
root > djangodir > angular
root > djangodir > static
root > djangodir > templates
root > djangodir > webpack-stats-angular.json
Set Up Angular for Django
1) Alter angular.json to include custom webpack config and change build type to builder
"architect": {
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
},
"outputPath": "../static/angular",
2) extra-webpack.config.js code
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
plugins:[
new BundleTracker({filename: '../webpack-stats-angular.json'})
],
output: {
path: require('path').resolve('../static/angular'),
filename: "[name]-[hash].js"
}
};
Set Up Django for Angular
1) settings.py - added webpack_loader to installed_apps
INSTALLED_APPS = [
'webpack_loader'
]
2) settings.py - added webpack_loader
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'angular/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-angular.json'),
}
}
3) requirements.txt - We have a script that pulls from a text file to include dependencies - to this we add
django-webpack-loader==0.6.0
4) urls.py - set up the init routing to the hello world angular app
from . import views as djangodir_views
urlpatterns = [
# path('', include(router.urls)),
path('', djangodir_views.serve_angular, name='serve_angular')
]
5) views.py - include url path
def serve_angular(request):
return render(request, 'angular.html')
Angular.html Page:
{% load render_bundle from webpack_loader %}
<!doctype html>
<html lang="en">
<head>
<base href="/">
<title>Angular/TypeScript Hello World Project</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Angular Hello World Starter">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<!-- <link href="assets/styles/styles.css" rel="stylesheet" /> -->
</head>
<body>
<header class="navbar navbar-inner navbar-fixed-top">
<nav class="container">
<div class="navbar-header">
<span class="app-title"></span>
</div>
</nav>
</header>
<main class="container">
<app-root>
Loading...
</app-root>
<br /><br />
</main>
<footer>
<div class="navbar navbar-fixed-bottom">
<div class="navbar-inner footer">
<div class="container">
<footer>
</footer>
</div>
</div>
</div>
</footer>
{% render_bundle 'runtime' %}
{% render_bundle 'polyfills' %}
{% render_bundle 'styles' %}
{% render_bundle 'vendor' %}
{% render_bundle 'main' %}
</html>
References:
Angular 6|5 Tutorial: Integrating Angular with Django
Customizing Angular CLI 6 build — an alternative to ng eject
Evolving your Django frontend
Angular Hello World Example used
Routing:
In order for angular routing to work, you must
1) app-routing.module.ts - Add the routing to angular
const routes: Routes = [
{ path: '', component: TestComponent, data: { title: 'Home' }},
{ path: 'test', component: Test2Component, data: { title: 'Test' }}
];
2) urls.py - Add the routing to Django - just point it to the same view
urlpatterns = [
path('', djangodir_views.serve_angular, name='serve_angular'),
path('test', djangodir_views.serve_angular, name='serve_angular')
]
So, I've got 3 questions
How to use Django's URLs in react
EXAMPLE:
index.js (in react)
<Router>
<div>
<nav className="navbar navbar-inverse bg-inverse">
<div className="container">
<Link to="/" className="navbar-brand">PetFinder</Link>
<Link to="/storage" className="navbar-brand">Storage </Link>
Sign-Up <== like this
</div>
</nav>
<Route exact path={"/"} component={PetRegistration} />
<Route path={"/storage"} render={() => <Storage ids={checkingName} />} />
</div>
</Router>
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
#path('api-auth/', include('rest_framework.urls', namespace="rest_framework")),
path('api/animals/', include('petsite.urls', namespace='petsite')),
path('api/user_info', core_views.UserInfo.as_view()),
path('signup/', core_views.signup, name='signup'),
path('', csrf_exempt(core_views.index), name='index'),
path(r'^login/$', auth_views.login, name='login'),
]
is_authenticated in react
How I did it:
In index.html
I wrote this ******. I am ashamed of this. Don't judge me, okay just a bit...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div class="signUpBlock">
Sign-Up
</div>
<div id="root">
</div>
<span class="currentUser" style="display: none">{{user.id}}</span>
<span class="currentUserName" style="display: none">{{user.username}}</span>
<span id="DJANGO_USER" style="display: none"></span>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script type="text/javascript">
var WHETHER_DJANGO_USER_IS_AUTH = "{{user.is_authenticated|yesno:"true,false"}}";
document.getElementById("DJANGO_USER").innerHTML = WHETHER_DJANGO_USER_IS_AUTH;
</script>
</body>
</html>
Check the code below:
<script type="text/javascript">
var WHETHER_DJANGO_USER_IS_AUTH = "{{user.is_authenticated|yesno:"true,false"}}";
document.getElementById("DJANGO_USER").innerHTML = WHETHER_DJANGO_USER_IS_AUTH;
</script>
<span id="DJANGO_USER" style="display: none"></span>
AND THEN IN index.js I do this
let boolButString = $('#DJANGO_USER').text()
var StringToBool = (boolButString === 'true');
If StringToBool = true I do smth (means that user is logged in)
else StringToBool != true I do smth (means that user is not logged in)
if (StringToBool) {
do smth
} else {
make some tea for him
}
I don't think I did it in a right way can you suggest me smth?
Is it real to check whether a user is auth. or not?
How to display Django context in react.
You might have seen how I did it in index.html
As usual, I wrote:
def index(request):
return render(request, 'index.html', {
"user" : request.user,
})
end then
<span class="currentUser" style="display: none">{{user.id}}</span>
grab data through jquery and display it in react app.
What can you suggest me?
How to display context properly?
Sry for cups.
I'm trying to use signalR in ionic 2 app .For signalR im using
ms-signalr-client library.
Index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>Ionic App</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#4e8ef7">
<!-- cordova.js required for cordova apps -->
<script src="cordova.js"></script>
<!-- un-comment this code to enable service worker
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(() => console.log('service worker installed'))
.catch(err => console.log('Error', err));
}
</script>-->
<link href="build/main.css" rel="stylesheet">
</head>
<body>
<!-- Ionic's root component and where the app will load -->
<ion-app></ion-app>
<!-- The polyfills js is generated during the build process -->
<script src="build/polyfills.js"></script>
<script src="build/main.js"></script>
<!-- The bundle js is generated during the build process -->
<!-- Zone.js and Reflect-metadata -->
<script src="build/js/Reflect.js"></script>
<script src="build/js/zone.js"></script>
<!--Below added jquery and signal-->
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../jquery.signalR.js"></script>
</body>
</html>
Using here
import { Injectable } from '#angular/core';
import $ from 'jquery';
import 'ms-signalr-client';
import 'rxjs/Rx';
#Injectable()
export class SignalRService {
connection: hubConnection;
hubProxy:any;
constructor() {
}
startConnection() {
console.log("Stage 1");
this.connection =$.hubConnection('http://192.168.0.213:9000');//Server Deployed
console.log("Stage 2");
this.hubProxy = this.connection.createHubProxy('broadcaster');
console.log("Stage 3");
this.connection.start({ jsonp: true })
.done(() => {
console.log('Now connected, connection ID=' + this.connection.id);
})
.fail((err) => {
console.log('Could not connect');
});
}
}
But this error appear every time. I have search but didn't find any solution.
Uncaught Error: jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.
Note: I have tired this library as well but it has an issue .
Issue:Ionic 2 signalr is not connecting with hub
In reference to this Ng2-signalr .I just copy code and its working fine now .
import 'expose-loader?jQuery!jquery';
import '../node_modules/signalr/jquery.signalR.js';
The only way I get it to work is by adding such code to the top of a vendors file:
import 'expose-loader?$!expose-loader?jQuery!jquery';
import './node_modules/signalr/jquery.signalR.min.js';
jQuery should be available globally through aliases that's why I use explose-loader import together with ProvidePlugin in webpack config:
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
Please note, you can use jQuery version 2 or above for signalR.
Hope this will help.
I followed angular2 tutorial https://angular.io/docs/ts/latest/tutorial/.
I didnt want it run under node.js lite-server, but under django.
I managed to finish it and its working BUT: everytime I import any angular module eg. in index.html:
System.import('static/dist/js/main')
.then(null, console.error.bind(console));
or in main.ts:
import {AppComponent} from './app.component'
or everywhere, javascript application is trying to load some js resource like static/dist/js/main file which doesnt exist of course, because the compiled file is named main.js not main.
When I add the extensions '.js' like:
System.import('static/dist/js/main.js')
.then(null, console.error.bind(console));
or
import {AppComponent} from './app.component.js'
It suddenly works, but ts to js compiler (npm run tsc) is throwing error (even throught its compiling) and my IDE is underlining imports as errors.
This is my full index.html:
{% verbatim %}
<html>
<head>
<base href="/">
<title>Angular 2 QuickStart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- IE required polyfills, in this exact order -->
<script src="static/node_modules/es6-shim/es6-shim.min.js"></script>
<script src="static/node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="static/node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="static/node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="static/node_modules/systemjs/dist/system.src.js"></script>
<script src="static/node_modules/rxjs/bundles/Rx.js"></script>
<script src="static/node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="static/node_modules/angular2/bundles/router.dev.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('static/dist/js/main')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
{% endverbatim %}
I checked this Angular2 Typescript app throws 404 on components when js extension not specified but it didnt helped me.
Does anyone have an idea, please?
Assuming you have configured tsc to output your code to the 'static/dist/js' folder you should be able to configure Systemjs like this:
<script>
System.defaultJSExtensions = true;
System.config({
baseURL: "./static/dist/js"
});
System.import("main")
</script>