Display .html file in iFrame uploaded as media file using Django - python

I'm looking to display an uploaded .html file in an iFrame on my template. I would rather NOT set it up as a url to visit in the urls.py file, I upload .html files from the admin panel to the media folder like so:
model
# Portfolio project overview model
class Work(models.Model):
html = models.FileField(upload_to="work_app/media/htmls/", null=True, blank=True)
settings.py
MEDIA_ROOT = str(BASE_DIR) + "/media/"
MEDIA_URL = '/media/'
STATIC_ROOT = str(BASE_DIR) + "/static/"
STATIC_URL = '/static/'
urls.py
urlpatterns = [
include("personal_portfolio_project.apps.resume_app.urls")),
path("work/", include("personal_portfolio_project.apps.work_app.urls")),
]
if DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My first attempt to display it using this template.html code:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>{{ work.title }}</h1>
<div class="row">
<div class="col-md-8">
{% if work.html %}
<iframe height="100%" width="100%" src="{{ 'work.html.url' }}">
</iframe>
{% endif %}
</div>
</div>
{% endblock %}
...looks like this:
As you can see, the iFrame is displaying, but seems like it can't find the .html file (404).
I saw in a few other posts that the html line should be:
<iframe height="100%" width="100%" src="{% url 'work.html' %}"> </iframe>
..and to also add X_FRAME_OPTIONS = 'SAMEORIGIN' to your settings.py file, so I did both those, where I now get:
What is this trying to tell me? What am I missing?
UPDATE
I have also tried:
<iframe height="100%" width="100%" src="{{ work.html }}"> </iframe>
to which I get another 404:
UPDATE
The closest I've gotten is using this:
<iframe type="html" height="100%" width="100%" src="{{ work.html.url }}"> </iframe>
But it gives me this screen:
I put the url above the image to make sure that it is in fact correct. According to other answers, they said just to enable X_FRAME_OPTIONS = 'SAMEORIGIN' and it'll work, but it doesn't for me. Any help from here would be greatly appreciated. Thanks!

I take back my last UPDATE above, what I had to do was clear my cache, or run the page in incognito mode as none of my changes were being reflected on the page due to the cache. Once I did that, it started showing the iframe properly.
Another option I was exploring was to set an xframe exemption decorator to the view that handles rendering the post details page, which would look something like:
from django.shortcuts import render
from django.views.decorators.clickjacking import xframe_options_exempt
# Create your views here.
from .models import Work
#xframe_options_exempt
def work_detail(request, pk):
work = Work.objects.get(pk=pk)
context = {
'work': work
}
return render(request, 'work_detail.html', context)
which also seemed to work, but I'm reverting back to the SAMEORIGIN method.

Related

How to call urls.py fetching a value from a loop in Django

On my index page, I have an image gallery. When someone clicks on an image, it should show more information with more photos in another page. All are loading from MySQL database using a for loop. I'm unable to get the detail of clicked image from my data base. It loads all the data
This page's process is like a news website -- all the news loading from a loop. if someone clicks on a news item it should only show details about the clicked item.
Below is my index.html page, my urls.py and views.py source code also.
I'm using Python, Django with MySQL; all latest versions.
Home page, source code of my images gallery
{% for x in destination %}
<!-- Destination -->
<a href="destination" id="{{x.id}}"><div class="destination item" >
<div class="destination_image">
<img src="{{x.img.url}}" alt="">
{% if x.offer %}
<div class="spec_offer text-center"><a >Special Offer</a></div>
{% endif %}
</div>
<div class="destination_content">
<div class="destination_title">{{x.name}}</div>
<div class="destination_subtitle"><p>{{x.short_description}}</p></div>
<div class="destination_price">From ${{x.price}}</div>
</div>
</div></a>
{% endfor %}
from . import views
from django.urls import path
urlpatterns = [
path('destination', views.destination, name='destination'),
path('', views.index, name='index')
]
from django.shortcuts import render
from .models import Destination
def destination(request):
dest = Destination
return render(request, 'destination.html', {'sub_destination': dest})
You can use Reverse resolution of URLs. just add another url pattern in your urls.py:
urlpatterns = [
path('destination/<int:dest>/', views.destination_content, name='destination_content'),
# ...
]
and use it inside your for loop in template like this:
<div class="destination_content">
<div class="destination_title">{{x.name}}</div>
...
</div>
NOTE: you must define destination_content function in your views.py

How to access the image in django template? [duplicate]

I'm new in Django. I read a lot on documentation and on this site about my question. But I really can not understand what I should do to make this. Can someone show me with all steps please?
model.py:
class Post(models.Model):
title=models.CharField(max_lengt=50)
img=models.ImageField(upload_to = 'images')
template:
{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{post.img}}">
{% endfor %}
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
If I access the admin page, how can I upload the image? In template I can't see image!
Sorry for my bad English. Help me please
In template, use:
{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{ post.img.url }}">
{% endfor %}
You have to add {{ post.img.url }}.
Also, make sure that in urls.py, you have:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It will Work.

"Could not load the image" from Django's media folder

I'm trying to display an image from a database (SQLite, Django2.7). These images are stored in root/media/pictures.
models.py
class News(models.Model):
news_id = models.AutoField(primary_key=True, editable=False)
news_img = models.FileField(upload_to="pictures/",validators=[FileExtensionValidator(allowed_extensions=['svg'])] )
urls.py
urlpatterns = [...]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I've try to insert the path in the var in the following methods:
template.html
{% for news_f in news_f%}
<div>
<img src="{{ media }}{{news_f.news_img}}">
</div>
{% endblock %}
and
{% for news_f in news_f%}
<div>
<img src="{{news_f.news_img.url}}">
</div>
{% endblock %}
When I inspect the element in the browser, I get the correct path to the file.
<img src="/media/pictures/file.svg">
But it isn't displayed in the HTML:
Could not load the image
That happens because django doesn't serve static files. Usually you use django along with some webserver like nginx and those servers are more reliable serving files.
Please check out django docs https://docs.djangoproject.com/en/2.2/howto/static-files/deployment/
Your configuration for media files is right, the problem is that Django doesn't serve SVG files with the right mime type by default, this answer explains how to make it work.

How to add django template variable in <img src>?

I have a Photo model with two fields:
title = models.CharField()
path = models.CharField()
When I adding the new photo in admin panel, the path is equals to /images/image_ex.jpg This is my view file:
def gallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
This is the tag in gallery.html:
{% loadstaticfiles %}
<img src="{%static '{{photo.path}}'%}"/>
The problem is that the photo does not render and if I look in the code of the page, the src is equals to something like that:
src="static/%7B%7B%20photo.path%20%7D%7D"
What is the problem? How can I use template variables in src?
P.S. The images folder exists in static folder, the image exists too. I added static directory to settings.py. Also if I change src to a normal one, like
<img src="{static 'images/image_ex.png'%}">
The photo renders normally.
You here pass '{{photo.path}}' as a string to {% static ... %}, hence it will simply prepend the static URL root to this string.
If you want to use the content of photo.path, you can use:
<img src="{% static photo.path %}"/>
So {% static ... %} accepts variables as parameters, and will take the content of the path attribute of the photo variable. (of course given that variable is passed, or is a variable you generate with {% for ... %} loops, etc.
Uses a for tag
{% for p in photos %}
<img src="{% static '{{ p.path }}' %}"/>
{% endfor %}
Better uses Imagefield as field in your model
In your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Create a folder named “media” in your project (at the same level that your apps)
In your urls.py (main)
from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In your models.py
Replace the CharField with Imagefield
image = models.ImageField(upload_to="my_folder_name")
Like this:
class Photo(models.Model):
title = models.CharField()
image = models.ImageField(upload_to="my_folder_name"))
In your views.py
def gallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
In your templates
{% for p in photos %}
<img src="{{ p.photo.url }}"/>
{% endfor %}
Do it like this:
<img src="{static 'images/'%}{{image_ex.png}}">
Use it after the static tag scope ends.
For Template
{% for image in all_image %}
<img src="{{ image.image.url }}"/>
{% endfor %}
Solved: load image dynamically in survey.html
"survey.toolsTechnology" is a dynamic variable, every time the
variable changes, the image also changes based on it.
<img src="{% static 'images/'%}{{survey.toolsTechnology}}.png"/>

Static image url is returned without MEDIA_URL

i followed this tutorial about displaying profile pictures on website, i did everything correctly (i hope so) but instead of returning example.com/media/posters/pic1.jpg it returns example.com/pictures/pic1.jpg (real example)
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
views.py
def index(request):
movies = {'movies' : movie.objects.all()}
return render(request, 'index.html', movies)
models.py
class movie(models.Model):
poster = models.ImageField(upload_to='posters')
and html
{% for a in movies %}
<img src="{{ a.poster }}" alt="">
{% endfor %}
i added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to urls.py file
also, i had to use a.poster instead of poster.image.url, it just returned unknow, different django version i assume
You need {% get_media_prefix %}.

Categories

Resources