I know similar questions have been asked before but I am very new to django and js. I have tried many solutions but I am not able to make sense of many and able to run them. So I am writing my code and the solution that I have tried. Can someone please tell me what mistake am I doing.
In my views.py I am handling a file which produces some results. These results are in the form of a Dataframe(used pandas). From this dataframe I am calculating few integer values which are stored in variables: tot,p,lp,us. I am also getting 3 sub-dataframes namely: dfp,dflp,dfus. I need to display all these on the webpage so I am sending them to an html: uploaded.html as shown below.
dict_1 = {'Path':p, 'LPath':lp, 'USig':us}
json1 = json.dumps(dict_1)
return render(request, 'uploaded.html', locals(), {'js_json1': json1, 'TotVar': tot})
The above code just sends the variables and not the dataframe as I don't know how to do it. I have handled it in my uploaded.html in the following way:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Upload File-Hereditary Cancers</title>
<link rel="stylesheet" href="/static/css/style.css" type="text/css">
<script type="text/javascript">
function results()
{
var totalvariants = {{TotVar}};
document.getElementById("totvar").innerHTML = "Total number of variants are: "+totalvariants;
}
</script>
</head>
<body>
<div id="header">
<div>
<div class="logo">
Hereditary Cancers
</div>
<ul id="navigation">
<li>
Home
</li>
<li>
About
</li>
<li class="active">
Upload File
</li>
<li>
Team
</li>
<li>
Contact Us
</li>
</ul>
</div>
</div>
<div>
{% if saved %}
<strong>Your file was uploaded.</strong>
<button onclick = "results()">Results</button>
<p id = "totvar">This will change</p>
{% endif %}
{% if not saved %}
<strong>Your file was not uploaded.</strong>
{% endif %}
</div>
<div id="footer">
<div class="clearfix">
<div id="connect">
</div>
<p>
© 2023 Zerotype. All Rights Reserved.
</p>
</div>
</div>
</body>
</html>
I am creating a button in my html which activates the script on click. I haven't done much in my script because I don't know how to. I have just tried to display the tot variable which is also not getting displayed.Can anyone tell me the complete script on how I can handle dataframes and variables in my js function and display their results.
i don't know what are you do, but you send locals() as context. first, why you did this? you don't use them in template. second, you should send your context in third parameter in render() and if you so need locals in template context, write something like this:
ctx = locals()
ctx.update(
js_json1 = json1,
TotVar = tot,
)
return render(request, 'uploaded.html', ctx)
or
ctx = {
'locals': locals(),
'js_json1': json1,
'TotVar': tot,
}
return render(request, 'uploaded.html', ctx)
https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render
Related
I have 2 buttons orders, and suppliers., and want to show data in a Django web app when the corresponding button is clicked. To do this my home.html looks like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".button_order").click(function(){
$(".myorders").show();
$(".mysupplier").hide();
});
$(".button_supplier").click(function(){
$(".myorders").hide();
$(".mysupplier").show();
});
});
</script>
syle.css looks like;
.myorders,
.mysupplier{
font-size: 25px;
display: none;
}
This works perfectly fine until I use normal data like;
<body>
{%block content %}
<button class="button_order" >ORDERS</button>
<button class="button_supplier" >SUPPLIER</button>
<p class="myorders" >
This is my order
</p>
<p class="mysupplier">
my supplier is cool
</p>
</body>
But when I try to use data into <p class="mysupplier"> or <p class="myorders" > from my databases, the hide property no longer works, like below part.
<p class="myorders">
{% for element in orders %}
{% for key,val in element.items %}
<ul><li>{{key}}:{{val}}</li></ul>
{% endfor %}
<hr class="new1">
{% endfor %}
</p>
I should get Order data from database only when ORDER button is clicked, but my server shows all data from before without even clicking the button. How to maintain hide and show the property of my data.
my views.py looks like
from django.shortcuts import render
client = MongoClient("mongodb://localhost:27017/")
db=client.inventory_data
def home(request):
collection_data_1 = db['orders']
orders = list(collection_data_1.find())
collection_data_2= db['suppliers']
suppliers = list(collection_data_2.find())
return render(request,'home.html',{'orders': orders,'suppliers':suppliers})
The loop in template is executed when rendering template. You pass all your data from view to template. if you just want to hide it from display add to your js:
<script>
$(document).ready(function(){
$(".mysupplier").hide();
$(".myorders").hide();
$(".button_order").click(function(){
$(".myorders").show();
$(".mysupplier").hide();
});
$(".button_supplier").click(function(){
$(".myorders").hide();
$(".mysupplier").show();
});
});
</script>
but if you would like to dynamicly fetch current data from db by pressing button i recommend use htmx (htmx.org)
Basically I have to develop a Tic-Tac-Toe game, here is the HTML file which I can't rewrite only reformat a bit, but the idea should stay the same.
{% block content %}
<nav class="navbar fixed-top navbar-light">
<button id="retry-button" class="btn btn-success">Try again?</button>
Reset settings
</nav>
<div id="game-board" class="mb-3" data-row-num="{{ row_num }}" data-col-num="{{ col_num }}" data-win-size="{{ win_size }}">
{% for row in range(row_num) %}
<div>
{% for col in range(col_num) %}
<div class="game-cell"
data-coordinate-x="{{ col }}"
data-coordinate-y="{{ row }}"></div>
{% endfor %}
</div>
{% endfor %}
</div>
{% endblock %}
As you can see i have a game-cell class which contains by default 9 elements. I would like to return the data-coordinate-x and data-coordinate-y when I click one of the game-cells. I had a previous try but if I clicked it returned all of the blocks not just the one i clicked on. I have to write it in Js. If you can point me in the right direction that's more than enough for me.
Thanks!
If I understood correctly, you need to access data attributes of your game-cell element. In order to do this, you need to select the element by some ID or class. I have modified your code a little to make it run inside stackoverflow`s platform. I have added an ID which i called "unique" and I also set some values into your coordinate-x and y data attributes. Please review the code bellow and see how I managed to get those data attributes. It's important to notice that this is not the only way to access them.
var gamecell = document.getElementById('unique');
console.log(gamecell.dataset.coordinateX);
console.log(gamecell.dataset.coordinateY);
<nav class="navbar fixed-top navbar-light">
<button id="retry-button" class="btn btn-success">Try again?</button>
Reset settings
</nav>
<div id="game-board" class="mb-3" data-row-num="{{ row_num }}" data-col-num="{{ col_num }}" data-win-size="{{ win_size }}">
<div>
<div class="game-cell" id="unique"
data-coordinate-x="172"
data-coordinate-y="273"></div>
</div>
</div>
Its also possible to get these values using the getAttribute method.
var elem = document.getElementById('unique');
var coordX = elem.getAttribute('data-coordinateX');
var coordY = elem.getAttribute('data-coordinateY');
Please, take a look at this page, it explains some aspects of data attributes:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
Simply access your clicked game-cell by: (it will find the clicked coordinateX and coordinateY)
document.querySelectorAll('.game-cell').forEach((game) => {
game.addEventListener('click',function(event){
console.log(game.dataset.coordinateX);
console.log(game.dataset.coordinateY);
});
});
you must to get your element by class name or id(add an id)
than you can get its attributes like this
let gameCell = document.getElementById('game-cell-id');// id for example
gameCell.getAttribute('data-coordinate-x')
I am working on a turn-based game where players can, but don't have to, gain ownership of certain spaces on the game board. My detail view in shows the spaces owned by each player, and I use a loop to display all owned spaces:
<small class="text-muted">Spaces Owned</small>
<div class="list-group list-group-flush">
{% for space in player.space_set.all %}
<a class="list-group-item" data-toggle="modal" data-target="#spaceModal" id="modalButton">
{{ space.name }}
</a>
{% endfor %}
</div>
I want to be able to populate a modal with all detailed information about whichever space is clicked on (hence why I'm using the anchor tag instead of a div, though I guess it might not matter as much). The modal would look something like this, though the goal is to populate it using appropriate IDs, etc using the response from the AJAX call instead of the template variables currently used as placeholders:
<div class="modal fade" id="spaceModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="wrapper">
<div class="box">
<h2>{{ space.name }}</h2>
<div class="float-left">{{ space.location }}</div>
<div class="float-right">{{ space.defense_points }}</div>
<br />
<div class="float-right">{{ space.attack_points }}</div>
</div>
</div>
</div>
</div>
</div>
</div>
What I want to be able to do is use an AJAX call to populate the modal for each space as it is clicked. I have the server-side function set up okay and it is correctly returning the JSON needed when I process a simple get request (I'm using the following url pattern):
from django.urls import path
urlpatterns = [
path('<int:game>/space_data/<int:space>', get_space_data, name = 'get_space_data'),
]
with my views.py defined as:
def get_space_data(request,game,space):
game = Game.objects.get(pk=game)
space = game.space_set.get(location=space)
data = {
'name': space.name,
'location': space.location,
'defense_points': space.defense,
'attack_points': space.attack,
}
return JsonResponse(data)
Right now the JS that I'm using to test usage is the following:
<script>
$("#modalButton").click(function(){
var space = "{{ space }}"
console.log(space)
alert('Modal Button Clicked')
})
</script>
Summary
Essentially all I want to be able to do, which I can't figure out how to do, is pass the space variable to the JS code so that I can build the appropriate AJAX call within the last script code.
To touch on what Daniel wrote, what I was asking was simply how to pass Django template data to a JQuery script, which I would then use in an AJAX call. I figured it out, though, and will post my answer here instead of just deleting the question.
The modal pop-up anchor tag should look like this:
<small class="text-muted">Spaces Owned</small>
<div class="list-group list-group-flush">
{% for space in player.space_set.all %}
<a class="list-group-item" data-toggle="modal" data-target="#spaceModal" id="modalButton" data-location="{{ space.location }}">
{{ space.name }}
</a>
{% endfor %}
</div>
and the resulting JQuery code is as follows:
<script>
$("#modalButton").click(function(){
console.log($(this).data('location'))
alert('Modal Button Clicked')
})
</script>
From this I will be able to add an actual AJAX call to the script and pull the data as needed.
in this way you send the variables to the js to use them in the ajax
{% block scripts %}
<script>
var name = {{space.name}}
var location = {{space.location}}
</script>
<!-- JS Template -->
<script src="{% static 'folder/name.js' %}"></script>
{% endblock scripts %}
and your js
$.ajax({
url: url,
method: "",
data: {
"name" : name,
"location":location
},
success: function (_response) {
},
)
Hey guys I am beyond frustrated/exhausted trying to fix this unicode code \u200e showing in my web page. I tried everything I can think of. Here is what my page looks like, its data scraped articles from news.google.com and shown on my page with the time submission (the time submission is where the \u200e pops up everywhere)
http://i.imgur.com/lrqmvWG.jpg
I am going to provide my views.py, my articles.html (the page in the picture that is set up to display everything), and header.html (for whatever reason. But this is the parent template of articles.html for the CSS inheriting). Also, I researched and know that the \u200e is a left-to-right mark and when I inspect the source in news.google.com, it pops up in the time submission element as
like so:
<span class="al-attribution-timestamp">51 minutes ago</span>
I tried editing the views.py to encode it using .encode(encoding='ascii','ignore') or utf-8 or iso-8859-8 and a couple other lines of code I found researching deep on google but it still displays \u200e everywhere. I put it in so many different parts of my views.py too even right after the for loop (and right before + after it gets stored as data in the variable "b" and its just not going away. What do I need to do?
Views.py
def articles(request):
""" Grabs the most recent articles from the main news page """
import bs4, requests
list = []
list2 = []
url = 'https://news.google.com/'
r = requests.get(url)
sta = ""
try:
r.raise_for_status() == True
except ValueError:
print('Something went wrong.')
soup = bs4.BeautifulSoup(r.text, 'html.parser')
for listarticles in soup.find_all('h2', 'esc-lead-article-title'):
a = listarticles.text
list.append(a)
for articles_times in soup.find_all('span','al-attribution-timestamp'):
b = articles_times.text
list2.append(b)
list = zip(list,list2)
context = {'list':list, 'list2':list2}
return render(request, 'newz/articles.html', context)
articles.html
{% extends "newz/header.html" %}
{% block content %}
<script>
.firstfont (
font-family: serif;
}
</script>
<div class ="row">
<h3 class="btn-primary">These articles are scraped from <strong>news.google.com</strong></h3><br>
<ul class="list-group">
{% for thefinallist in list %}
<div class="col-md-15">
<li class="list-group-item">{{ thefinallist }}
</li>
</div>
{% endfor %}
</div></ul>
{{ list }}
{% endblock %}
header.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sacred Page</title>
<meta charset="utf-8" />
{% load staticfiles %}
<meta name="viewport" content = "width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'newz/css/bootstrap.min.css' %}" type = "text/css"/>
<style type="text/css">
html,
body {
height:100%
}
</style>
</head>
<body class="body" style="background-color:#EEEDFA">
<div class="container-fluid" style="min-height:95%; ">
<div class="row">
<div class="col-sm-2">
<br>
<center>
<img src="{% static 'newz/img/profile.jpg' %}" class="responsive-img" style='max-height:100px;' alt="face">
</center>
</div>
<div class="col-sm-10">
<br>
<center>
<h3><font color="007385">The sacred database</font></h3>
</center>
</div>
</div><hr>
<div class="row">
<div class="col-sm-2">
<br>
<br>
<!-- Great, til you resize. -->
<!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#E77200">-->
<div class="well bs-sidebar" id="sidebar" style="background-color:#E1DCF5">
<ul class="nav nav-pills nav-stacked">
<li><a href='/'>Home</a></li>
<li><a href='/newz/'>News database</a></li>
<li><a href='/blog/'>Blog</a></li>
<li><a href='/contact/'>Contact</a></li>
</ul>
</div> <!--well bs-sidebar affix-->
</div> <!--col-sm-2-->
<div class="col-sm-10">
<div class='container-fluid'>
<br><br>
<font color="#2E2C2B">
{% block content %}
{% endblock %}
{% block fool %}
{% endblock fool %}
</font>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid" style='margin-left:15px'>
<p>Contact | LinkedIn | Twitter | Google+</p>
</div>
</footer>
</body>
</html>
If you want, you can use replace() to strip the character from your string.
b = articles_times.text.replace('\u200E', '')
The reason that you see \u200E in the rendered html instead of is that you are including the tuple {{ thefinallist }} in your template. That means Python calls repr() on the tuple, and you see \u200E. It also means you see the parentheses, for example ('headline' '\u200e1 hour ago')
If you display the elements of the tuple separately, then you will get in the template instead. For example, you could do:
{% for headline, timeago in list %}
<div class="col-md-15">
<li class="list-group-item">{{ headline }} {{ timeago }}
</li>
</div>
{% endfor %}
Need achieve some features like [http://webonise.co.uk/][1] when click on contact,resume,resources link will update (location URL&div content) but without refresh the page.
Flask view function
#app.route('/')
def index():
flash('Welcome')
return render_template('index.html')
Under index.html is extends base.html
{% block content %}
{{super()}}
<section class="content">
<i class="mdi-event"></i>Event
<i class="mdi-contact"></i>Contact
<div class="board">
{# dynamic template #}
{# without using {{% include 'event.html' %}} #}
</div>
</section>
{%- endblock %}
How can i dynamic rendar event.html / contact.html content when different link is click and rendar under {# dynamic template #} without refresh the page ?
<!--event.html-->
<ul class="list">
<li>
<h3>123</h3>
<p>abc</p>
</li>
</ul>
What I try
import jinja2 Environment but still no idea how to achieve this
env = Environment(autoescape=True,
loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
#app.route('/')
def index():
board = env.get_template('event.html')
flash('Welcome Home Tyler')
return render_template('index.html', board=board)
Is there really need ajax technique get/post method to achieve all this?
You can use Flask-Sijax which helps you add Sijax support to your Flask app. Sijax is a python/jquery library that makes AJAX easy to use on your web applications. Alternatively you could do this:
<script>
$(document).ready( function() {
$('#next').click(function() {
$.ajax("{{ url_for('yourroute') }}").done(function (reply) {
$('#container').html(reply);
});
});
});
</script>
<input type="button" id="next" value="Next" />
<div id="container"></div>