Localhost with Django Rest from MySQL and HTML based webclient not working as expected

Multi tool use
Localhost with Django Rest from MySQL and HTML based webclient not working as expected
I am having problem with my little project I am working on and come to you with for hope to get some assistance.
Firstly I will ask a simple question which might be origin of my problem - but in case it is not I will provide my code from REST settings and webclient side. So this is expected to be long post.
I am able to use my webclient from local machine, where localhost 127.0.0.1:8000 is running, and everything is working like a charm. Webclient is run from the browser from my schools public_html system. How this is set up, I am not 100% sure, but basically we can set up webpage
run from school system using the folder and access the pages from web. I got index.html and stuff like JS, Tabulator extension, Jquery, Ajax
etc running from scripts or locally installed and included in tags.
webpage
JS, Tabulator extension, Jquery, Ajax
I can use GET/PUT/DELETE
etc commands as I have set them up - so everything works when I am working on local machine through webclient
.
GET/PUT/DELETE
webclient
Question is:
Am I supposed to be able to connect the REST from non-local machine when localhost 127.0.0.1:8000 is running and up on the localmachine
where webclient
is hosted from?
localmachine
webclient
So far I have not been successful to do so - and I am wondering if my hypothesis is wrong that I should be able to.
When I use non-local machine the GET request doesn't get any answer nor shows up on the CMD
where 127.0.0.1:8000 is running. Local Machine I get a reply even when I set up it to fail (for testing). But non-local machine doesn't seem to get _anything.
CMD
If my hypothesis is correct that it should work - would the problem be yet again with the CORS?
Any suggestions?
Django 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__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secretkey'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
ACCESS_CONTROL_ALLOW_ORIGIN = ['http://www.cc.puv.fi']
ACCESS_CONTROL_ALLOW_HEADER = ['X-Requested-With', 'Content-Type', 'Origin', 'Cache-Control', 'Pragme', 'Authorization', 'Accept', 'Accept_Encoding']
ACCESSS_CONTROL_ALLOW_METHODS = ['PUT', 'POST', 'GET', 'OPTIONS', 'DELETE']
# Application definition
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'lab',
]
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',
]
CORS_ORIGIN_ALLOW_ALL = True
#CORS_ALLOW_CREDENTIALS = True
#CORS_ORIGIN_WHITELIST = (
# 'http://www.cc.puv.fi',
# 'http://127.0.0.1:8000',
#)
ROOT_URLCONF = 'lab.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 = 'lab.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbname',
'USER': 'ursername',
'PASSWORD': 'password',
'HOST': 'host',
'PORT': 'port',
}
}
# 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 = 'UTC'
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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'D:VAMKlabstatic', # HUOMAA D levy!!
]
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'rest_framework_xml.renderers.XMLRenderer',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
}
One of the pages that uses REST:
Vamk Database
https://code.jquery.com/jquery-3.3.1.min.js
<!-- SCRIPT FOR AXIOS -->
<!-- SCRIPT FOR JQUERY UI -->
https://code.jquery.com/ui/1.12.1/jquery-ui.min.js
<!-- SCRIPT FOR -->
<!-- SCRIPT FOR TABULATOR -->
<link rel="stylesheet" href="dist/css/tabulator.css">
http://dist/js/tabulator.js
<!-- SCRIPT FOR -->
<!-- SCRIPT FOR -->
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js
<!-- SCRIPT FOR -->
<!-- DOWNLOAD LIBS -->
http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js
https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js
https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.3.2/jspdf.plugin.autotable.js
//STORED PASSWORD AND USERNAME
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "extra.txt", false);
xhttp.send();
var x = xhttp.responseText;
var auther = x;
var validation = "";
// CHECKS IF THERE IS AUTH TOKEN IN DB
function getAuth(){
var request = new XMLHttpRequest();
request.open("GET", "http://127.0.0.1:8000/Valids/", false);
request.setRequestHeader("Authorization", "Basic " + btoa(auther));
request.setRequestHeader("X-CSRFToken", readCookie("csrftoken"));
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send();
array = JSON.parse(request.responseText);
if (array == "") {
validation = false;
}
else {
validation = true;
}
return validation;
}
//COOKIE CHECK
function readCookie(name) {
var nameEQ = encodeURIComponent(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i
</head>
<body>
getAuth();
VAMK Laboratory Database
Toggle Options
Return
Logout
</div>
if ( validation != true) {
console.log(validation);
document.getElementById("noacc").style.display='block';
document.getElementById("options").style.display='none';
document.getElementById("example-table").style.display='none';
}
else {
document.getElementById("noacc").style.display='none';
// DIV HIDING SCRIPT
$("#show-ops").click(function(){
if (document.getElementById("ops").style.display == 'none')
document.getElementById("ops").style.display='block';
else
document.getElementById("ops").style.display='none';
});
/*
// Performing a GET request !
axios({
method: 'GET',
url: 'http://127.0.0.1:8000/Vamk_Rs/',
responseType: 'json'
})
.then(function(response){
*/
var response = new XMLHttpRequest();
response.open("GET", "http://127.0.0.1:8000/Vamk_Rs/", false);
response.setRequestHeader("Authorization", "Basic " + btoa(auther));
response.setRequestHeader("X-CSRFToken", readCookie("csrftoken"));
response.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
response.send();
var array = JSON.parse(response.responseText);
console.log(array);
if (response.status == 200) {
// POSTING UPDATED CELL TO REST
$("#example-table").tabulator({
cellEdited:function(cell){
var data = cell.getData();
var url = data.url;
var posting = JSON.stringify(data);
var update = new XMLHttpRequest();
update.open("PUT", url, true);
update.setRequestHeader("Authorization", "Basic " + btoa(auther));
update.setRequestHeader("X-CSRFToken", readCookie("csrftoken"));
update.setRequestHeader("Content-Type", 'application/json');
update.send(posting);
},
// TABLE LAYOUT
layoutColumnsOnNewData:true,
layout:"fitColumns",
responsiveLayout:"hide",
placeholder:"No Data Set",
pagination:"local",
paginationSize:50,
addRowPos:"top",
selectable: true,
align: 'center',
columns:[
{title:"Select Row", field:"", width:'100'},
{title:"Category", field:"category", headerFilter:"input", align:"center", editor: "input"},
{title:"Value", field:"strenght", headerFilter:"input", editor:"input", width: '80'},
{title:"Unit", field:"unit", headerFilter:"input", editor:"input", width: '80'},
{title:"Part Number", field:"manufacturer_part_number", headerFilter:"input", editor:"input", width: '160'},
{title:"Location", field:"storing_location", headerFilter:"input", editor:"input"},
{title:"EC19 Location", field:"storing_location_ec19", headerFilter:"input", editor:"input"},
{title:"Type", field:"ptypename", headerFilter:"input", editor:"input"},
{title:"Description", field:"description", headerFilter:"input", editor:"input", width: '180'},
{title:"Order Number Elfa", field:"order_number_elfa", headerFilter:"input", editor:"input", width: '150'},
{title:"Order Number Farnell", field:"order_number_farnell", headerFilter:"input", editor:"input", width: '160'},
{title:"Amount", field:"a", editor:"input", width: '80', headerFilter:"input"},
{title:"Tilattu", field:"tilattu", editor:"input", width: '80', headerFilter:"input"},
{title:"Kuittaus", field:"kuittaus", editor:"input", width: '80', headerFilter:"input"},
],
});
// DOWNLOAD OPTIONS!!!
//trigger download of data.csv file
$("#download-csv").click(function(){
$("#example-table").tabulator("download", "csv", "data.csv");
});
//trigger download of data.json file
$("#download-json").click(function(){
$("#example-table").tabulator("download", "json", "data.json");
});
//trigger download of data.xlsx file
$("#download-xlsx").click(function(){
$("#example-table").tabulator("download", "xlsx", "data.xlsx", {sheetName:"My Data"});
});
//trigger download of data.pdf file
$("#download-pdf").click(function(){
$("#example-table").tabulator("download", "pdf", "data.pdf", {
orientation:"portrait", //set page orientation to portrait
title:"Example Report", //add title to report
});
});
// ADD AND DELETE ROWS
//Add row on "Add Row" button click
$("#add-row").click(function(){
$("#example-table").tabulator("addRow", {});
var data = {
"category": "",
"strenght": "",
"manufacturer_part_number": "",
"storing_location": "",
"storing_location_ec19": "",
"ptypename": "",
"tolerance": "",
"description": "",
"order_number_elfa": "",
"order_number_farnell": null,
"a": "",
"tilattu": "",
"kuittaus": ""
}
posting = JSON.stringify(data);
var request = new XMLHttpRequest();
var url = "http://127.0.0.1:8000/Vamk_Rs/";
request.open("POST", url, true);
request.setRequestHeader("Authorization", "Basic " + btoa(auther));
request.setRequestHeader("X-CSRFToken", readCookie("csrftoken"));
request.setRequestHeader("Content-Type", 'application/json');
request.send(posting);
});
//Delete row on "Delete Row" button click
$("#del-row").click(function(){
var rows = $('#example-table').tabulator("getSelectedRows");
console.log(rows);
$.each(rows, function(index, row) {
console.log(rows);
row.delete();
//SENDING INFO OF DELETED ROWS TO REST
var data = row.getData();
console.log(data);
posting = JSON.stringify(data);
var request = new XMLHttpRequest();
var url = data.url;
request.open("DELETE", url, true);
request.setRequestHeader("Authorization", "Basic " + btoa(auther));
request.setRequestHeader("X-CSRFToken", readCookie("csrftoken"));
request.setRequestHeader("Content-Type", 'application/json');
request.send(posting);
});
});
// INIATE THE TABLE
$("#example-table").tabulator("setData", array);
}
}
function logout(){
var req = new XMLHttpRequest();
req.open("GET", "http://127.0.0.1:8000/Valids/", false);
req.setRequestHeader("Authorization", "Basic " + btoa(auther));
req.setRequestHeader("X-CSRFToken", readCookie("csrftoken"));
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.send();
var tmpStr = req.responseText;
var newStr = tmpStr.substring(1, tmpStr .length-1);
console.log("newStr= " + newStr);
var obj = JSON.parse(newStr);
console.log("OBJ = " + obj);
var url = obj.url;
var del = new XMLHttpRequest();
del.open("DELETE", url, false);
del.setRequestHeader("Authorization", "Basic " + btoa(auther));
del.setRequestHeader("X-CSRFToken", readCookie("csrftoken"));
del.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
del.send();
window.location.href='index.html';
}
</div>
</body>
</html>
Sorry, my code is really messy at the moment - been trying different things to fix the problem and have not cleaned it up yet. Hope you are able to read it.
Also sorry if I have made mistakes with the text, English is not my first language.
Hoping to see your replies! Thanks!
Yes. I run it with "python manage.py runserver 127.0.0.1:8000"
– Honia
Jul 4 at 6:15
this ip use for local machine. if you want to publish your program, you should run with a public ip, for example "python manage.py runserver 179.9.128.87:8000"
– Mohammad Ali
Jul 4 at 6:21
Oh gosh, I feel so silly! It does indeed work now. Thank you so much!
– Honia
Jul 4 at 6:52
if it was good hit the comment
– Mohammad Ali
Jul 4 at 7:07
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
How you run your program on the machine? you just use 'python manage.py runserver' command?
– Mohammad Ali
Jul 4 at 4:12