I've decided to integrate an existing Angular 2 app into my Django REST project.
create Django app with static folder for my frontend:
urls.py:
from django.conf.urls import url
from frontend import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.index, name='index'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
def index(request):
"""
Renders the Angular2 SPA
"""
return render(request, template_name='index.html')
move my Angular 2 app to frontend static folder
add static settings in my settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend', 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
make changes in index.html:
<html>
<head>
<base href="/">
<title>PhotoHub</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% load staticfiles %}
<link rel="stylesheet" href="{% static "node_modules/bootstrap/dist/css/bootstrap.min.css" %}">
<link href="{% static "bower_components/font-awesome/css/font-awesome.min.css" %}" rel="stylesheet" />
<link href="{% static "bower_components/alertify.js/themes/alertify.core.css" %}" rel="stylesheet" />
<link href="{% static "bower_components/alertify.js/themes/alertify.bootstrap.css" %}" rel="stylesheet" />
<link rel="stylesheet" href="{% static "styles.css" %}">
<script src="{% static "bower_components/jquery/dist/jquery.min.js" %}"></script>
<script src="{% static "node_modules/bootstrap/dist/js/bootstrap.min.js" %}"></script>
<script src="{% static "bower_components/alertify.js/lib/alertify.min.js" %}"></script>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="{% static "node_modules/core-js/client/shim.min.js" %}"></script>
<script src="{% static "node_modules/zone.js/dist/zone.js" %}"></script>
<script src="{% static "node_modules/reflect-metadata/Reflect.js" %}"></script>
<script src="{% static "node_modules/systemjs/dist/system.src.js" %}"></script>
<!-- 2. Configure SystemJS -->
<script src="{% static "systemjs.config.js" %}"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<photohub></photohub>
</body>
</html>
make changes in systemjs.config.js:
(function (global) {
System.config({
//static
defaultJSExtensions: true,
paths: {
// paths serve as alias
'npm:': 'static/node_modules/'
},
// map tells the System loader where to look for things
map: {
app: 'static/dist',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
The TypeScript files are compiled in /dist and templates remained in /app. When I used two different servers the path for templateUrl look like this:
templateUrl: './app/app.component.html'
now I'm trying to declare templateUrl this way, but it doesn't work:
templateUrl: '{{ STATIC_URL }}' + '/app/app.component.html'
How to deal with templates urls now?
Response:
"GET /app/components/login/login.component.html HTTP/1.1" 404 2601
Not Found: /app/app.component.html
JavaScript files loaded well:
"GET /app/components/login/login.component.html HTTP/1.1" 404 2601
Not Found: /app/components/register/register.component.html
This solved problem:
templateUrl: 'static/app/app.component.html'
I am not sure what error you're having but you probably should use the static tag to make a URL to a static asset in your template:
{% load static %}
templateUrl: "{% static '/app/app.component.html' %}"
Doc: https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#std:templatetag-static
Related
Following is the my static folder structure:
ProjectABC
- App1
- App2
- App3
- ProjectABC
- resources
- static
- imgs
- css
- templates
This is how the project structure looks like.
This is how the static configuration in settings.py looks like:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
This is how the base.html looks like:
<!doctype html>
{% load static %}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, maximum-scale=1, initial-
scale=1, user-scalable=0">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?
family=Open+Sans:400,600,800">
<title>{{SITE_NAME}}</title>
<link rel='shortcut icon' href= "{% static 'img/favicon.png' %}"/>
<link href="{{STATIC_URL}}css/application.css" media="screen" rel="stylesheet"
type="text/css" />
<link href="{{STATIC_URL}}css/style.css" media="screen" rel="stylesheet"
type="text/css" />
<script src="{{STATIC_URL}}js/application.js" type="text/javascript"></script>
{% block extracss %}
{% endblock %}
</head>
<body>
<div class="container">
<h1>Hello</h1>
</div>
</body>
</html>
All the static files are being loaded as seen in terminal, but in browser its just loading bare html without any css or img:
Please lemme know if i am missing something.
Thnk You!
<link href="{%static 'css/style.css' %}" media="screen" rel="stylesheet"
type="text/css" />
add settings.py
STATIC_URL = "/static/"
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
Project App Url
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),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Static directory must be under the app itself. Create a 'static' directory directly to your app and for better practice, you can also create another directory to the static directory with your app name (static/[app_name]).
Also, {% load static %} must be above doctype in your base.html
change the static config in your settings.py to this:
STATIC_ROOT = os.path.join(BASE_DIR, 'resources/static')
STATIC_URL = 'resources/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'ProjectABC')
]
then run python manage.py collectstatic
and when you call the static file do it like this {% static 'css/style.css' %}
I am Building a BlogApp and I am stuck on an Problem.
The Problem
Static Files are not loading from static folder. Some files are loading but some are not loading.
What have i done ?
urls.py
I also put static url in urls.py , it also didn't work for me.
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
os.path.join(BASE_DIR, "static", "static")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
my_template.html
{% load static %}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Next Level - Gallery</title>
<!--
Next Level CSS Template
https://templatemo.com/tm-532-next-level
-->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" />
<script src="{% static 'comments/all.min.css' %}"></script>
<script src="{% static 'comments/bootstrap.min.css' %}"></script>
<script src="{% static 'comments/templatemo-style.css' %}"></script>
</head>
<div class="row tm-welcome-row">
<div class="col-12">
<div
class="tm-welcome-parallax tm-center-child"
data-parallax="scroll"
data-image-src="static/images/blooming-bg.jpg"
>
<div class="tm-bg-black-transparent tm-parallax-overlay">
<h2>Our Gallery</h2>
<p>this is a parallax background image</p>
</div>
</div>
</div>
</div>
<div class="tm-page-col-right">
<div class="tm-gallery" id="tmGallery">
<div class="tm-gallery-item category-1">
<figure class="effect-bubba">
<img
src="static/comments/gallery/gallery-item-01.jpg"
alt="Gallery item"
class="img-fluid"
/>
</figure>
</div>
</div>
</div>
</div>
</section>
<script src="{% static 'comments/jquery.min.js' %}"></script>
<script src="{% static 'coments/parallax.min.js' %}"></script>
<script src="{% static 'comments/imagesloaded.pkgd.min.js' %}"></script>
<script src="{% static 'comments/isotope.pkgd.min.js' %}"></script>
<script src="{% static 'comments/bootstrap.min.js' %}"></script>
<script>
$(function() {
/* Isotope Gallery */
// init isotope
var $gallery = $(".tm-gallery").isotope({
itemSelector: ".tm-gallery-item",
layoutMode: "fitRows"
});
// layout Isotope after each image loads
$gallery.imagesLoaded().progress(function() {
$gallery.isotope("layout");
});
$(".filters-button-group").on("click", "a", function() {
var filterValue = $(this).attr("data-filter");
$gallery.isotope({ filter: filterValue });
console.log("Filter value: " + filterValue);
});
/* Tabs */
$(".tabgroup > div").hide();
$(".tabgroup > div:first-of-type").show();
$(".tabs a").click(function(e) {
e.preventDefault();
var $this = $(this),
tabgroup = "#" + $this.parents(".tabs").data("tabgroup"),
others = $this
.closest("li")
.siblings()
.children("a"),
target = $this.attr("href");
others.removeClass("active");
$this.addClass("active");
// Scroll to tab content (for mobile)
if ($(window).width() < 992) {
$("html, body").animate(
{
scrollTop: $("#tmGallery").offset().top
},
200
);
}
});
});
</script>
</body>
</html>
What have i tried
I also try python manage.py collectstatic and it showed 0 static files copied to 'D:\myapp\static_cdn', 248 unmodified.
I tried many answers AND some of were saying that add static url in urls.py` BUT it didn't work.
I don't know what to do
Any help would appreciated
Thank You in Advance
make sure that your settings.py has the following
settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR,"templates")
STATIC_DIR = os.path.join(BASE_DIR,"static")
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
the below preferably at the bottom end
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
#MEDIA
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
LOGIN_URL = 'user_login'
now create a folder called static in the base directory( the place where you have your manage.py ) and have your static files inside
make sure to {% load static %} in your template
if nothing works try opening a new project and try the above
However static files dir is different from static files directory.Django uses 2 types of static folder . system & apps
You need to put all your static files into static files dir location then run python manage.py collectstatic . It will move all your applications static files to system static folder.
Now it will served from destination(systems static files directory) location.
I have a static website in django at: domain.com/press/. The page at this address is visible, but there is a problem with static files - they don't appear.
Error in console (F12):
domain.com/press/%7B%%20static%20'images/presslogo.png'%20%%7D Failed to load resource: the server responded with a status of 400 (Bad Request)
My settings in nginx:
location /press/ {
alias /path_to_templates/;
index press.html;
}
Part of my html code:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Press</title>
</head>
<body>
<img src="{% static 'images/presslogo.png' %}">
</body>
</html>
setting.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
How can I display an image on a static page?
/press/ is being served by nginx. Hence <img src="{% static 'images/presslogo.png' %}"> will not work.
Please give exact path of your image. That is
<img src="domain.com/<your-static-url>/images/presslogo.png">
I'm running a project with an Angular front-end and a Django back-end. Today when I changed some code in the templates the ng build didn't update. I have discovered that it neither updates template changes nor component changes. However, when I run ng serve instead and go to 127.0.0.1:4200 instead of the Django port 8000 the new updates versions are rendered.
The way I have it set up is that I have a template that Django points to with TemplateViev :
{% load static %}
{% csrf_token %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularWebapp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<app-root></app-root>
{% block javascript %}
<script type="text/javascript" src="{% static 'runtime.js' %}"></script><script type="text/javascript" src="{% static 'polyfills.js' %}"></script><script type="text/javascript" src="{% static 'styles.js' %}"></script><script type="text/javascript" src="{% static 'vendor.js' %}"></script><script type="text/javascript" src="{% static 'main.js' %}"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
{% endblock %}
</body>
</html>
And the static directory layout looks like this in settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'angular', 'static'),
os.path.join(BASE_DIR, 'angular-webapp', 'dist', 'angular-webapp'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
And urls.py:
from django.contrib import admin
from django.urls import path, re_path, include
from django.views.generic import TemplateView
from rest_framework import routers
from authentication.views import AccountViewSet, LoginView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib.staticfiles import views
router=routers.SimpleRouter()
router.register('accounts', AccountViewSet)
class IndexView(TemplateView):
template_name = 'index.html'
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include(router.urls)),
re_path(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
re_path(r'^.*/$', IndexView.as_view()),
path('', IndexView.as_view()),
]
Which is the only place I have static files, and which is where the files from ng build is put, IE. the static load loads the runtime.js etc. from the folder where it's output when i ng build.
However, from yesterday the changes I make to my app in the angular-webapp/src/app folder doesn't get updated when I ng build. I have tried removing the dist folder to create a fresh one, but that doesn't change anything. When it comes back and I run the project it still somehow uses the old layout while ng serve works perfectly.
Is it something about how ng build works that I am missing?
It's probably a cache busting issue : your files still have the same name, and since they're cached by the browser, it doesn't reload them.
consider building with the --prod flag, which contains several other flags such as --aot, but to correct your issue, try building with --output-hashing=all.
Directly from ng build --help :
--output-hashing=none|all|media|bundles
(String) Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>
I new to AngularJS and trying to set up Django with AngularJs, however, I have some issues with handling the routing with those two frameworks. so far I've set up like below:
When I run http://localhost:8000/index.html it works and shows me the file, but when I run http://localhost:8000/test as I wrote in app.js it gives me standard Django 404 error.
What am I missing?
urls.py
urlpatterns = [
url(r'^index.html/$',
]
app.js
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/test", {
templateUrl : "index.html",
controller: "MainCtrl"
})
});
app.controller("MainCtrl", function ($scope) {
$scope.msg = "test";
});
index.html
{% load static %}
<html ng-app="myApp">
<head>
</head>
<body>
<div>
test
</div>
<script src="{% static 'js/general/angular.min.js' %}" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script type="text/javascript" src="{% static 'js/app.js' %}"></script>
</body>
</html>
You need to define the URL and it's corresponding views method.
In you urls.py
You need something like:
url(r'^test/$', views.test, name='test')
In views.py
def test(request):
return HttpResponse('You are looking at test')