Mutiple bokeh Charts in django template - django

I don't understand how I can set up several Bokeh Chart in my django template. I have read this page https://docs.bokeh.org/en/latest/docs/user_guide/embed.html which supposed to explain this but it is not clear at all.
Here is my view :
def Bokehplot(request):
source = ColumnDataSource(S.df)
p = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc")
p.line("date", "Te", source = source, line_width = 2,color = "green", alpha = 0.6)
q = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc")
q.line("date", "Tr", source = source, line_width = 2,color = "red", alpha = 0.6)
plots = {'Red': p, 'Blue': q}
script, div = components(plots)
return render(request, 'batterie/results.html', locals())
{{div|safe}} gives the 2 divs on a row. I would like to access div1 (first graph) and div2 (second graph) in order to put them in 2 different bootstrap columns ? Any help is welcome. Thanks!

Got my answer, very simple. My View :
def Bokehplot(request):
source = ColumnDataSource(S.df)
p = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc")
p.line("date", "Te", source = source, line_width = 2,color = "green", alpha = 0.6)
q = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc")
q.line("date", "Tr", source = source, line_width = 2,color = "red", alpha = 0.6)
plots = {'Red': p, 'Blue': q}
script, div = components(plots)
div1 = div["Red"]
div2 = div["Blue"]
return render(request, 'batterie/results.html', locals())
My template :
<div class = "row">
<div class = "col-sm-6 p-3 text-center">
{{ div1 | safe }}
</div>
<div class = "col-sm-6 p-3 text-center">
{{ div2 | safe }}
</div>
</div>
Now, I can arrange my plots with Bootstrap. Cool !

Related

Rendering a v2 form from Preside formbuilder

I'm stuck in rendering a v2 form that I created using Preside formbuilder.
so far I have:
args.newsletter = formbuilderService.getForm("[id]");
args.rendered = formbuilderService.renderForm(
formId = args.newsletter.id,
layout = "default",
validationResult = "");
but all I get from args.rendered is:
<div class="formbuilder-form form form-horizontal"> <div class="alert alert-success"></div> </div>
But I want to render the whole form, like if I would add it by using a widget.
FormbuilderService.renderForm expects the configuration argument to contain data from the form builder widget in order to render the form correctly.
You can use the renderWidget helper to render the form
args.newsletter = formbuilderService.getForm( "[id]" );
args.rendered = renderWidget(
widgetId = "formbuilderForm"
, config = {
form = args.newsletter
, layout = "default"
, instanceid = ""
}
);

Download dataTable is printing HTML along with table

I have this sample app to display and download dataTable. But it is also printing HTML script on top of the downloaded attachment. It is printing logo and title HTML but I also want to preserve them on the app.
library(shiny)
library(DT)
ui <- fluidPage(
titlePanel(title = tags$div(img(src = "test.jpg", width = 170, height = 115, align = "left"))),
titlePanel(title = tags$div(class = "header" , tags$p("Cars", tags$br(), tags$h4("MTCARS", style = "text-align: center; color:navy;"), style = "text-align: center; color:navy;"))),
dataTableOutput("table_output")
)
server <- function(input, output, session){
output$table_output <- renderDataTable(server=FALSE,{
DT::datatable(head(mtcars), extensions = c('Buttons'),
options = list(autoWidth = FALSE, dom = 'lfrtipB',
buttons = list(list(extend = "csv", text = "CSV", filename = "cars",
exportOptions = list(modifier = list(page = "all"))),
list(extend = "excel", text = "EXCEL", filename = "cars",
exportOptions = list(modifier = list(page = "all"))),
list(extend = "pdf", text = "PDF", filename = "cars",
exportOptions = list(modifier = list(page = "all")))
))) })
}
shinyApp(ui, server)
I had to change the UI function to get the proper attachment.
ui <- fluidPage(
img(src = "test.jpg", width = 170, height = 115, align = "left"),
tags$div(class = "header" , tags$h2("Cars", tags$br(), tags$h4("MTCARS", style = "text-align: center; color:navy;"), style = "text-align: center; color:navy;")),
dataTableOutput("table_output")
)

Django heatmap d3.js passing returned data from search

am creating a searchable repository that displays heatmap after the search is completed in django (windows) and postgresql.
my code for the search is not used to HTML.
views.py
def search_result(request):
if request.method == "POST":
ChemSearched = request.POST.get('ChemSearched')
tarname = Bindll.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched)[:10]
return render(request, 'Search/search_result.html',
{'ChemSearched':ChemSearched,'tarname':tarname})
else:
return render(request, 'Search/search_result.html',{})
Searchresults.html
...
<br/><br/><br/><br/>
<strong><h1>{% if ChemSearched %}
<script>
var margin = {top: 30, right: 30, bottom: 30, left: 30},
width = 450 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
{% for Bindll in tarname %}
var myGroups = [ "{{ Bindll }}" ]
var myVars = [ "{{ Bindll.ki_nm }}" ]
{% endfor %}
var x = d3.scaleBand()
.range([ 0, width ])
.domain(myGroups)
.padding(0.01);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
var y = d3.scaleBand()
.range([ height, 0 ])
.domain(myVars)
.padding(0.01);
svg.append("g")
.call(d3.axisLeft(y));
var myColor = d3.scaleLinear()
.range(["white", "#69b3a2"])
.domain([1,100])
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/heatmap_data.csv", function(data) {
svg.selectAll()
.data(data, function(d) {return d.group+':'+d.variable;})
.enter()
.append("rect")
.attr("x", function(d) { return x(d.group) })
.attr("y", function(d) { return y(d.variable) })
.attr("width", x.bandwidth() )
.attr("height", y.bandwidth() )
.style("fill", function(d) { return myColor(d.value)} )
})
</script>
<br>
{% for Bindll in tarname %}
{{ Bindll }}--{{ Bindll.ki_nm }}-{{ Bindll.ic50_nm }} - {{ Bindll.kd_nm }} - {{ Bindll.ec50_nm }} - <br>
{% endfor %}
{% else %}
<strong>No Entry</strong>
{% endif %}
never used webs before so any help why the chart is only showing one element, tried using for loop to append the values in a list did not work
but its printing quite fine the results, any way you can guide me on what am doing wrong, to make the heatmap show my results.
Thanks
Can you build your scale domains this way instead, and see if it works. I don't see the immediate problem outside of a possible mistake in the domains:
var myGroups= data.map(d=>d.group).filter((item, i, ar) => ar.indexOf(item) === i),
myVars = data.map(d=>d.variable).filter((item, i, ar) => ar.indexOf(item) === i);

Could not parse some characters: video.viewers.all.count| ans video.viewers_by_ip.all.count||intcomma

How I can parse or sum two ManyToMany field in the template
<div class=""> <h6 class="card-text ml-2 p-2 bd-highlight" style="text-align: left; height: 1px; "><small class="text-muted ">{{ video.viewers.all.count + video.viewers_by_ip.all.count|intcomma }} views . </small></h6></div>
I tried to get this number by my view but I got this message
'list' object has no attribute 'viewers_by_ip'
my view
profile = get_object_or_404(Account, username=request.user)
if not profile.is_active:
return render(request, 'personal/violated.html')
users = [user for user in profile.following.all()]
video = []
for u in users:
p = Account.objects.get(username=u)
p_posts = p.video_set.all()
video.append(p_posts)
my_post = profile.account_video()
video.append(my_post)
if len(video):
video = sorted(chain(*video), reverse=True, key=lambda video: video.created_date)
video_viewers_ip = video.viewers_by_ip.all()
video_viewers = video.viewers.all()
video_views = len(list(chain(video_viewers_ip, video_viewers)))

How to update a specific value inside a dictionary using JQuery and Flask?

I've created a session list that contains my products, i need to update the quantity of any product by increasing it amount, for that am using an HTML type="number" , i also created a function which take the changed amount and multiplying it value with the current quantity, so lets say the amount of the first product by default is 2 by increasing the number lets say 2 the product amount will become 4 and so on, also the price will be multiplied .
Here are the codes:
<th style="text-align: center;" class="amount-izd">{{value["amount"]}}</th>
<th style="text-align: center; width: 14%;">
<div class="block">
<input type="number" id="myNumber" value="1" min=1 data-amount='{{value["amount"]}}' data-pros='{{value["id"]}}' data-price='
{% if g.currency == "euro" %}
{{format_price(value["price"] * config.SITE_CURRENCIES["euro"]).rsplit(".",1)[0]}}
{% elif g.currency == "dollar" %}
{{format_price(value["price"] * config.SITE_CURRENCIES["dollar"]).rsplit(".",1)[0]}}
{% else %}
{{format_price(value["price"] * config.SITE_CURRENCIES["ruble"]).rsplit(".",1)[0]}}
{% endif %}
'>
<label for="myNumber">qty</label>
</div>
</th>
JQuery codes:
$("input[type='number']").bind('keyup change click', function (e) {
if (! $(this).data("previousValue") ||
$(this).data("previousValue") != $(this).val()
)
{
var currentAmount = $(this).attr('data-amount');
var currentPrice = $(this).attr('data-price');
$(this).closest('tr').find('.amount-izd').text(parseInt(currentAmount) * $(this).val());
$(this).closest('tr').find('.price-izd').text(parseInt(currentPrice) * $(this).val());
$.ajax({
type: 'post',
url: '/standard-{{g.currency}}/profile/'+$(this).attr("data-pros")+'/update/price/' + parseInt(currentPrice) * $(this).val(),
cache: false
}).done(function(data){
if(data.error){
toastr.error(data.error)
}
});
$(this).data("previousValue", $(this).val());
} else {
}
});
And finally views.py :
#profile_route.route("/standard-<set_curr>/profile/cart/", methods=['GET','POST'])
#authorize
def cart_products():
if "cart" not in session:
return render_template("my-cart.html", display_cart = {}, total = 0)
else:
items = session["cart"]
dict_of_products = {}
total_price = 0
for item in items:
product = Goods.query.get(item)
total_price += product.price
if product.id in dict_of_products:
pass
else:
dict_of_products[product.id] = {"qty":1, "name":product.product_name, 'category':product.Category.name, "sizes": product.sizes, "hex_color":product.hex_color, "text_color":product.text_color, "material":product.material, "article":product.article, "price":product.price, "sort": product.sort, "amount": product.amount, 'slug':product.slug, 'public_id' : product.public_id, "id":product.id}
return render_template("my-cart.html", display_cart=dict_of_products, total = total_price)
#profile_route.route("/standard-<set_curr>/profile/<int:id>/update/price/<price>", methods=['GET','POST'])
#login_required
def update_price(id, price):
items = session["cart"]
dict_of_products = {}
for item in items:
product = Goods.query.get(item)
if product.id in dict_of_products:
dict_of_products[id]['price'] = price
return jsonify(success=dict_of_products[id]['price'])
return jsonify(error='No product found.')
If i changed the amount , in console i got a 500 error that says:
return jsonify(success=dict_of_products[id]['price'])
KeyError: 47
Please how to overcome this problem ?
Update:
I was wondering , is it possible to update any value of the dictionary by accessing it directly from JQuery ??