I am badly stuck in deployement, I am trying to deploy the react django together on heroku,the problem is react app is not loading when i hit url it shows blank page and I can't get what the problem is it might be of build directory,where I think the path is not correct when made initial build "npm run build".Here's my below try:
Settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
urlpatterns = [
path('admin/', admin.site.urls),
path('automation/', include('performaApp.urls')),
re_path('.*',TemplateView.as_view(template_name='index.html'))
#url(r'^', FrontendAppView.as_view())
]
build/index.html
<!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"><link rel="manifest" href="/static/manifest.json"><link rel="shortcut icon" href="/static/favicon.ico"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css"><title>Cameria - Facial Recognition</title><link href="/static/css/main.1ec2ccf3.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script type="text/javascript" src="/static/js/main.40de23a7.js"></script></body></html>
Package.json
{
"name": "react-redux-starter-template",
"version": "0.1.0",
"private": true,
"homepage": "https://adidas008.herokuapp.com",
"dependencies": {
"#material-ui/core": "^4.9.0",
"#material-ui/icons": "^4.5.1",
"axios": "^0.19.2",
"material-ui": "^0.20.0",
"react": "^16.2.0",
"react-bootstrap": "^0.32.0",
"react-dom": "^16.2.0",
"react-flexbox-grid": "^2.0.0",
"react-loader-spinner": "^3.1.5",
"react-redux": "^5.0.6",
"react-router-dom": "^4.2.2",
"react-scripts": "1.0.17",
"react-webcam": "^0.2.0",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-promise": "^0.5.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"postinstall": "npm run build"
},
"engines": {
"node": "10.18.1",
"npm": "6.13.4"
}
}
I think the main issue is the path of css or manifest files, thats why it may not loading react app,when I go to url it shows blank page and when I open console it giving me below errors :
Refused to apply style from 'https://adidas008.herokuapp.com/static/css/main.1ec2ccf3.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
register:1 Refused to execute script from 'https://adidas008.herokuapp.com/static/js/main.40de23a7.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
static/manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.
register:1 Refused to apply style from 'https://adidas008.herokuapp.com/static/css/main.1ec2ccf3.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled
Blank screen:
Kindly someone suggest I am stuck in this for so long,In my opinion it may be build directory fault,is the paths in index.html is valid,it was automatically made when I ran "npm run build".How can I load my react app.What can I fix?
I think you are missing this from your configuration:
class Assets(View):
def get(self, _request, filename):
path = os.path.join(os.path.dirname(__file__), "static", filename)
if os.path.isfile(path):
with open(path, "rb") as file:
return HttpResponse(file.read(), content_type="application/javascript")
else:
return HttpResponseNotFound()
Without this, Heroku will be receiving all statics with the default content-type for Django http requests, which is text/html. They need to be application/javascript in this case.
The whole thing with some gotchas is quite detailed here:
https://dev.to/mdrhmn/deploying-react-django-app-using-heroku-2gfa
Related
I was wondering if there is a solution to Debug Django Javascript with in VSCode.
VScode Chrome Debuger seems very popular. Is it possible to use that together with Django server enviorment?
untill now i tried following setting in my config:
{
"name": "Launch Chrome",
"request": "launch",
"type": "pwa-chrome",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}/path/to/static/files"
},
webRoot is the same path as my STATIC_ROOT constant from settings.py
Any Ideas? For me the solution does not to be nessesarly the VSChrome-Debugger, I just dont want to debug JS in Chrome directly all the time ^^.
Thanks!!
This setup works for me:
{
"name": "Chrome Debugger - launch",
"type": "chrome",
"request": "launch",
"url": "http://localhost:8000/v2/",
"webRoot": "${workspaceFolder}/project/djangoprojectname/appname/static/main",
"disableNetworkCache": true
}
important is the webRoot. My webRoot path points to where my JS Directory is.
My Django HTML template loads my JS from the folling source:
<script type="module" src="{% static 'main/js/index.js' %}"></script>
For reference, this is how my complete path looks like: ${workspaceFolder}/project/djangoprojectname/appname/static/main/js/index.js
disableNetworkCache is optional.
Documentation: https://github.com/microsoft/vscode-chrome-debug
disableNetworkCache: If false, the network cache will be NOT disabled. It is disabled by
default.
So I have this Django application with django-summernote, and I'm having trouble uploading image files via the editor. When I click the upload button and choose an image from my computer, I get an error saying "Failed to save attachment". And in the console, I see this error: "POST /summernote/upload_attachment/ 500". Let me show you my code. settings.py
INSTALLED_APPS = [
...
'django_summernote',
...
]
...
DEBUG = True
...
SUMMERNOTE_CONFIG = {
'iframe': True,
'lang' : 'ko-KR',
'summernote': {
'width': '100%',
'height': '450px',
'placeholder':'First sentence',
'toolbar': [
['style', ['style',]],
['font', ['fontsize', 'bold', 'italic', 'strikethrough']],
['color', ['forecolor', ]],
['para', ['ul', 'ol', 'height']],
['insert', ['link']],
['misc', ['picture', 'fullscreen', 'print', 'help', ]],
],
},
'js': (
'static/summernote-ext-print.js',
),
'js_for_inplace': (
'/static/summernote-ext-print.js',
),
'css': (
'//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css',
'/mvp/static/summernote.css',
),
'css_for_inplace': (
'//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css',
'/summernote.css',
),
'codemirror': {
'theme': 'base16-dark',
'mode': 'htmlmixed',
'lineNumbers': 'true',
},
'lazy': False,
}
SUMMERNOTE_THEME = 'bs4'
X_FRAME_OPTIONS = 'SAMEORIGIN'
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
path('summernote/', include('django_summernote.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I don't see what I've done wrong. Everything else except uploading image works fine. BTW, I'm using Django 3.x and Bootstrap 4.x.
+++ If it gives you any further info: I also keep getting these errors in the console as well. Might be related?
Refused to apply style from '<myURL>/summernote.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Failed to load resource: the server responded with a status of 404 () ... summernote-ext-print.js Failed to load resource: the server responded with a status of 500 () .../summernote/upload_attachment/
This has been making me so frustrated for days. I'd very much appreciate your help. :)
I've built a simple SPA CRUD web app with Django, Vue and Docker(-compose).
Since I've finished developing the app, I'm now preparing for the production environment, that is, using bundle.js and bundle.css files.
When I try to load the main page, http://localhost:8000, no CSS or JS
are being loaded because I'm getting this error in the browser's console:
GET http://0.0.0.0:8080/bundle.css net::ERR_CONNECTION_REFUSED
GET http://0.0.0.0:8080/bundle.js net::ERR_CONNECTION_REFUSED
I really don't know why it is giving that error or how to fix it.
This is my vue.config.js file:
const webpack = require("webpack");
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
publicPath: "http://0.0.0.0:8080/",
outputDir: "./dist/",
filenameHashing: false,
configureWebpack: {
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
]
},
chainWebpack: config => {
config
.plugin("BundleTracker")
.use(BundleTracker, [{ filename: "./webpack-stats.json" }]);
config.output.filename("bundle.js");
config.optimization.splitChunks(false);
config.optimization.delete("splitChunks");
config.resolve.alias.set("__STATIC__", "static");
config.devServer
.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"
}
}
};
This is part of my settings.py file:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "assets"),
os.path.join(BASE_DIR, "frontend/dist"),
]
# STATIC_ROOT = "" # The absolute path to the dir for collectstatic
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'dist/',
'STATS_FILE': os.path.join(BASE_DIR, 'frontend', 'webpack-stats.json'),
}
}
When I run the npm run build command I get notified that both the bundle.css and the bundle.js files have been generated:
File Size Gzipped
dist/bundle.js 150.73 KiB 51.05 KiB
dist/bundle.css 192.06 KiB 26.89 KiB
Images and other types of assets omitted.
DONE Build complete. The dist directory is ready to be deployed.
INFO Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
I really don't know why it is giving that ERR_CONNECTION_REFUSEDerror or how to fix it.
For production remove publicPath from your vue config file, I suppose you used that for development purposes, but in production you should only create the bundle and serve it to the user.
What's probably happening is that in your Docker setup you don't have the webpack dev server running (and you don't need it), thus you hit a connection refused error.
I've been reading a million answers in this subject but I can't find a solution that works.
I have a Django DRF backend that is used for all the API calls and a separate Angular(5) front-end project. The Django backend is deployed to Elastic Beanstalk and is working properly.
All I want to do is to deploy the angular frontend without needing to add template tags to the htmls. Better yet I don't want to change anything in the built dist Angular folder.
I see there are several approaches - As far as I can understand the best one would be to serve the index.html through a regular Django url and then expose all the dist folder (the static files).
I achieved the first part using:
urlpatterns += [
url(r'^$', TemplateView.as_view(template_name='index.html')),
url(r'^(?P<path>.*)/$', TemplateView.as_view(template_name='index.html')),
]
and defining the dist folder as a template folder in settings.py:
ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'client/dist')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ANGULAR_APP_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.i18n',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Currently, I define an s3 bucket to hold all static files. 'collectstatic' runs when I deploy the code and puts all the static files in the right location on s3, including the files in dist, because I added this:
STATICFILES_DIRS = [
ANGULAR_APP_DIR,
]
I can't figure out how to serve all the other static files (js, css assets) from the base url ("/") which is the location that the Angular app is expecting it to be in.
I'm not sure if I should try redirecting the calls Through Django urls to the s3 bucket, or if I should do it totally separate from Django with routes on s3.
What would be a better approach and how is it done?
Thank you!
I am experimenting with Crossbar.io 0.10.4 and Django 1.6.11, trying to follow the example here. The code shows you can configure Crossbar.io to serve up the Django app at "/" -- but when I try that in my configuration, I get a Python import error:
ApplicationError: ApplicationError('crossbar.error.invalid_configuration', args = (u"WSGI app module 'apache/django.wsgi' import failed: Import by filename is not supported. - Python search path was ....
My config.json is here:
{
"controller": {
},
"workers": [
{
"type": "router",
"realms": [
{
"name": "backstage-producer",
"roles": [
{
"name": "anonymous",
"permissions": [
{
"uri": "*",
"publish": false,
"subscribe": true,
"call": false,
"register": false
}
]
}
]
}
],
"transports": [
{
"type": "web",
"endpoint": {
"type": "tcp",
"port": 8080
},
"paths": {
"/": {
"type": "wsgi",
"module": "apache/django.wsgi",
"object": "application"
},
"ws": {
"type": "websocket",
"debug": false
},
"notify": {
"type": "publisher",
"realm": "backstage-producer",
"role": "anonymous"
},
"static": {
"type": "static",
"directory": "../static"
}
}
}
]
}
]
}
Where the Python paths searched do not include my Django project directory. Typically I append my specific project directories to sys.path in my wsgi file, but apparently that workflow doesn't work with Crossbar.io. Trying a relative import fails (need to specify "package" argument) as does full path (same import by filename error as above).
Removing the definition for "/" does not work, because Crossbar.io complains that it must be defined.
How can I set this up properly with Crossbar.io? My apache/django.wsgi file is below, for reference:
ALLDIRS = ['/usr/local/pythonenv/myapp/lib/python2.6/site-packages']
import os
import sys
import site
# from https://code.google.com/p/modwsgi/wiki/VirtualEnvironments
sys.path.insert(0, '/var/www/myapp/myapp_main/')
sys.path.insert(1, '/var/www/myapp/')
prev_sys_path = list(sys.path)
for directory in ALLDIRS:
site.addsitedir(directory)
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp_main.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
----UPDATE 1------
Per Daniel's suggestion, I changed the file to just wsgi.py and my config to use the Python module path, not the filename / directory path. Config then looked like this:
"paths": {
"/": {
"type": "wsgi",
"module": "apache.wsgi",
"object": "application"
},
Throws the same exception:
ApplicationError: ApplicationError('crossbar.error.invalid_configuration', args = (u"WSGI app module 'apache.wsgi' import failed: No module named apache.wsgi - Python search path was
My directory structure is:
Project
|- apache
| |-__init__.py
| |-wsgi.py
|-.crossbar
|-config.json
-------UPDATE 2-------
The only solution (read "hack") I have found is to hard-code my project path into crossbar/worker/router.py so that it is included in the Python search path list:
sys.path.insert(0, '/var/www/myapp/myapp_main/')
sys.path.insert(1, '/var/www/myapp/')
Seems like there should be a better way...
The error is telling you that you have a file path in the setting that points to your WSGI file, whereas you need a Python module path. Your WSGI file should actually be a file called "wsgi.py" inside your project directory (which presumably is "apache", which is a strange name for a project that explicitly is not using Apache).
"/": {
"type": "wsgi",
"module": "apache.wsgi",
"object": "application"
},
Update So I found the config docs at last: they really don't go out of their way to make it easy, like actually providing an index. Oh well.
It looks like you can provide an options hash to the router configuration including a pythonpath setting:
"workers": [
{
"type": "router",
"options": {
"pythonpath": ["/var/myapp/myapp_main/", "/var/myapp"]
},
...
"transports": {
...