Getting CORS error in frontend with Django backend - javascript

From my frontend http://127.0.0.1:5500/index.html I am calling Django REST POST API http://127.0.0.1:8000/api. I have installed django-cors-headers and my frontend's image_upload.js, backend's settings.py, and views.py, project level urls.py and app level urls.py are as follows, API is working in postman but I am getting CORS error in chromes console,
Chrome console
Django console
image_upload.js
const image_input = document.querySelector("#image_input");
const display_image = document.querySelector("#display-image");
image_input.addEventListener("change", (event) => {
console.log(event.target.files[0]);
// console.log(URL.createObjectURL(event.target.files[0]));
display_image.src = URL.createObjectURL(event.target.files[0]);
const url = "http://127.0.0.1:8000/api";
const data = event.target.files[0];
axios
.post(url, JSON.stringify(data), {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
settings.py
"""
Django settings for model project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pd^*8)+5$qr_q9(a+n)(meh22&m=0+qn7a^g8$#&)(+fv!1wgc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['http://127.0.0.1:5500']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'rest_framework',
"corsheaders",
# Local
'apis.apps.ApisConfig',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
"corsheaders.middleware.CorsMiddleware",
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# CORS_ALLOWED_ORIGINS = [
# 'http://127.0.0.1:8000',
# ]
# CSRF_TRUSTED_ORIGINS = [
# 'http://127.0.0.1:8000',
# ]
ROOT_URLCONF = 'model.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'model.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CORS_ORIGIN_ALLOW_ALL: True
# CORS_ALLOW_CREDENTIALS = True
# CORS_ALLOWED_ORIGINS = [
# 'http://127.0.0.1:8000/api/',
# 'http://127.0.0.1:5500',
# ]
CORS_ORIGIN_WHITELIST = [
'http://127.0.0.1:5500',
# 'http://127.0.0.1:8000',
]
# CORS_ALLOW_HEADERS = ['*']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
views.py
from email import message
from tkinter import image_names
from django.shortcuts import render
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from rest_framework.decorators import api_view
from tensorflow.keras.models import load_model
import urllib.request
# Create your views here.
#api_view(['GET', 'POST'])
def PostRequests(request):
print(request.body)
# ing_url = ''
# img_name = "tumor_image.jpg"
# img = urllib.request.urlretrieve(img_url,img_name)
# print(img)
# loaded_model = load_model("vgg16_model_with_90_acc.h5")
return JsonResponse({'message': "It Worked!"}, safe=False)
Project level urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('apis.urls')),
]
App level urls.py
from django.urls import path
from apis import views
urlpatterns = [
path('', views.PostRequests),
]

in your settings.py file you should convert this
CORS_ORIGIN_WHITELIST = [
'http://127.0.0.1:5500'
]
to this :
CORS_ALLOWED_ORIGINS=[
"http://127.0.0.1:5500"
]

Change CORS_ORIGIN_ALLOW_ALL: True to CORS_ALLOW_ALL_ORIGINS=True. That may be one problem.

Related

Add extra file to database, path is wrong

I am creating a website using Python Django and the main purpose of the website is to modify XML files. I have uploaded the files to the hosting server and when I try to perform the conversion, I need to add another file to the database record that was created. On my local server, the process works smoothly without any issues, but when I try to do it on the hosting server, I get an error message:
"SuspiciousFileOperation at /test/ Detected path traversal attempt in '/home/t/tkor470gma/converter/new_CUST.xml".
My models.py looks like this:
class Document(models.Model):
document = models.FileField(verbose_name='Document (old structure with settings)',upload_to='documents/')
document1 = models.FileField(verbose_name='Document (new structures without settings)',upload_to='documents/')
author = models.ForeignKey(User,on_delete=models.CASCADE)
resdocument = models.FileField(upload_to='documents/',blank=True)
transaction_date = models.DateTimeField(auto_now_add=True)
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ['document','document1']
views.py - this form uploads files to the database
def model_form_upload(request):
form = DocumentForm()
pathresdoc = ''
if request.method == 'POST':
user = request.user
form = DocumentForm(request.POST, request.FILES)
obj = Document.objects.filter(author_id=user).order_by('-id')
if obj.count() >= 1:
return HttpResponse('it is impossible to convert first <button>Pay</button>')
else:
if form.is_valid():
instance = form.save(commit=False)
instance.author = user
form.save()
create_file(request.user.id)
respeople = instance.id
add_file_to_database('/home/t/tkor470gma/converter/new_CUST.xml',respeople)
pathresdoc = Document.objects.get(id=respeople).resdocument.path
else:
form = DocumentForm()
return render(request, 'model_form.html', {'form': form,'pathresdoc': str(pathresdoc)})
This one adds the resulting file to the database:
def add_file_to_database(file_path,idtransaction):
my_file = File(open(file_path, 'rb'))
model_instance = Document.objects.get(id=idtransaction)
model_instance.resdocument = my_file
model_instance.save_base()
This one creates the file itself:
def create_file(request):
obj = Document.objects.filter(author_id=request).order_by('-id')[0]
converterfile(str(obj.document.path),str(obj.document1.path),r"/home/t/tkor470gma/converter/new_CUST.xml")
This calls the program which converts the files:
def converterfile(file1,file2,file3):
call(['python',"/home/t/tkor470gma/converter/backend/New_file.py", file1, file2, file3], shell=True)
How can I resolve this issue? I have tried using both the relative and absolute path, but the same error keeps appearing.
SuspiciousFileOperation at /test/
Detected path traversal attempt in
'/home/t/tkor470gma/converter/new_CUST.xml'
Request Method: POST
Request URL:
https://sapxmlversionup.ru/test/
Django Version: 4.0
Exception Type: SuspiciousFileOperation
Exception Value:
Detected path traversal attempt in
'/home/t/tkor470gma/converter/new_CUST.xml'
Exception Location:/home/t/tkor470gma/.djangovenv/lib/python3.8/sit
e-packages/django/core/files/utils.py, line
18, in validate_file_name
Python Executable: /usr/bin/python3
Python Version: 3.8.5
Python Path:
['/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/t/tkor470gma/converter/public_html',
'/home/t/tkor470gma/converter',
This is my hosting settings.py
from pathlib import Path
import os
from django.utils.translation import gettext_lazy as _
# Build paths inside the project like this:
BASE_DIR / 'subdir'.
BASE_DIR =
Path(__file__).resolve().parent.parent
MEDIA_ROOT = os.path.join(BASE_DIR, 'documents')
DEBUG = True
ALLOWED_HOSTS = ['sapxmlversionup.ru']
AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
# Application definition
SITE_ID = 1
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MainConv',
'users',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Converter.urls'
TEMPLATES = [
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'Converter.wsgi.application'
DATABASES = {
'default': {
'ENGINE':
'django.db.backends.postgresql_psycopg2',
'NAME': 'tkor470gma',
'USER': 'tkor470gma',
'PASSWORD': '***',
'HOST': 'pg2.sweb.ru',
'PORT': '5432',
}
}
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'ru'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
USE_L10N = True
DATE_INPUT_FORMATS = ( "%d/%m/%Y", )
DATETIME_INPUT_FORMATS = ( "%d/%m/%Y %H:%M", )
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = '/media/'
And this local settings:
from pathlib import Path
import os
from django.utils.translation import gettext_lazy as _
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
SITE_ID = 1
INSTALLED_APPS = [
'modeltranslation',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MainConv',
'users',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Converter.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'Converter.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'tkor470gma',
'USER': 'postgres',
'PASSWORD': '***',
'HOST': 'localhost',
'PORT': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'ru'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
USE_L10N = True
MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
DATE_INPUT_FORMATS = ( "%d/%m/%Y", )
DATETIME_INPUT_FORMATS = ( "%d/%m/%Y %H:%M", )
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = '/media/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Cannot fetch API data after deploying application to Heroku (works perfectly locally)

I cannot fetch the data from my Django Rest API publicly after deploying to Heroku. It works perfectly locally. When I click on the heroku webpage -> Inspect -> Console, says "Failed to load resource: net::ERR_CONNECTION_REFUSED" & "Uncaught (in promise) TypeError: Failed to fetch".
The API is located publicly on heroku and it CORRECTLY has all my data (https://xxxxxxxxxx.herokuapp.com/api).
I'm using Django backend and ReactJS frontend.
Settings.py
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['xxxxxxxxxxxxx.herokuapp.com', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'backend',
'corsheaders',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'xxxxxxxxxxxxx.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'reactapp/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',
],
},
},
]
WSGI_APPLICATION = 'xxxxxxxxxxxxx.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'reactapp/build/static'),
]
CORS_ORIGIN_WHITELIST = [
"http://localhost:3000", "http://127.0.0.1:8000", "https://xxxxxxxxxxxxx.herokuapp.com",
]
App.js
fetchTasks(){
fetch('https://xxxxxxxxxx.herokuapp.com/api')
.then(response => response.json())
.then(data =>
this.setState({
todoList:data
})
)
}
Solved! Silly mistake on my part. My data was fetching from my local API instead of my public API. I changed my code to fetch publicly but forgot to run "npm run build" in my terminal.

Path to my media file won't work in django project

I've tried to put my site that I've designed into django, and I've encountered some problemes with paths to my media file in css and javascript but now my css paths work but my javascripts file don't.
Thanks in advance for any help provided!
I've tried to change my STATIC_URL and all but it didn't work. it seems like django is changing my path for no reason.
WORKING:
How I wrote my Path into css (works.css in my project)
#font-face { font-family: gameboy; src: url('media/font/gameboy.ttf'); }
background-image: url('media/gif/drive3.gif');
NOT WORKING:
How I wrote my Path into javascript (works.js in my project)
var pic1 = 'media/picture/travis.jpg';
var pic2 = 'media/picture/snoop.jpg';
var pic3 = 'media/gif/vash.gif';
var pic4 = 'media/picture/snoop.jpg';
The http response:
[07/Aug/2019 10:23:51] "GET /works/media/picture/snoop.jpg HTTP/1.1" 404 3066
My Settings file:
Django settings for Music project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 't867#%uk)99t*28%uxk5mbj5c7)&7*x9^r&g&12*-fdja6jovl'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'Musicapp.apps.MusicappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Music.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'Music.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
Thanks again!
Thewizy

Static Files not getting loaded in Django Python

Here is the code I am trying to run:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
</style>
<script src="http://d3js.org/d3.v3.js"></script>
<script src="http://misoproject.com/js/d3.chart.js"></script>
</head>
<body>
<script src="{% static 'stock-line.js' %}"></script>
<script src="{% static 'stock-line-app.js' %}"></script>
</body>
</html>
Reference Link for Js and sample data: Reference link
My static path is: C:\Users\aims\Desktop\mysite\static
I am getting the following error in the console log:
GET http://127.0.0.1:8000/static/stock-line.js 404 (Not Found)
GET http://127.0.0.1:8000/static/stock-line-app.js 404 (Not Found)
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://misoproject.com/js/d3.chart.js with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
GET http://127.0.0.1:8000/static/stock-line.js 404 (Not Found)
GET http://127.0.0.1:8000/static/stock-line-app.js 404 (Not Found)
Pease do let me know what I have missed. I have placed the respective files in the static folder. Still file is not found. It is a mystery for me. Help me solve it.
Settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print("Base URL is \n: ",BASE_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*******'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'demod3',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
print("Statcic URL is : \n: ", STATIC_ROOT)
views.py
def testingD3(request):
return render_to_response('tt/testingD3.html', {})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('tt/', views.show),
path('pie/', views.pie),
path('dd3/', views.testingD3),
path('fera/', views.fera),
]
Gone through these questions:
Django - Static file not found
Django: static file not found
Read a blog: https://www.agiliq.com/blog/2013/03/serving-static-files-in-django/
urls.py
...
if settings.DEBUG:
urlpatterns +=
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
https://docs.djangoproject.com/en/2.1/howto/static-files/#serving-static-files-during-development

Downloaded boostrap.min.js does not work in Django template

Downloaded boostrap.min.js did not work in Django template but CDN boostrap.min.js did.
Here my base.html code which did not work:
Local boostrap.min.js not work
i can even open the link of javascript in developer mode of Chrome
When i change the code as below, it worked as normal :
CDN boostrap.min.js work
ps:This is just an example, in an other app, my downloaded boostrap CSS and static files like image and fonts worked but boostrap did not
This is my setting.py:
"""
Django settings for website1 project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'index',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'website1.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'website1.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Ho_Chi_Minh'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
On top of your html template
{% load staticfiles %}
and then you need to give src like this.
<script src="{% static 'index/js/bootstrap.min.js' %}"></script>

Categories