External URL into a iframe to embed an external url within Django - django

I would like to embed a pptx that is uploaded into a folder in OneDrive within a iframe tag in a Django template. I have the urls stored in a model and saved into the SQLite database. In this sense, in the views.py file, I have the following code:
context = {
'selectedunit': selectedunit,
'url_to_be_inserted': MyModel.objects.filter(unit=selectedunit)
}
return render(request, 'web.html', context)
The code for web.html is very easy:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container col-lg-8">
<div class="center">
<iframe class="center" src={{ url_to_be_inserted.url }} width="100%" height="300%" frameborder="0"/>
</div>
</div>
{% endblock %}
The result is the snapshot below:
While, I would like to embed the ppt into the web site. If I directly insert the URL, instead of using the context variable, it works. That is to say:
<iframe class="center" src="https://..." width="100%" height="300%" frameborder="0"/>
In this case, the result is as follows (ppt embedded into the Web site):
The reason why doing in this sense is because, depending on the selectedunit variable, I would like to address a different pptx with a different URL and I would like to dynamically change the pointer (as you see above by filtering the model).
How could I solve it?
Many thanks in advance

Related

Single page design - loading new content on link click

I'm working on a django webpage using single page design approach. Generally what I'm trying to achieve is to have some new content being loaded (picture gallery) to my main webpage after clicking certain links.
What I have already achieved is that the new content is being loaded on a link click but unfortunately it seems like the whole page is being reloaded and not rendered correctly. My current implementation is based on having main index.html template and extension template, both using {% block content %} relation.
views.py
def index(request):
categories = Category.objects.all().order_by('name')
return render(request, 'index.html', {'categories': categories})
def gallery(request, id):
category = Category.objects.get(id=id)
return render(request, 'gallery.html', {'category': category})
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('view_gallery/<int:id>/', views.gallery, name='view_gallery')
]
index.html
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
{% for category in categories%}
<li class="nav-item">
<a class="nav-link" href="{% url 'view_gallery' category.id %}">{{ category.name }}</a>
</li>
{% endfor %}
</ul>
</div>
<div>
{% block content %}
{% endblock %}
</div>
gallery.html
{% extends 'index.html' %}
{% block content %}
<p>{{ category.name }}</p>
{% endblock %}
I hope I have explained clearly what I'm trying to achieve. Could you please point me in the right direction?
Requests and page changes in single page sites work quite differently than those for normal web pages. Single page sites use JavaScript to change the page content rather than requesting a new page from the server. Single page sites can request content from the server, but generally that content is just data while the structure (HTML) of the page is decided by the client in JavaScript. The only time a full HTML page is sent by the server is on the initial request, which should be responded to with index.html.
In your example, you could have this work by adding a script that requests content from the server and modifies the DOM when a link is clicked.
For example:
const a1 = document.querySelector("a.link1");
const a2 = document.querySelector("a.link2");
a1.addEventListener("click", () => {
setContent("<p>Content from link 1</p>")
});
a2.addEventListener("click", () => {
setContent("<p>Content from link 2</p>")
});
function setContent(content) {
const contentDiv = document.querySelector("div.content");
contentDiv.innerHTML = content;
}
a {
text-decoration: underline;
color: blue;
}
a:hover {
cursor: pointer;
}
<h1>My Page</h1>
<a class="link1">link 1</a>
<a class="link2">link 2</a>
<div class="content">
</div>
And the click event callbacks could request content from your server instead of having the content hard-coded as in this example. Note that then the server should respond with just a snippet of HTML rather than an entire new page.
For example, you could use the following function to get content for the div.content element:
function fetchData() {
const response = fetch("/gallery");
return response;
}
If you're new to single page sites, you might checkout a framework like React, Vue, or Angular to get started and gain a better understanding or even use for this project.

Template Django application extending template django project

I am quite a beginner in django and I need some advices.
I am trying as much as possible to create reusable django applications that will be used in several different projects. But I don't know how to proceed with templates.
If I have an application managing user, I think the template allowing to add, remove or list a user shall be located in the application and not in the project. Templates project should define headers, footers and general organisation (correct me if I'm wrong).
However, if I want to use template inheritance I will extend project template in my application template :
{% extends "base.html" %}
{% block content %}
...
{% endblock %}
So in developping my reusable application I make the assumption that my project will have a template called base.html with a block content, and in my mind this information should not be located at application level, but in project level. In some projects I will want to display users in block content, but not necessarily in others. I could want to display user information in several places in the same page for example...
How do you developp your application template to bypass this limitation ?
Thanks in advance,
Bill
What you are describing is probably best solved with custom template tags, specifically inclusion tags.
I would do a basic html template containing a header and a footer, and many reusable templates extending the basic one, containing the different layouts I would need. I would also create reusable components (tiles, datagrids...).
For the templates :
base.html
<!doctype HTML>
<html>
<head>
....
</head>
<body>
{% block content %}
</body>
</html>
3_columns.html
{% extends "project/base.html" %}
{% block content %}
<div class="line">
<div class="column">{% block col1 %}</div>
<div class="column">{% block col2 %}</div>
<div class="column">{% block col3 %}</div>
</div>
{% endblock %}
2_lines.html
{% extends "project/base.html" %}
{% block content %}
<div class="line">{% block line1 %}</div>
<div class="line">{% block line2 %}</div>
{% endblock %}
A basic custom component :
templatetags/custom.py
import django
from django.template.defaulttags import register
#register.inclusion_tag('components/custom.html')
def custom(params):
context = {
'a': params['a'],
'b': params['b']
}
return context
templates/components/custom.html
<div class="custom">
<label>{{ a }}
<input name={{ b }}
</label>
</div>
django-admin.py collectstatic
Read docs
Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.

Django not displaying images from blog Post

I have created a DJANGO blog-engine which takes my post and the template parses it for html tags. links etc.. are working but it does not load image file and instead shows the 'alternative' . I have tried the tag in separate html files and it is otherwise. Just not displaying image from inside a django blog post.
Relevant portions of the template file :
{% include 'blog/header.html' %}
</aside>
<section id ="content">
<article>
{%for post in posts %}
<h2>{{ post.title }}</h2>
<h3>{{ post.created}}</h3>
<p>
{{ post.body|safe }}<br>
</p>
<h3>By {{ post.author }}</h3>
I am copy-pasting the post in question
<---- text here ------------------>
GDCM::Directory
<img src="/home/usman/www/deejay/blog/static/images/dicomdir.png" />
This is it
Interestingly, the 'a' tag works fine but the 'img' tag is not working. I have tried many variations but i want some inline code to display simple html tag, alternatively of course i will resort to it programmatically by passing some variable to the template from inside the post to let it know where to position the image.
Your problem is here: {{ post_get_absolute_url }}. You should use {{ post.get_absolute_url }}.
The better way is to call the URL of the image directly; that way you maintain your URLs in urls.py and not in your model code. It makes your app more portable.
Take your image field name value from your model, and then {{ post.image.url }}. For example, if your model is:
class Post(models.Model):
img = models.ImageField(upload_to='images')
Then you would use {{ post.img.url }}
Problem solved when I replaced the full address with
<img src="/static/images/dicomdir.png"/>
On development server as well as on production. What helped was that I looked at the Dev-server responses on my terminal and was able to figure out the url.

Can't Embed YouTube Link Within Django Template Tag, Twitter Bootstrap

I'm currently attempting to embed a user-submitted YouTube link via a Django form within a Twitter Bootstrap layout.
The space for the video is appearing and the source code reflects the correct information and link, but neither the video nor the player appears. I'm also using the "flex-video" class from this link for a responsive layout http://poslavsky.com/blog/2012/04/01/responsive-video-in-twitter-bootstrap/ but it doesn't work when that class is changed to another name such as "video" either.
This is the code:
<div class="row">
<div class="span12">
<span>{{story.author}}</span><br>
<span>{{story.zip_code}}</span><br>
<span>{{story.date}}</span><br>
<p>{{story.copy}}</p>
<div class="image">
{% if story.pic %}
<img src="{{ story.pic.url }}" alt="some_image_alt_text" />
{% endif %}
</div>
<div class="flex-video">
{% if story.video %}
<p> <iframe width="460" height="250" src="{{ story.video}}" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</p>
{% endif %}
</div>
</div>
Any insight greatly appreciated.
I guess {{story.video}} gives Youtube video Url something similar to this http://youtube.com/watch?v=ASO_ypdnsQ which is direct youtube url, and not embed url.
Embed URL for same video is different than direct url, like this http://youtube.com/embed/....
I created a custom template tag, here is how.
import urlparse
...
#register.inclusion_tag('video_embed.html', takes_context=True)
def youtube_embed(context, url):
url_data = urlparse.urlparse(url)
query = urlparse.parse_qs(url_data.query)
video_id = query["v"][0]
context['embed_url'] = ('http://youtube.com/embed/%s' % video_id)
return context
Then, in templates just load the tag, and pass the youtube url. It will give embed url from normal url.

build website for mobile and pc with django

I am trying to develop a website for mobile and pc browser with django.
and I am trying to figure out a best structure of the views and templates.
there is what I have tried:
1) use different url ( like http://example.com/mobile/ and http://example.com/ OR
http://example.com/?c=mobile ) to distinguish mobile and pc, and map them to different view which set different templates.
2) in the view set different template according to USER_CLIENT
3) use a wrapper layer of the view, the actual view just return the data to the wrapper, the wrapper set the different template.
Is there a common way to handle this in django? any suggestions and comments?
Use Django's "sites" framework for a mobile version at http://m.example.com.
I would recommended solution 3; using a decorator to inspect the clients User Agent and returning à different template in case of a mobile agent.
Have the decorator take two arguments: the normal template, and the mobile template.
From your view, return a dict The decorator may pass to the rendering function as context. There is a decorator called 'render_to' that does this very well, Google for it.
To deal with the use case where users want the full version, even when browsing from a mobile device, you may use a redirecting view that sets a cookie your decorator may check for.
best practice: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so.
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view_on_mobile_and_desktop(request)
.....
render_to_response('regular_template.html',
{'my vars to template':vars},
context_instance=RequestContext(request))
then in your template you are able to introduce stuff like:
<html>
<head>
{% block head %}
<title>blah</title>
{% if request.mobile %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
{% else %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
{% endif %}
</head>
<body>
<div id="navigation">
{% include "_navigation.html" %}
</div>
{% if not request.mobile %}
<div id="sidebar">
<p> sidebar content not fit for mobile </p>
</div>
{% endif %>
<div id="content">
<article>
{% if not request.mobile %}
<aside>
<p> aside content </p>
</aside>
{% endif %}
<p> article content </p>
</aricle>
</div>
</body>
</html>