how to use dash_html_components.Script command - plotly-dash

i would like to convert the code below into dash-plotly code.
may i know how to translate the second script tag in the HTML code into dash-plotly?
.summary:hover+.detail,
.detail:hover {
display: block;
}
.show.detail {
display: block;
}
.detail {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<a class="summary" href="javascript:void(0);">Sample1</a>
<div class="detail">Detail of this summary</div>
</div>
<div class="wrapper">
<a class="summary" href="javascript:void(0);">Sample2</a>
<div class="detail">Detail of this summary</div>
</div>
<div class="wrapper">
<a class="summary" href="javascript:void(0);">Sample3</a>
<div class="detail">Detail of this summary</div>
</div>
<script>
$(".summary").on("click", function() {
$(this).next().toggleClass("show");
})
</script>

You can build up the same html structure within plotly.
The following code is an working example.
Requirement: Your CSS code must be stored in static/stylesheet.css
Example:
import dash
import dash_core_components as dcc
import dash_html_components as html
from flask import send_from_directory
import os
app = dash.Dash(__name__)
server = app.server
# Configure Samples
sample1 = html.Div([
dcc.Link('Sample1', href='javascript:void(0);', className='summary'),
html.Div('Details of this summary', className='detail')
], className='wrapper')
sample2 = html.Div([
dcc.Link('Sample2', href='javascript:void(0);', className='summary'),
html.Div('Details of this summary', className='detail')
], className='wrapper')
sample3 = html.Div([
dcc.Link('Sample3', href='javascript:void(0);', className='summary'),
html.Div('Details of this summary', className='detail')
], className='wrapper')
# Define layout
app.layout = html.Div([
sample1,
sample2,
sample3
])
app.scripts.append_script({"external_url": [
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
]})
# Add css file (locally hosted)
app.css.append_css({"external_url": [
"static/stylesheet.css"
]})
# Serving local static files
#app.server.route('/static/<path:path>')
def static_file(path):
static_folder = os.path.join(os.getcwd(), 'static')
return send_from_directory(static_folder, path)
if __name__ == '__main__':
app.run_server(debug=True)

try to add a custom-file.js in your assets forlder :
https://dash.plotly.com/external-resources
The example with the "altert" works for me, and the script appears in html / body / footer / script when I inspect the page of my app.

Related

Dynamic URL routing is not working in django web application

A am working on a simple application, where trying to generate Dynamic URl and routing take place as per the ID in the url.
Dynamic value is getting populated in the URL, but it not performing action that needed.
prop_listings.html HTML Page:-
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i> {{ listing.list_date | timesince }}
</div>
</div>
<hr>
More Info
</div>
</div>
</div>
URL.py in App Listings:-
from django.urls import path
from . import views
urlpatterns = [
path('',views.PropListings,name="prop_listings"),
path('<int:listing_id>', views.mlisting, name="morelisting"),
]
Views.py :-
def mlisting(request, listing_id):
# listingDetl = get_object_or_404(Listing, pk=listing_id)
listingDetl = Listing.objects.get(pk=listing_id)
print(listingDetl.username, listingDetl.address,listingDetl.city)
context = {
'listingDetails': listingDetl
}
return render(request,'listings/detail_listing.html', context)
URL.py in MainProject:-
urlpatterns = [
path('', include('static_pages.urls')),
path('user_account/', include('user_account.urls')),
path('listings/', include('listings.urls')),
path('feedback/', include('feedback.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Am trying to redirect the page from prop_listings.html to detail_listing.html, based on the below tag URL generated on listing.id
More Info
It's not working as expected on-click of above tag.
But when i did inspect on the same, URL is getting generated properly and when i click on the url, it will work as expected.
Inspect on the html page, URL populated
I looked into similar issue threads and tried to make changes, but not able to fix it.
Not getting what the issue and how to correct it.

Image won't load in Flask App static folder

I am trying to add an image to the header of my app and it will not load. I have the image stored in the static folder which is at the same level as the app.py file. The code that should display the image is:
<header class="d-flex flex-wrap justify-content-center py-3 mb-4 border-bottom">
<img src="{{url_for('static', filename='marco_icon.png')}}" />
<ul class="nav nav-pills">
<li class="nav-item">Home</li>
</ul>
</header>
when I open the app it appears as an error icon:
When I inspect the element it shows:
app.py code is as follows:
from myproject import app
from flask import render_template
#app.route('/')
def index():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
init.py is as follows:
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app,db)
from myproject.trips.views import trips_blueprint
app.register_blueprint(trips_blueprint,url_prefix='/trips')
Directory structure:
Any thoughts on what I am doing wrong would be appreciated!

Django Render HTML to PDF

I'm trying to render an html file to pdf however while the pdf functionality is working fine the rendering is working properly, no css. Also it renders the whole page, how can i render specific sections of the html page. I'm using xhtml2pdf.
views.py file
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
data = {
"company": "Name",
}
#Opens up page as PDF
class ViewPDF(View):
def get(self, request, *args, **kwargs):
pdf = render_to_pdf('listings/listing.html', data)
return HttpResponse(pdf, content_type='application/pdf')
urls.py file
path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"),
html file
<section class="p0">
<div class="container">
<div class="row listing_single_row">
<div class="col-sm-6 col-lg-7 col-xl-8">
<div class="single_property_title">
<span class="flaticon-photo-camera"></span> View Photos
</div>
</div>
<div class="col-sm-6 col-lg-5 col-xl-4">
<div class="single_property_social_share">
<div class="spss style2 mt10 text-right tal-400">
<ul class="mb0">
<li class="list-inline-item"><span class="flaticon-transfer-1"></span></li>
<li class="list-inline-item"><span class="flaticon-heart"></span></li>
<li class="list-inline-item"><span class="flaticon-share"></span></li>
<li class="list-inline-item"><span class="flaticon-printer"></span></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
Thank you!
Ans 1.) If you want to style your html than directly use style property in tag. If you make class and use template inheritance than it is not going to work as it is independent html. Use style directly in html.
Ans 2.) if you want specific section of html in pdf than write content which you need in html or use style = “display: none ;” on section which you dont want in pdf.

Django iframe gview from fileSystem/Storage not loading

Im trying to load with gview a PDF file from the filesystem
The file its storage and when I call "{{documento.adjunto.url}}" it doesnt shows me 404 error, but still the PDF its not show.
Trying using one from web, it works.
<iframe src="http://docs.google.com/gview?url=https://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf&embedded=true" style="width:600px; height:450px;" frameborder="0"></iframe>
HTML
<div class="container">
<div class="row">
<div class="col-lg-12">
<iframe src="http://docs.google.com/gview?url={{documento.adjunto.url}}&embedded=true" style="width:600px; height:450px;" frameborder="0"></iframe>
</div>>
</div>
</div>
Viws.py
#login_required
def CurriculumDetailView(request, pk):
documento = Curriculum.objects.get(pk=pk)
return render(
request,
"INTRANET/curriculum_detail.html",
context = { 'documento':documento,
},
)
Model
class Curriculum(models.Model):
rut_candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE)
adjunto = models.FileField(upload_to=UPLOAD_CVS)
fecha_ingreso_cv = models.DateField(_("Date"), auto_now_add=True)
URL.py
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

how to use webbrowser to open the link when it is clicked in wxPython frame

I am writing a small app using wxPython. I have already save my data into a HTML string. I use the wx.html2.webview to display my HTMl.
And here is my code being simplified:
class MyBrowser(wx.Dialog):
def __init__(self, *args, **kwds):
wx.Dialog.__init__(self, *args, **kwds)
sizer = wx.BoxSizer(wx.VERTICAL)
self.browser = wx.html2.WebView.New(self)
sizer.Add(self.browser, 1, wx.EXPAND, 10)
self.SetSizer(sizer)
self.SetSize((800, 700))
if __name__ == '__main__':
app = wx.App()
dialog = MyBrowser(None, -1)
dialog.browser.SetPage(HTMLstring,"")
dialog.Show()
app.MainLoop()
there are images and links in my HTML string. I have successfully display my HTML string. But my question is :I hope the default webbrowser can open the links when I click on it.
So what should I do. Could someone please provide a link to such an example or (better still), post a short snippet here that shows how to do it?
By the way, I used the wx.HTMLwindow before I found it could not display my HTML string in the right way.
Here is my HTMLstring being simplified:
<html>
<head>
<style type="text/css">
div#container{background-color:#F0F8FF;width:700px}
div#content {height:200px;width:400px;float:left;word-break: break-all;}
div#predict{width:700px;}
.box {height:200px;width:300px;overflow:hidden;background-repeat: no-repeat;background-position:center center;float:left;}
img{margin-top: -50px;}
a:link{ text-decoration:none;}
</style>
</head>
<body>
<br>
<hr />
<p>SCCA Predicted:</p>
<div>
Eye discharge 1.0, Sensation of foreign body 0.99901248481,
</div>
</body></html>
There isn't a good way to do this. You can use webview's EVT_WEBVIEW_NAVIGATING event. However as the documentation notes, if there are multiple frames on the web page, then this event will get fired multiple times. If you want to go that route and try it out, then I would recommend using Python's webbrowser module to open your default browser.
Here's a quick demo:
import webbrowser
import wx
import wx.html2
class MyBrowser(wx.Dialog):
def __init__(self, *args, **kwds):
wx.Dialog.__init__(self, *args, **kwds)
sizer = wx.BoxSizer(wx.VERTICAL)
self.browser = wx.html2.WebView.New(self)
self.browser.Bind(wx.html2.EVT_WEBVIEW_NAVIGATING, self.onNav)
self.browser.Bind(wx.html2.EVT_WEBVIEW_NEWWINDOW, self.onNewWindow)
sizer.Add(self.browser, 1, wx.EXPAND, 10)
self.SetSizer(sizer)
self.SetSize((700, 700))
def onNav(self, event):
print "onNav called"
url = event.GetURL()
print url
webbrowser.open(url)
def onNewWindow(self, event):
print "onNewWindow called"
url = event.GetURL()
print url
webbrowser.open(url)
if __name__ == '__main__':
html = """<html>
<head>
<style type="text/css">
div#container{background-color:#F0F8FF;width:700px}
div#content {height:200px;width:400px;float:left;word-break: break-all;}
div#predict{width:700px;}
.box {height:200px;width:300px;overflow:hidden;background-repeat: no-repeat;background-position:center center;float:left;}
img{margin-top: -50px;}
a:link{ text-decoration:none;}
</style>
</head>
<body>
<br>
<hr />
<p>SCCA Predicted:</p>
<div>
<a href="http://sideeffects.embl.de/se/C0423006" >Eye discharge 1.0, </a><a href="http://sideeffects.embl.de/se/C0423602" >Sensation of foreign body 0.99901248481, </a>
</div>
</body></html>
"""
app = wx.App()
dialog = MyBrowser(None, -1)
dialog.browser.SetPage(html, '')
dialog.Show()
app.MainLoop()
I use the desktop module for that, edited using Mike's example but using desktop module instead of webbrowser.
import wx
import wx.html2
import desktop
html = """
<html>
<head>
<style type="text/css">
div#container{background-color:#F0F8FF;width:700px}
div#content {height:200px;width:400px;float:left;word-break: break-all;}
div#predict{width:700px;}
.box {height:200px;width:300px;overflow:hidden;background-repeat: no-repeat;background-position:center center;float:left;}
img{margin-top: -50px;}
a:link{ text-decoration:none;}
</style>
</head>
<body>
<br>
<hr />
<p>SCCA Predicted:</p>
<div>
<a href="http://sideeffects.embl.de/se/C0423006" >Eye discharge 1.0, </a><a href="http://sideeffects.embl.de/se/C0423602" >Sensation of foreign body 0.99901248481, </a>
</div>
</body></html>
"""
class MyBrowser(wx.Dialog):
def __init__(self, *args, **kwds):
wx.Dialog.__init__(self, *args, **kwds)
sizer = wx.BoxSizer(wx.VERTICAL)
self.browser = wx.html2.WebView.New(self)
self.browser.Bind(wx.html2.EVT_WEBVIEW_NAVIGATING, self.onNav)
sizer.Add(self.browser, 1, wx.EXPAND, 10)
self.SetSizer(sizer)
self.SetSize((700, 700))
def onNav(self, event):
print "onNav called"
url = event.GetURL()
print url
self.openExternal(url)
def openExternal(self, url, doclear=False):
"""
Open an external file with desktop module.
:param `url`: the file url to open in external program
:param `doclear`: clear InfoBar message
"""
wx.BeginBusyCursor()
try:
desktop.open(url.strip())
except OSError:
text = (_(u'Your default browser could not be opened, \
or the external program was not found or no \
external program is defined for this file.'))
wx.EndBusyCursor()
if __name__ == '__main__':
app = wx.App()
with MyBrowser(None, -1) as dlg:
dlg.browser.SetPage(html, '')
dlg.ShowModal()
app.MainLoop()
I also use 'with' to create the dialog, this ensures that it is getting destroyed when one with done with it.
https://pypi.python.org/pypi/desktop
If you need it on Py3 I made some changes which you can get here:
https://bitbucket.org/wbruhin/desktop