I'm trying to use {{ MEDIA_URL }} in my template tag. This is my html code:
<li data-ng-repeat="image in pictures[currentCat]">
<a>
<img src="{{ MEDIA_URL }}{$ image.imgs $}" />
</a>
</li>
I'm sending the json to a js and use it in AngularJS
$http.get("imagelist/").success(function(data) {
$scope.pictures=data;
});
And I've add this part to my setting.py:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.media",
)
Now this answer suggest to do this
from django.template.context import RequestContext
context = {'latest': p}
render_to_response('Question/latest.html',
context_instance=RequestContext(request, context))
But I'm using HttpResponse and it doesn't work on my code.
def getimagelist(request):
dictionaries=[]
for cat in Category.objects.all():
dictionary=[obj.as_json() for obj in Gallery.objects.filter(cat_id=cat.id)]
dictionaries.append(dictionary)
return HttpResponse(json.dumps(dictionaries), content_type='application/json')
My question is how to use {{ MEDIA_URL }} in my code when using HttpResponse ?
Currently it shows blank in my html.
Thanks
Turned out I didn't need any of those. Since I'm using nginx to handle my site, I just added media path to nginx locations
location /media/ {
autoindex on;
alias mysitepath/media/;
}
and changed my html code like this
<img src="/media/{$ image.imgs $}" />
So now everythong works just fine
You're not passing the MEDIA_URL variable in your response's context. You should be doing something like this:
from django.conf import settings
data = {'pictures': dictionaries, 'mediaUrl': settings.MEDIA_URL}
HttpResponse(json.dumps(data), content_type='application/json')
In your angular code:
$http.get("imagelist/").success(function(data) {
$scope.pictures = data.pictures;
$scope.mediaUrl = data.mediaUrl;
});
And in your template
<img src="{$ mediaUrl $}{$ image.imgs $}" />
That way, the media url is passed from your settings down to your angular app and loaded in the angular template (all of this could use better naming though, but you get the idea).
Related
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.
I have trouble displaying images stored in a file server to the django template.
File server link is \11234.123.123.123\dashboard.jpg (just a sample).
It seems like the img src url is being added by the django localhost url prefix to the file server path as follows: http://127.0.0.1:8000/dashboard/\\11234.123.123.123\dashboard.jpg
In django template, the img tag is written as:
<img class="imgView" src="{{dashboard_image}}" alt="Dashboard画面.jpg"></img>
My views.py just sends the image file server URL as text (with value of \11234.123.123.123\dashboard.jpg) to be displayed as image in the HTML page as the django template.
def dashboard(request):
dashboard_image_url = '\\11234.123.123.123\dashboard.jpg' #TODO temporary, just sample
context = {'dashboard_image': dashboard_image_url}
return render(request, 'dashboard.html', context)
But, the image does not show properly as follows.
Please help, thank you!
In your template instead of:
<img class="imgView" src="{{dashboard_image}}" alt="Dashboard画面.jpg"></img>
DO this:
<img class="imgView" src="{{dashboard_image.url}}" alt="Dashboard画面.jpg"></img>
<img class='img-responsive' src="{{ MEDIA_URL }}{{ item.image.url }}" />
or
<img class='img-responsive' src="{{ item.image.url }}" />
and in main urls.py
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)
I have set up my media root, media url etc. so the file will show up when I call
http://127.0.0.1:8000/media/something/somewhere/my_pdf.pdf
Now I want to show the same file within a template (i.e. the PDF in an object or embed tag plus some other stuff. I pass the path to the file (i.e. everything after 'media' in the view context, something like:
def test_doc(request):`
p = r'something/somewhere/my_pdf.pdf'`
return render(request, 'documents/test.html', {'pdf':p})
So what do I have to put in my template? I tried
<object data="{{ MEDIA_URL }}{{ pdf }}">something</object>
and many many variations thereof. What am I doing wrong?
I tested your approach and I believe I was able to reproduce your issue.
PDF was displayed in browser from address: http://127.0.0.1:8000/myapp/media/myapp/my_pdf.pdf
PDF not displayed when loaded into an object with <object data="{{ MEDIA_URL }}{{ pdf }}"></object> in template
PDF not displayed when loaded into an object with <object data="{% get_media_prefix %}{{ pdf }}"> in template
There are two problems occurring simultaneously.
Django's default project settings enable clickjacking protection using X-Frame-Options. This does not prevent loading the media files with a direct request, but does so when you try to load media into an object. Firefox Inspector shows an error message: The loading of “http://127.0.0.1:8000/myapp/media/myapp/my_pdf.pdf” in a frame is denied by “X-Frame-Options“ directive set to “DENY“.
Django's documentation tells to use #xframe_options_exempt decorator for the view. It did not help in my tests. Disabling clickjacking protection by commenting out 'django.middleware.clickjacking.XFrameOptionsMiddleware' in settings.py allowed me to display PDF in an object with <object data="media/myapp/my_pdf.pdf"> in the template.
Both {{ MEDIA_URL }}{{ pdf }} and {% get_media_prefix %}{{ pdf }} tags in the template lead to loading the PDF from the disk with path "/media/myapp/my_pdf.pdf". Note the extra "/" in the beginning. You can prevent this by defining p = 'media/myapp/my_pdf.pdf' in the view and using <object data="{{ pdf }}"> in the template. Not very elegant, but works when clickjacking middleware is disabled.
Since you have set up MEDIA_ROOT and MEDIA_URL, you should use the {% get_media_prefix %} template tag:
{% load static %}
<object data="{% get_media_prefix %}{{ pdf }}">something</object>
EDIT:
If you are running in development mode (DEBUG = True), you also need to change your urls.py to serve media files:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ...
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
According to your code it doesn't look like MEDIA_URL is defined in your views context.
from django.conf import settings
def test_doc(request):`
p = r'something/somewhere/my_pdf.pdf'`
return render(request, 'documents/test.html', {'pdf':p, 'MEDIA_URL': settings.MEDIA_URL})
To complete answer of drec4s that fixes Django side stuff, you will need to add a markup like this one on your template :
<embed type="application/pdf" src= "{% get_media_prefix %}{{ pdf }}" width= "500" height= "375">
So I am trying to give the absolute path for the static folder. Can you point what I am doing wrong?
My template looks like
<img src="{{ALLOWED_HOSTS}}{% static 'assets/img/logo-ST.png' %}" alt="logo" border="0" width="102">
And in the Settings
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', str)
I know I'm doing something wring with the hostname and port, can you please help?
You probably want the url, not the file path, so just use:
<img src="{% static "assets/img/logo-ST.png" %}" ...>
in your template, and
STATIC_URL = 'http://example.com/'
in settings.py.
(remember to run python manage.py collectstatic)
Add a BASE_URL constant to your settings file
# settings.py
BASE_URL = env.str('BASE_URL')
Create a template tag
# templatetags/__init__.py
# templatetags/settings_tag.py
from django import template
from django.conf import settings as django_settings
register = template.Library()
#register.simple_tag
def settings():
return django_settings
Your email template
{% load settings_tag %}
<img src="{% settings.BASE_URL %}{% static 'assets/img/logo-ST.png' %}" alt="logo" border="0" width="102">
My settings.py contains the following configuration parameters.
STATIC_ROOT = ''
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
'C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows',
)
My project's CSS file is located at C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows/static/default.css.
I have a mock HTML file that should pull in the CSS content, but the URL is a 404.
<link rel="stylesheet" href="{{ STATIC_URL }}static/default.css" />
What am I doing wrong?
Things to check:
DEBUG = True in settings.py
urls
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
use context processor or load static if {{ STATIC_URL }} isn't working
If {{ STATIC_URL }} isn't working in
your template, you're probably not
using RequestContext when rendering
the template.
As a brief refresher, context
processors add variables into the
contexts of every template. However,
context processors require that you
use RequestContext when rendering
templates. This happens automatically
if you're using a generic view, but in
views written by hand you'll need to
explicitally use RequestContext To see
how that works, and to read more
details, check out Subclassing
Context: RequestContext.
<link rel="stylesheet" href="{{ STATIC_URL }}default.css" />
You need to also edit your urls: