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">
Related
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'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.
I have an application where I upload images and the images are uploaded to a specific directory but after uploading which works fine if I attenp to click on the image url I get an error which says
The current URL, media/gallery/2017/12/28/230-256.png, didn't match any of these and also the image is not displaying in the browser html
below is my model and view despite having my media path defined in the settings
Models.py
class Gallery(models.Model):
name = models.CharField(max_length=400, db_index=True)
image = models.ImageField(upload_to='gallery/%Y/%m/%d', blank=True)
class Meta:
ordering = ('name',)
def __str__(self):
return self.image.url
Views.py
def index(request):
gallery = Gallery.objects.all()
context = {
'gallery': gallery,
}
template = 'gallery.html'
return render(request, template, context)
html
{% if gallery.image %}
<div><img src="{{ gallery.image.url }}"></div>
{% endif %}
While you are developing, in the project urls.py you must add
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This will make your uploaded file accessible by the application.
When on a production server, it is better if the webserver itself (apache, nginx, ..) can reach the location where the files are uploaded, you can find how to configure that in other answers (here for nginx, and here for apache
Your HTML needs to be something like this:
{% if gallery.image %}
<div><img src="{{ MEDIA_URL }}{{ gallery.image.url }}"></div>
{% endif %}
MEDIA_URL should be configured in settings.py. This should be set to the base URL from where you're serving the files stored in MEDIA_ROOT.
The URL attribute of the image field stores only the relative URL of the image.
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).
I'm working to build a django web application. I'm using adobe brackets for the html and I'm trying to use an image from my folders on the website. The image appears during the brackets simulation, but not during django runserver.
here is my folder directory:
mysite-
Images-
livestream-
helloworld.jpg
templates-
livestream-
helloWorld.html
This is a very simplified version of the site, but you get the idea.
My html code asks for the image:
<img src="../../Images/livestream/helloworld.jpg" alt="helloWorld" width="590" height="269">
when I run the django server it returns:
[18/Jul/2013 09:11:40] "GET /livestream/Images/livestream/helloworld.jpg HTTP/1.1" 404 2605
Does anyone know how to fix this issue?
This has to do with how your staticfiles app related settings are set up for your project.
You should also use the static template tag in order to fetch your static media.
For example, assuming that your structure under the location of any filepath within the STATICFILES_DIRS tuple is the following:
{{STATICFILES_ROOT_DIR}}/Images/livestream/helloworld.jpg
you can fetch the static file using:
{% load static from staticfiles %}
{% static "Images/livestream/helloworld.jpg" as myimg %}
<img src="{{ myimg }}" alt="helloworld" />
Why don't you set your {{ STATIC_URL }} in your settings, as per the docs to point to your Images folder and then just type in
<img src="{{ STATIC_URL }}livestream/helloworld.jpg" alt="helloWorld" width="590" height="269">
This is the standard approach to manage static files, and will turn out useful in the future as well