How to host Angular 6 application in Python Django? - django

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')
]

Related

How to render Vue with Django

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.

Django with vue.js frontend - Static Files Path

I am attempting to serve a django app with a vue frontend and need some help configuring the static files.
The Question TLDR:
How do I get Django to recognize this built path as an attempt to reach a static file, or alternatively, how do I modify the post-build injection path on the Vue side to match the current Django static-file settings?
Django serves the built index.html from vue, however it can not find the static files (scripts/css) that are autoinjected from the build process due to the path being "absolute". I have modified the vue.config.js to not autoinject the scripts (since they will need {% static %} during the build, and the template index.html to add them in appropriately.
My directory structure is as follows:
- Root
- app
- migrations
- templates
- app (outputDir)
- index.html (Built from vue)
- base.html
- templateFolder1
- templateFolder2
- various .py files
- assets (assetsDir)
- css
- static files
- js
- static files
- frontend
- public
- index.html (Template for build for vue)
- src
- assets
- components
- App.vue
- main.js
The build is run from the frontend directory, with --no-clean to not delete my django templates folder on build.
Here is my workaround for adding {% static %} tags to the built index.html. I realize I am breaking the convention vue has that assetsDir is a subdirectory of outputDir, and I am not opposed to adding another staticfile dir to the settings.py to match the convention (although my issue is still the same).
vue.config.js
publicPath: isProd ? '/app/' : '/',
outputDir: __dirname + '/../app/templates/app',
assetsDir: "../../../assets",
indexPath: './index.html',
configureWebpack: {
...
plugins: [
new HtmlWebpackPlugin({
template: __dirname + '/public/index.html',
favicon: __dirname + '/../assets/img/favicon/favicon.ico',
inject: false,
minify: false
})
],
},
public/index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>MAPP Remote</title>
<link rel="shortcut icon" href="{% static '<%= htmlWebpackPlugin.files.favicon %>' %}">
<% for (key in htmlWebpackPlugin.files.css) { %> <link rel="stylesheet" href="{% static '<%= htmlWebpackPlugin.files.css[key] %>' %}"> <% } %>
</head>
<body>
...
<div id="app"></div>
<!-- built files will be auto injected -->
<% for (key in htmlWebpackPlugin.files.js) { %> <script type="text/javascript" src="{% static '<%= htmlWebpackPlugin.files.js[key] %>' %}"></script> <% } %>
</body>
</html>
The built index.html:
app/templates/app/index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>MAPP Remote</title>
<link rel="shortcut icon" href="{% static '/app/favicon.ico' %}">
<link rel="stylesheet" href="{% static '/app/../../../assets/css/chunk-vendors.0ba3e87d.css' %}"> <link rel="stylesheet" href="{% static '/app/../../../assets/css/app.fb012fc8.css' %}">
</head>
<body>
...
<div id="app"></div>
<!-- built files will be auto injected -->
<script type="text/javascript" src="{% static '/app/../../../assets/js/chunk-vendors.6a3b11f1.js' %}"></script> <script type="text/javascript" src="{% static '/app/../../../assets/js/app.45295baa.js' %}"></script>
</body>
</html>
My django settings.py configuration for static files:
Settings.py
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = "/static/"
STATICFILES_DIRS = [os.path.join(BASE_DIR, "assets")]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
...
The way my static file finders are configured via Django requires modification to the built script/css paths inside of app/templates/app/index.html.
In stead of <script src="{% static '/app/../../../assets/js/chunk-vendors.6a3b11f1.js' %}">
The path currently needs to be <script src="{% static 'js/chunk-vendors.6a3b11f1.js' %}">
Changing the assetsDir path in vue.config.js to match the Vue convention of having assets be a subdirectory of outputDir results in a similar issue in which the path is 'app/assets/js/...' rather than 'js/...'
I decided to adjust the path that is loaded into the template during the Vue build by modifying public/index.html file as well as the vue.config.js options. I declared a const asset_dir = '/asset/dir in vue.config.js and then added this as an extra option to the HtmlWebpackPlugin to pull it into the template. Lastly, I substring the path for the static files by the length of the unnecessary portion of the path.
vue.config.js
const asset_dir = "../../../assets"
module.exports = {
publicPath: isProd ? '/app/' : '/',
outputDir: __dirname + '/../app/templates/app',
assetsDir: asset_dir,
indexPath: './index.html',
configureWebpack: {
...
plugins: [
new HtmlWebpackPlugin({
template: __dirname + '/public/index.html',
inject: false,
minify: false,
assetsDir: asset_dir
})
],
}
}
public/index.html
{% load static %}
<% if (htmlWebpackPlugin.options['assetsDir'] !== undefined) { %> <% var assetDirLength = htmlWebpackPlugin.options['assetsDir'].length + htmlWebpackPlugin.files.publicPath.length + "/".length%> <% } %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>MAPP Remote</title>
<link rel="shortcut icon" href="{% static 'img/favicon/favicon.ico' %}">
<% for (key in htmlWebpackPlugin.files.css) { %> <link rel="stylesheet" href="{% static '<%= htmlWebpackPlugin.files.css[key].substr(assetDirLength) %>' %}"> <% } %>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
<!-- Pulled from htmlWebpackPlugin Docs -->
<!-- https://github.com/jaketrent/html-webpack-template/blob/86f285d5c790a6c15263f5cc50fd666d51f974fd/index.html -->
<% for (var chunk in htmlWebpackPlugin.files.chunks) { %>
<script src="{% static '<%= htmlWebpackPlugin.files.chunks[chunk].entry.substr(assetDirLength) %>' %}"></script>
<% } %>
</body>
</html>

usinig Django urls in react, is_authenticated in react, displaying context in react

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.

Error 404 is thrown, when .js extension is not specified during modul import in typescript

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>

How to add bootstrap template in django app

I want to add bootstrap template in my django app. I have downloaded it and kept in my static folder, then added its path in setting.py file as-
STATICFILES_DIRS = '/home/dc/my_django_apps/mutech_website/mutech/static/'
index.html of template is-
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Freelancer - Start Bootstrap Theme</title>
<!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/freelancer.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top" class="index">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#page-top">Start Bootstrap</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden">
</li>
<li class="page-scroll">
Portfolio
</li>
<li class="page-scroll">
About
</li>
<li class="page-scroll">
Contact
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="js/classie.js"></script>
<script src="js/cbpAnimatedHeader.js"></script>
<!-- Contact Form JavaScript -->
<script src="js/jqBootstrapValidation.js"></script>
<script src="js/contact_me.js"></script>
<!-- Custom Theme JavaScript -->
<script src="js/freelancer.js"></script>
</body>
</html>
but still its not working. Any suggestion will be appreciated.
First configure the static files app, in setting.py by adding this setting
STATIC_URL = '/static/'
and make sure you have all your static files/folders inside a folder called static in the root or in static folder inside your app but make sure to run collectstatic command, then reference JS file from static files please use this syntax
<script src="{% static 'js/classie.js' %}"></script>
and for linking the CSS:
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
You will need 3 variables in your settings.py:
# Alias that will be written in the source code
STATIC_URL = '/public/'
# The actual folder where static files will be collected
STATIC_ROOT = 'static'
# Location of folders that will be added to static folder
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "folder_one", "folder_two", "static"),
)
After this, you'll need to run the command
python manage.py collectstatic
that will copy all static files to the STATIC_ROOT.
After this, you can use the static files in the template. Just add the tag to the template
{% load staticfiles %}
and use the static tag:
{% static 'folder_one/folder_two/path_to_static' %}
You can also use
... src="/public/folder_one/folder_two/path_to_static" ...
but if you want to change the alias one day, you'll have to change all of them... so, the first option is much better.
You'll have to check the static folder to see what path you'll have to use.
And django will write something like this
'/public/folder_one/folder_two/path_to_static'
When you make this work, have a look at bower and bower-installer
The first will download all packages that you need with a single command. The second will put all the files you need in a specific folder. This is quite good because you don't have to download one by one.
bower.json example
{
"name": "your_project_name",
"version": "1.0.0",
"authors": [
"you Name <your#email>"
],
"license": "License type",
"ignore": [
"**/.*",
"node_modules",
"bower_components"
],
"dependencies": {
"jquery": "latest",
"bootstrap": "latest"
},
"install": {
"path": "where/do/you/want/your/files"
}
}
Just add more dependencies and you're done. Then check bower-installer. It will copy only the files you need to a directory and not the whole source code for each package. when you're done you can remove the bower folder if you want and leave only the bower-installer folder.