python dcc.Location opening new page within a page - python

I have several dash apps in a html files, example of html with app 'viewer':
{% extends 'base.html' %}
{% load static %}
{% block content %}
{% load plotly_dash %}
<h1>Viewer</h1>
<div class="{% plotly_class name='viewer' %} card" style="height: 100%; width: 100%">
{% plotly_app name='viewer' ratio=0.7 %}
</div>
<br>
{{ plot1 | safe }}
{% endblock %}
I am trying to open another html from a dash app using dcc.Location (a callback provides a href back to this after a button is clicked) but it loads the html within the current html so I end up with two of all the side menu's, search bars etc.. How do I get the app to load a whole new page? Even opening the link on a new tab would suffice.

So after doing some reading I have solved the problem but will answer here for anyone else that has a similar issue. It is a very simple solution, you just need to change plotly_app to plotly_direct in the html file above. You will then subsequently need to add (plotly_header} and {plotly_footer} above and below this repectively and remove ratio from the original plotly_app section.
https://django-plotly-dash.readthedocs.io/en/latest/template_tags.html

Related

Nested for loop with if statement in Jinja fails to work

enter image description hereenter code here`
<div class="container">
{% for bookmark_title in bookmarks_titles %}
<div class="container-head">
<h2>{{ bookmark_title.title }}</h2>
<span>{{bookmark_title.description}}</span>
</div>
{% for bookmark in bookmarks %}
{% if bookmark.tag == bookmark_title.title %}
<div class="container-body">
<img src="{{bookmark.favicon}}" alt="icon" /> {{ bookmark["title"]}}
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
When I run the HTML the first for loop works as expected however, the second nested for loop and if statement only runs after the parent for loop ends.
But I want to return the "Bookmark" saved under each Bookmark_title.title.
As you can see in the attached image for nested for loop works only after the parent for loop ends.
Any suggestion, please.
In the process of filtering all the bookmarks before passing them to the HTML page. Instead of appending the filtered data from the database.db I was replacing with the new results so only the bookmarks, I filtered using the last title tag in this case Entertainment only passed into the HTML page which caused the issue.
To fix it I filtered all the bookmarks from the database.db since the 'Bookmarks' sheet only has the bookmarks, so I don't need to filter by tag.)
# Previously
for tag in tags:
bookmarks = db.session.query(Bookmarks).filter_by(tag=tag)
Fix
bookmarks = db.session.query(Bookmarks).all()

How to add links dynamically in html files in django?

For my project, I'm searching for articles on google news based on keyword input by the user, I want to display these links obtained from the search on my results page.
this is my result.html
{% extends 'base.html' %}
{% block title %}Result{% endblock %}
{% block content %}
<h3>Reported Url</h3>
<div>Post Content: <br>{{content}}</div>
<h3>News articles related to your query:</h3>
<ul>
{% for key, value in articles.items %}
<li>{{value}}</li>
{% endfor %}
</ul>
<div>
Back to Home Page
</div>
{% endblock %}
But the links do not work and I get the page not found error, since these links are not contained in urls.py.
How can I link these urls correctly?
thank you
You cannot execute python code inside Django templates.
Check out this thread: Numeric for loop in Django templates
Fixed the problem I had to replace "./" in the article to the homepage of the site I was refering to.

Django. How to show some content on only single page without duplicating?

For starters, i'm new in Django.
I have a searchbar and i want to show it on only single page. I use {%block searchbar %} {%endblock%} on all pages where I don't want to see the search bar. But suddenly I thought: I'm duplicating the code, and this violates the principle of "DRY". So, how can I display some content on a single page without duplicating this {%block searchbar %} {%endblock%} stuff?
In advance, thanks for your help!
Use include tag to include the search bar on the pages that you want. See here for more from the docs.
Place the code for the search bar in an HTML file called "searchbar.html
and then include it in any pages that you want.
{% extends "header.html" %}
{% block bar %}
{% include "searchbar.html" %} <!-- Simply include this on pages that you want -->
{% endblock %}
this way you will not violate the DRY principle.

Processing Payments Via Paypal in Django-Oscar

I am trying to set up a basic e-commerce site using Django Oscar and am having difficulties. The majority of the problem has to do with the absence of examples of how to hook up meaningful (think Paypal, Stripe, Braintree) methods of payment and presence of obscure ones of which I have never heard before.
Either way, I am attempting to use django-oscar-paypal and follow its documentation. The Paypal Express part seems to work in that the button shows up and something akin to check out and processing happens.
However, if I choose to proceed with checkout in a regular way (with hopes of paying with a card), I am taken to the following page (the message in parentheses is mine)
Which is a product of the following template:
{% extends "checkout/checkout.html" %}
{% load i18n %}
{% block title %}
{% trans "Payment details" %} | {{ block.super }}
{% endblock %}
{% block checkout_nav %}
{% include 'checkout/nav.html' with step=3 %}
{% endblock %}
{% block checkout_title %}{% trans "Enter payment details" %}{% endblock %}
{% block order_contents %}{% endblock %}
{% block shipping_address %}{% endblock %}
{% block shipping_method %}{% endblock %}
{% block payment_method %}{% endblock %}
{% block payment_details %}
{% block payment_details_content %}
<p>{% trans "(*** Message from ./templates/tshirt-theme/ ***) This page needs implementing within your project. You may want to use one of Oscar's payment gateway libraries:" %}</p>
<ul>
<li>django-oscar-paypal</li>
<li>django-oscar-datacash</li>
<li>django-oscar-gocardless</li>
<li>django-oscar-paymentexpress</li>
<li>django-oscar-accounts</li>
</ul>
<a id="view_preview" href="{% url 'checkout:preview' %}" class="btn btn-primary btn-lg">{% trans "Continue" %}</a>
{% endblock payment_details_content %}
{% endblock payment_details %}
When I click "Continue", I am taken to something resembling a pre-order page on which the Payment Method is empty. When I click "Change" on it, it takes me back to the page on the screenshot.
My question is how do I get credit cards to work with this setup? Is there a better way of doing this thing altogether? I am somewhat familiar with Django, but this seemingly simple task seems to require a lot of knowledge and/or a lot of re-inventing the wheel. The latter must be the case because there is no documentation or tutorials on any of this, but many sites allegedly use Django-Oscar.
Any help or advice is appreciated.
From the django-paypal repo view the sandbox code, in particular the templates folder, settings.py and urls.py. I followed the instructions and added the necessary paypal keys to settings.py as well as the urls.py but failed to copy the templates, since that was documented less carefully.
For me simply adding at the very least the same templates as the sandbox made the screen you are viewing be replaced with working paypal buttons. In particular, the sandbox/templates/checkout/payment_details.html seems to be what gets rendered in place of this reminder message you are seeing — note that the template has both Express and Flow options, so use only what your site is set to use.
Add the below code to oscar/checkout/preview.html, and also change the client ID #
<body>
<div class="col-sm-5 col-sm-offset-7">
<!-- Set up a container element for the button -->
<div id="paypal-button-container" ></div>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id={{'Askdlsfhslfkdlfkdsflskd-wkJzFrkfldfkjhdlkfrW3-5U-RW0-ZsZskflsfu_YT-85r'}}&currency=PLN&locale=pl_PL"></script>
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
style: {
layout: 'horizontal',
size: 'small',
color: 'blue',
shape: 'rect',
label: 'pay',
height: 44,
tagline: 'true'
},
enableStandardCardFields: false,
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: JSON.parse({{ order_total.incl_tax }}) // pass variable with amount to script
// <!-- value: '0.01', -->
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
}
}).render('#paypal-button-container');
</script>
</div>
</body>

webapp2, Jinja2: how to cut large html file into multiple html files

When I blog, I like to separate each blog-post into its own .html file (is that ok?)
This prevents the file getting too big, and makes it easy to go back and edit a previously written blog post if need be.
Occasionally the blog post will contain css/js/ajax/template variables.
But on my website, I like all the blog posts on one page (so I can scroll through them all, instead of going to a separate page for each post)
Here is an html file that contains two blog posts:
{% extends "base.html" %}
{% block blog_posts %}
<!-- links/targest for the side menu to jump to a post -->
<li>Post2 - April 2012</li>
<li>Post1 - Feb 2012</li>
{% endblock %}
{% block content %}
<div id="post1">
spam1 blah blah
</div>
<div id="post2">
spam2
</div>
{% endblock %}
and in base.html I have something like:
<div id="content-container">
<div id="section-navigation">
<ul>
{% block blog_posts %}
{% endblock %}
</ul>
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</div>
What is the best way for me to split these blog posts out into separate files using webapp2 and jinja2?
e.g. blog1.html might look like:
{% block blog_posts %}
<!-- links/targest for the side menu to jump to a post -->
<li>Post1 - Feb 2012</li>
{% endblock %}
{% block content %}
<div id="post1">
spam1 blah blah
</div>
{% endblock %}
(And I would want the links and the blogposts to be displayed in the right order on the website)
I could think of a way of doing it where post2 extends post1.html, post3 extends post2.html etc, but I would prefer to fan out more
"Henry and Kafura introduced Software Structure Metrics Based on Information Flow in 1981[2] which measures complexity as a function of fan in and fan out."
Thanks
#robert king, your design has data embedded directly in the template. Templates should only contain the blueprint to a view, and they should be rendered with new data generated from your main code every time. I simulate this process here (Edited to illustrate the use of a loop to extract post titles, and the display of a single post.):
import jinja2
# NOTE: in this template there is no data relating to specific posts.
# There are only references to data structures passed in from your main code
page_template = jinja2.Template('''
<!-- this is a navigation block that should probably be in base.html -->
{% block blog_posts %}
<!-- links/targets for the side menu to jump to a post -->
{% for post in posts %}
<li><a href="{{ post.url }}">{{ post.title }}
- {{ post.date }}</a></li>
{% endfor %}
{% endblock %}
<!-- this is a content block that should probably be in page.html -->
{% block content %}
<div id="post">
<h1>{{ current.title }}</h1>
<h2>{{ current.date }}</h2>
<p>{{ current.content }}</p>
</div>
{% endblock %}
''')
# NOTE your main code would create a data structure such as this
# list of dictionaries ready to pass in to your template
list_of_posts = [
{ 'url' : '#post1',
'title' : 'My first post',
'date' : 'Feb 2012',
'content' : 'My first post is about Hello World.'},
{ 'url' : '#post2',
'title' : 'My second post',
'date' : 'Apr 2012',
'content' : 'My second post is about Foo Bar.'}
]
# Pass in a full list of posts and a variable containing the last
# post in the list, assumed to be the most recent.
print page_template.render(posts = list_of_posts,
current = list_of_posts[-1])
Hope this helps.
EDIT See also my answer to a question on "Site fragments - composite views"
I just found another option in the jinja2 tutorial. I think it makes more sense for my handler to pass my template a list of filenames of blog posts, and then to include the blog posts.
include - returns the rendered contents of that file into the current namespace:
{% include 'header.html' %}
<div ...
{% include 'footer.html' %}
Included templates have access to the variables of the active context by default. For more details about context behavior of imports and includes see Import Context Behavior.
From Jinja 2.2 onwards you can mark an include with ignore missing in which case Jinja will ignore the statement if the template to be ignored does not exist. When combined with with or without context it has to be placed before the context visibility statement. Here some valid examples:
{% include "sidebar.html" ignore missing %}
{% include "sidebar.html" ignore missing with context %}
{% include "sidebar.html" ignore missing without context %}
New in version 2.2.
You can also provide a list of templates that are checked for existence before inclusion. The first template that exists will be included. If ignore missing is given, it will fall back to rendering nothing if none of the templates exist, otherwise it will raise an exception. Example:
{% include ['page_detailed.html', 'page.html'] %}
{% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
When I read the raw html file (file.read()) and passed the data to my template, it escaped all the html.
instead of {{data}} i had to use {{data|safe}} which allowed raw html.
something like:
class HomeHandler(BaseHandler):
def get(self):
file_names = sorted(os.listdir('blog_posts'))
html = [open('blog_posts/%s' % fn).read() for fn in file_names]
templates = {'html': enumerate(html)}
self.render_template('home.html', **templates)
{% block content %}
{% for num,data in html %}
<div id="post{{num}}">
{{data|safe}}
</div>
<br />
<img src="http://www.sadmuffin.net/screamcute/graphics/graphics-page-divider/page-divider-007.gif" border=0>
<br />
{% endfor %}
{% endblock %}
(make sure the directory isn't a static directory)

Categories

Resources