This is a follow-up to my previous question How to get the value of input field entered in navigation .
I'm trying to get the value of an input field in the backend- Django.
In views.py, I've included the following:
Code:
def vis(request):
if request.method == 'POST':
examples = request.POST.get('examples')
# Process the value of examples
print(examples) # not getting printed on the terminal
return render(request, "vis.html")
To get the value assigned for the placeholder
, I used the below.
function getExampleValue() {
const fid = document.getElementById("examples").value;
console.log(fid)
const fpath = `/path/${fid}.json`;
fetch(fpath)
.then(response => response.json())
.then( data => {
var x = data.x
})
However, I cannot directly specify the filename in fetch
since it fails to load from the file system in Django. So I want to receive the value and pass it to fetch
, the value received (filename
) will be used for loading a file from the path using fetch
.
So I specified form
in vis.html.
<form class="form" id="myForm" action="{% url 'visualization' %}" method="post">
But I am not able to receive the value in the backend.
I want to receive the value set for the placeholder
in examples
:
<input id="examples" class="input" name="examples" placeholder=" " onfocusout=getExampleValue() />
Complete HTML below:
{% load static %}
<html>
<head>
<nav class="nav">
<ul class="nav__links">
<li class="nav__item">
<a class="nav__link" href="{% url 'home' %}">Home</a>
</li>
<li class="nav__item">
<a class="nav__link" href="{% url 'about' %}">About</a>
</li>
<li class="nav__item">
<a class="nav__link" href="{% url 'login' %}">Login</a>
</li>
</ul>
</nav>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
Visualization
</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdn.plot.ly/plotly-1.58.5.min.js"></script>
<style>
.graph-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.main-panel {
width: 100%;
height: 800px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.side-panel {
position: absolute;
top: 0px;
bottom: 0;
right: -300px;
width: 300px;
background-color: red;
transition: right 0.5s;
overflow-y: auto;
padding: 20px;
}
.side-panel.open {
right: 0;
}
.arrow {
position: absolute;
top: 20px;
left: 20px;
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-right: 20px solid #2196F3;
cursor: pointer;
}
.arrow.open {
transform: rotate(180deg);
}
.left-arrow {
position: absolute;
top: 20px;
right: 20px;
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-right: 20px solid #2196F3;
cursor: pointer;
}
.open .left-arrow {
transform: rotate(180deg);
}
{# Added Code for side bar #}
.sidenav {
height: 100%;
width: 250px;
position: fixed;
z-index: 3;
top: 80px;
left: 0px;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.open .sidenav {
left: -20px;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s;
}
.sidenav a:hover {
color: #f1f1f1;
}
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
#main {
transition: margin-left .5s;
padding: 16px;
margin-left: 250px;
}
.form {
border-radius: 20px;
box-sizing: border-box;
height: 500px;
padding: 20px;
width: inherit;
font-size: 1.8rem;
}
.title{
color: #eee;
font-family: "Bitstream Vera Sans Mono", Monaco, "Courier New", Courier, monospace;
font-size: 25px;
font-weight: 400;
padding-left: 15px;
}
.input-container {
height: 50px;
position: relative;
width: 100%;
}
.soura {
margin-top: 40px;
}
.ic2 {
margin-top: 30px;
}
.input {
background-color: #303245;
border-radius: 12px;
border: 0;
box-sizing: border-box;
color: #eee;
font-size: 18px;
height: 100%;
outline: 0;
padding: 4px 20px 0;
width: 100%;
}
.cut {
background-color: black;
border-radius: 10px;
height: 20px;
left: 20px;
position: absolute;
top: -20px;
transform: translateY(0);
transition: transform 200ms;
}
.arrowsize-cut{
width: 80px;
}
.concentration-cut{
width: 105px;
}
.example-cut{
width: 140px;
}
.labelsize-cut{
width: 80px;
}
.input:focus ~ .cut,
.input:not(:placeholder-shown) ~ .cut {
transform: translateY(8px);
}
.placeholder {
color: #65657b;
font-family: sans-serif;
left: 20px;
line-height: 14px;
position: absolute;
transform-origin: 0 50%;
transition: transform 200ms, color 200ms;
top: 20px;
}
.input:focus ~ .placeholder,
.input:not(:placeholder-shown) ~ .placeholder {
transform: translateY(-30px) translateX(10px) scale(0.75);
}
.input:not(:placeholder-shown) ~ .placeholder {
color: #808097;
}
.input:focus ~ .placeholder {
color: #dc2f55;
}
.submit {
background-color: #08d;
border-radius: 12px;
border: 0;
box-sizing: border-box;
color: #eee;
cursor: pointer;
font-size: 18px;
height: 30px;
margin-top: 38px;
outline: 0;
text-align: center;
width: 100%;
}
.submit:active {
background-color: #06b;
}
/* Adding the button */
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
/* Code for download button */
.hide {
max-height: 0 !important;
}
.dropdown{
border: 0.1em solid white;
width: 18em;
margin-bottom: 1em;
margin-top: 2rem;
position: relative;
}
.dropdown .title{
margin: .3em .3em .3em .3em;
width: 100%;
}
.dropdown .title .fa-angle-right{
float: right;
margin-right: .7em;
transition: transform .3s;
}
.dropdown .menu{
transition: bottom .5s ease-out;
background-color: black;
min-width: 18rem;
/* bottom: 7.9em; */
border: solid white;
overflow: hidden;
position: absolute;
font-size: 10px;
}
.dropdown .menu .option{
margin: .1em .1em .1em .1em;
margin-top: 0.3em;
color: white;
font-size: 10px;
}
.dropdown .menu .option:hover{
background: rgba(0,0,0,0.2);
}
.pointerCursor:hover{
cursor: pointer;
}
.rotate-90{
transform: rotate(-90deg);
}
.clickable {
cursor: pointer;
text-decoration: underline;
color: blue;
}
.dropdown .download-button {
position: absolute;
top: 0;
right: -60px; /* Adjust the position as needed */
width: 50px;
height: 100%;
background-color: #333;
border: none;
border-radius: 0 4px 4px 0;
color: white;
font-size: 16px;
cursor: pointer;
}
.dropdown .download-button i {
margin-top: 6px;
}
</style>
</head>
<body>
<div id = "main" style="margin-left: 7rem;">
<div id="mySidenav" class="sidenav">
<div class="left-arrow" onclick="toggleNav()"></div>
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<form class="form" id="myForm" action="{% url 'visualization' %}" method="post">
{% csrf_token %}
<div class = "title">settings</div>
<div class="input-container soura">
<input id="examples" class="input" name="examples" placeholder=" " onfocusout=getExampleValue() />
<div class="cut example-cut"></div>
<label for="examples" class="placeholder">
Examples
<span id="example1" class="example" onclick="setExampleValue('example1')"> #1</span>
<span id="example2" class="example" onclick="setExampleValue('example2')"> #2</span>
</label>
</div>
<div class="input-container ic2">
<input id="arrowsize" class="input" type="text" placeholder=" " />
<div class="cut arrowsize-cut"></div>
<label for="arrowsize" class="placeholder">arrow size</label>
</div>
<div class="input-container ic2">
<input id="labelsize" class="input" type="text" placeholder=" " />
<div class="cut arrowsize-cut"></div>
<label for="labelsize" class="placeholder">label font-size</label>
</div>
<button type="submit" class="submit">Submit</button>
</form>
<div class='dropdown'>
<a class='title pointerCursor'>Download <i class="fa fa-angle-down"></i></a>
<div class='menu pointerCursor hide'>
<div class='option' id='option1'><a href="#">PNG</a></div>
<div class='option' id='option2'><a href="#">SVG</a></div>
<div class='option' id='option3'><a href="#">JPEG</a></div>
</div>
<button class="download-button"><i class="fa fa-download"></i></button>
</div>
</div>
<div class="graph-container">
<div id="network" class="main-panel"></div>
<div id="graph" class="side-panel">
<div class="arrow"></div>
</div>
</div>
<script src="https://kit.fontawesome.com/adf1f3a283.js" crossorigin="anonymous"></script>
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}
// examples
function setExampleValue(value) {
document.getElementById("examples").value = value;
}
// download options
const dropdownTitle = document.querySelector('.dropdown .title');
const dropdownMenu = document.querySelector('.dropdown .menu');
dropdownTitle.addEventListener('click', function () {
dropdownMenu.classList.toggle('hide');
});
document.querySelectorAll('.dropdown .option').forEach(function (option) {
option.addEventListener('click', function () {
// Handle the selected download option here
const selectedOption = this.textContent;
console.log('Selected option:', selectedOption);
// Display the selected option in the dropdown title
dropdownTitle.textContent = `Download ${selectedOption}`;
// Close the dropdown menu
dropdownMenu.classList.add('hide');
});
});
function getExampleValue() {
const fid = document.getElementById("examples").value;
console.log(fid)
const fpath = `${fid}.json`;
//read the data from the json file
fetch(fpath)
.then(response => response.json())
.then(data => {
var x = data.x
})
}
</script>
</div>
</body>
</html>
Suggestions on how to receive the placeholder
value (filename) in the backend and how to pass the filename to the HTML for fetch
function, will be really helpful.
EDIT:
I've included the following for
function getCookie(name) {
const cookieValue = document.cookie
.split('; ')
.find(cookie => cookie.startsWith(name + '='));
if (cookieValue) {
return decodeURIComponent(cookieValue.split('=')[1]);
}
return null;
}
But I am not sure when async function getExampleValue()
function has to be called.
Suggestions will be really helpful.
EDIT2:
I've changed onfocusout to onchange
<input id="examples" class="input" name="examples" placeholder=" " onchange="getExampleValue()" />
I am trying to check if the function call getExampleValue
works right. But
async function getExampleValue() {
const filename = document.getElementById("examples").value;
console.log(filename)
doesn't return display the value.
Its not being printed because of a few factors. But mainly because fetch
by default sends a GET
request, thus its falling off on your first view condition if request.method == 'POST'
.
To
data with fetch you need to specify the method. Also, in Django you must POST
retrieve csrftoken
from cookies and attach it to your request headers
:
<script>
...
function getCookie(name) {
...
}
async function getExampleValue() {
const filename = document.getElementById("examples").value;
const csrftoken = getCookie("csrftoken");
const url = "{% url 'visualization' %}"
await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": csrftoken
},
body: JSON.stringify({filename})
})
.then(response => response.json())
.then(data => {
console.log(data)
});
}
</script>
In the backend, use HttpRequest.body
together with Python json
to load and parse data.
views.py
from django.http import JsonResponse
import json
def vis(request):
if request.method == 'POST':
data = json.loads(request.body)
filename = data.get('filename', None)
if filename:
with open(f'path/to/files/{filename}.json') as f:
file_json_data = json.loads(f.read())
return JsonResponse(file_json_data)
return render(request, "vis.html")
Alghouth, I must say that normally you would implement two different views. One for rendering your page and another for your async
request.