Angular serve working, Angular build not updating files - python

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>

Related

Django templates not picking static files

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' %}

Django 404 css file

For a long time I tried to solve the problem with loading all my static files. When I found a working solution, all svg started loading, but css files didn't.
Here is my settings.py (showing you only main things)
import mimetypes
mimetypes.add_type("text/css", ".css", True)
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = False
STATIC_URL = '/static/'
if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else: STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Here is my urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
path('', include('main.urls')),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
Here is an example of using css files in my templates
{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-v4-grid-only#1.0.0/dist/bootstrap-grid.min.css">
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
<link rel="stylesheet" type="text/css" href=" {% static 'css/main.css' %}">
And this is the error in Chrome Console
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
And also i cant open css files in a new tab. I am getting that error
Also, if you remove %20 from the address bar, then I will open the css file
P.S.
I am trying to deploy it
1- Try to replace a slash forward path
<link rel="stylesheet" type="text/css" href=" {% static '/css/reset.css' %}">
2- whitenoise
pip install whitenoise
Then, set it to "MIDDLEWARE" in "settings.py". Finally, CSS is loaded successfully:
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", # Here
# "whitenoise" will solve "MIME type" error then CSS is loaded successfully:
]
3- change your static URL like that:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I think your mistake is that you put in a space in front of your static link
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
Try removing the space in front of {% so it will become
<link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}">
%20 is translated to a space character in URL's, so that why I think that's the issue

Django not serving static files and not stylizing anything

I downloaded a template in the form of a zip file on my machine. It has a file for a homepage, auth-login.html. If I load this on its own then it loads correctly, I see styling and I don't get any console errors.
But it seems like I can't get this template to load its css and styling in my Django project via python manage.py runserver with DEBUG=true. I'm trying to just get this on a development server and I haven't really been able to get past step 1. When I try to go to my application's home page, I see unstylized times new roman text in my browser. No styling loads on the page at all. I'm not getting server/console errors either.
My Django project is of the following structure
lpbsproject/
project_root/
staticFiles/ (STATIC_ROOT, where collectstatic copies to)
project_app/
settings.py
urls.py
wsgi.py, asgi.py, __init__.py...
static/ (STATIC_URL, original location of static files)
assets/ (this folder is copied/pasted from the template .zip)
css/, js/, ...
user_auth/
migrations
views.py
admin.py, models.py, apps.py, test.py ...
templates/
manage.py
Here's the <head> of my html file with all the <link> and <script> statements. These currently aren't generating errors.
{% load static %}
<!doctype html>
<html lang="en">
<head>
<title>Login template from online</title>
<link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}">
<link href="{% static 'assets/css/bootstrap.min.css' %}" id="bootstrap-style"/>
<link href="{% static 'assets/css/icons.min.css' %}" type="text/css" />
<link href="{% static 'assets/css/app.min.css' %}" id="app-style" type="text/css" />
<script src="{% static 'assets/libs/jquery/jquery.min.js' %}"></script>
<script src="{% static 'assets/libs/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'assets/libs/metismenu/metisMenu.min.js' %}"></script>
<script src="{% static 'assets/libs/simplebar/simplebar.min.js' %}"></script>
<script src="{% static 'assets/libs/node-waves/waves.min.js' %}"></script>
<script src="{% static 'assets/js/app.js' %}"></script>
</head>
In settings.py, this is how BASEDIR and the static file location are specified
BASE_DIR = Path(__file__).resolve().parent.parent # points to project_root/ directory
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticFiles')
There's ~1200 files in project_root/static/assets/ and I am seeing these get copied into project_root/staticFiles from python manage.py collectstatic. Last night I was dealing with some weridness where none of the js files were getting copied via the collectstatic command.
and urls.py for curiosity sake...
from django.contrib import admin
from django.urls import path
from django.contrib import admin
from django.urls import path, include
from user_auth import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.userLogin, name='loginHome'),
path('login', views.userLogin, name='login'),
path('logout', views.userLogout, name='logout'),
path('registration', views.userRegistration, name='registration'),
path('dashboard', views.dashboard, name='dashboard'),
]
So if python manage.py collectstatic is working... why am I still not able to see any styling at all? I'm not really sure what's going wrong here. It's felt way too difficult to just get a simple /static/ folder working for this project.
The terminal using python manage.py runserver isn't even showing requests for most of these css or js files. I just see
[24/Nov/2020 12:48:00] "GET / HTTP/1.1" 200 7194
[24/Nov/2020 13:25:39] "GET /static/assets/libs/bootstrap/js/bootstrap.bundle.mi
n.js.map HTTP/1.1" 404 1883
[24/Nov/2020 13:25:39] "GET /static/assets/libs/metismenu/metisMenu.min.js.map HTTP/1.1" 404 1853
[24/Nov/2020 13:25:39] "GET /static/assets/libs/node-waves/waves.min.js.map HTTP /1.1" 404 1844
I was able to get an answer when I posted about this on django forums.
No one here caught the html errors. I was inconsistently using type=text/css and rel='stylesheet'. Also <link> tags can end with >, not />.

Django not importing CSS

I cannot get the CSS to appear when I refresh the page nor when I turn the server off and then restart it.
{% load staticfiles %}
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name='viewpoint' content='width-device-width, initial-scale-1.0'>
<meta http-equix='X-UA-Compatible' content='ie-edge'>
<link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css"/>
<link ref="stylesheet" type='text/css' href="{% static 'css/styles.css' %}" />
My settings.py file has STATIC_URL = '/static/'
I'm not sure what else it could be. I've attempted several other stackoverflow questions but I'm out of ideas.
Any help is appreciated.
in setting.py file your set DEBUG=True, please update url.py file root (url.py project)
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
#url pattern.....
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and than if DEBUG=False ALLOWED_HOSTS=['your_host'], please running command ./manage.py collectstatic from the terminal
Maybe in your urls.py you did not import from django.conf import settings and/or
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
and you did not add urlpatterns += staticfiles_urlpatterns() in your urls.py too.
And maybe your first css (I mean <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css"/>)
Blocks your second css. Try to comment your first css and check is it working.

Django and Angular 2 templateUrl

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

Categories

Resources