How to Debug Django Javascript within VSCode? - django

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.

Related

Access Django admin from Firebase

I have a website which has a React frontend hosted on Firebase and a Django backend which is hosted on Google Cloud Run. I have a Firebase rewrite rule which points all my API calls to the Cloud Run instance. However, I am unable to use the Django admin panel from my custom domain which points to Firebase.
I have tried two different versions of rewrite rules -
"rewrites": [
{
"source": "/**",
"run": {
"serviceId": "serviceId",
"region": "europe-west1"
}
},
{
"source": "**",
"destination": "/index.html"
}
]
--- AND ---
"rewrites": [
{
"source": "/api/**",
"run": {
"serviceId": "serviceId",
"region": "europe-west1"
}
},
{
"source": "/admin/**",
"run": {
"serviceId": "serviceId",
"region": "europe-west1"
}
},
{
"source": "**",
"destination": "/index.html"
}
]
I am able to see the log in page when I go to url.com/admin/, however I am unable to go any further. It just refreshes the page with empty email/password fields and no error message. Just as an FYI, it is not to do with my username and password as I have tested the admin panel and it works fine when accessing it directly using the Cloud Run url.
Any help will be much appreciated.
I didn't actually find an answer to why the admin login page was just refreshing when I was trying to log in using the Firebase rewrite rule, however I thought of an alternative way to access the admin panel using my custom domain.
I have added a custom domain to the Cloud Run instance so that is uses a subdomain of my site domain and I can access the admin panel by using admin.customUrl.com rather than customUrl.com/admin/.

React And Django Deployment on heroku

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

How do I fix this error message "Initialization error (Eslint). Unexpected Identifier"?

I have Eslint and JSCS setup to reformat some code base with airbnb js style guide in WebStorm. I have been using this setup effectively for the past 2 days, but all of a sudden, WebStorm started throwing this error...
Problem with ESLint reformatting:index.js: Initialization error (ESLint). Unexpected identifier
I thought maybe I had some error in my .eslintrc but then I had used the same config to successfully refactor about 150 files before this sudden error.
Prior to this, the JSCS compiler was occasionally throwing "less than a minute timeout" exceptions, but then I would fix this with closing and reopening the file. The eslint though seems not to be falling for this trick.
This is my .eslintrc config
{
"extends": "airbnb",
"env": {
"browser": true,
"node": true
},
"globals": {
"document": false
},
"rules": {
"validateIndentation": 4,
"func-names": [
"error",
"never"
],
"react/jsx-filename-extension": [
1,
{
"extensions": [
".js",
".jsx"
]
}
],
"jsx-a11y/label-has-for": [
2,
{
"components": [
"Label"
],
"required": {
"some": [
"nesting",
"id"
]
},
"allowChildren": false
}
],
"jsx-a11y/anchor-is-valid": [
"error",
{
"components": [
"Link"
],
"specialLink": [
"to",
"hrefLeft",
"hrefRight"
],
"aspects": [
"noHref",
"invalidHref",
"preferButton"
]
}
]
}
}
Some part of package.json
{
"eslint": "^4.14.0",
"eslint-config-airbnb": "^16.1.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-flowtype": "^2.40.1",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.5.1",
"extract-text-webpack-plugin": "^3.0.2",
"prop-types": "^15.6.0",
"react": "^16.2.0",
"react-dev-utils": "^4.2.1",
"react-dom": "^16.2.0",
"react-redux": "^5.0.6",
"react-router-dom": "^4.2.2",
},
"babel": {
"presets": [
"react-app",
"flow"
]
},
"eslintConfig": {
"extends": "react-app"
}
}
Can some one throw me some pointers on how I can go about fixing this. I suspect it might be more of a WebStorm error than Eslint.
PS: Forgive me if this question might be better suited at superuser. I just thought it's most likely someone here might have faced the same issue.
i use this pattern for my eslint configuraion in phpstorm and error has gone now,
{**/*,*}.{js,ts,jsx,tsx,html,vue},{!node_modules/*}
Solved by a yarn upgrade
My attempts at recreating the issue with a fresh project failed, with the same configs, both eslint and jscs were running successfully.
However on using the WebStorm context menu command Apply ESlint Code Style Rules on non js files(tested on .eslintrc itself), i got a much more detailed error.
Error on attempt to find parent and base ESLint configuration files of '.eslintrc': [projectpath]\node_modules\lodash\lodash.js:386 '\u0149': ''n', '\u017f': 's',
I double checked lodash package node_modules and package.json, tripple checked the settings configs(Eslint & JSCS) and was sure I had identical setup to the test projects that were linting without errors.
Running yarn upgrade lodash saved my hair. Since I was already running the latest lodash, I think yarn's Resolving and Rebuilding the packages did the trick.
Hope someone might find this helpful somewhere along the line.

System.getenv() returning VCAP_SERVICES : "******"

System.getenv() is returning json with VCAP_SERVICES : "******". My cloud foundry java spring-boot app is bound to three services. If I give cf env app_name in CLI, its returning all bound services correctly. Also VCAP_APPLICATION and other fields in returned json are just fine except this one.
A Little background:
I need to get service name, label and plan for all the services bound to my app. I'm new to cloud foundry and spring-boot, so don't know how to use spring cloud connectors in my code.
The value in the VCAP_SERVICES environment variable will be a JSON string that you need to parse, and it will give you an object describing all the bound services, including data like name, label, and plan. If you Google "vcap services" or "cloud foundry environment variables" the first result is this doc, and it has a section on VCAP_SERVICES. Here's the example they provide of what this JSON object looks like (after parsing):
{
"elephantsql": [
{
"name": "elephantsql-c6c60",
"label": "elephantsql",
"tags": [
"postgres",
"postgresql",
"relational"
],
"plan": "turtle",
"credentials": {
"uri": "postgres://seilbmbd:ABcdEF#babar.elephantsql.com:5432/seilbmbd"
}
}
],
"sendgrid": [
{
"name": "mysendgrid",
"label": "sendgrid",
"tags": [
"smtp"
],
"plan": "free",
"credentials": {
"hostname": "smtp.sendgrid.net",
"username": "QvsXMbJ3rK",
"password": "HCHMOYluTv"
}
}
]
}
As you suggest wanting to try to to acces this info in your code you should consider the cloud foundry java client, good intro here and its really easy to get up and running. I've found that the api is somewhat limited but its worth looking at - http://docs.cloudfoundry.org/buildpacks/java/java-client.html

Crossbar.io configure WSGI for Django app

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": {
...