I am sending my images from my web server Django like follows :
localhost:8000/media/images/foo.png
My question is am I sending the images is the correct way? I think it is not necessary to send the server since I am the only one who serves the photographs. Any ideas, something like this media/images/foo.png.
In order that in the img tag of HTML this is a relative path and not a link.
For serving images in Django,
First make sure that you have your MEDIA_ROOT and MEDIA_URL defined inside the settings.py file.
Now let's say you have a model, models.py
class SomeModel(models.Model):
image = models.ImageField(upload_to = 'your_directory_inside_media')
#Rest of the fields
Next inside your views,
model_object = SomeModel.objects.get(...) #get an instance of model which has an ImageField
context = {'image' : model_object.image }
html = render(request , 'some_html.html' , context)
And finally inside your HTML,
{% load static %}
<img src="{% get_media_prefix %}{{ image.image }}">
Hope this helps. Thanks.
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)
What I want to accomplish is have an separate application generate graphs that will be placed in a directory of my Django project. Then in my template loop through and display all the graphs from that directory on the webpage. The generated graphs will be refreshed daily and will be of varying numbers depending on the day (so some days it could be 20 and/or the next it could be 50).
Option 1)
I don't think I want to use django manage.py collectstatic everyday. I've never gotten to the point of deploying a Django project to a server but my assumption is that I would have to collectstatic manually everyday on the server (which I could be thoroughly off on here)
Option 2)
I've tried creating a model Model Picture. The Char field is just my relative path to the picture. From there in my views I'm to rendering the path in the index(request) View Picture. From there in my template I'm trying to loop through the picture relative paths and show them Template Picture. When I remove photos = Photo.objects.all() & the {% for img in photos %} in the template the page does load Webpage working. However when I run it with all those parts in there I get a blank webpage with "what do you want to do with index" at the bottom. Webpage not working
Interested to hear if there are any better way of doing this . I'm not trying to user upload an image field because the amount of graphs will be substantial.
Details on Option 2:
---Notes---
Top Lvl Directory is--chartingtest-project
chartingtest is the project
sectors is the name of the app
media folder is a folder in the top level directory, not within the project or test folder
models.py in sectors app contains
class Photo(models.Model):
photoname = models.ImageField()
views.py in sectors app contains
from .models import Photo
def index(request):
pets = Pets.objects.all()
photos = Photo.objects.all()
return render(request, 'index.html', {'pets': pets}, {'photos': photos})
index.html template
{% load static %}
<H1>Hello World Index!</H1>
#Testing bringing in variables from a model (2020/05/07 Works!)
<ul>
{% for pet in pets %}
<li>{{pet.name}}</li>
{% endfor %}
</ul>
# ************************************
# This is where I'm trying display generated pictures from the media folder
# ************************************
<ul>
{% for img in photos %}
<li>
<img src="chart1s/{{img.image.url}}" />
</li>
{% endfor %}
</ul>
#Testing Static Image (2020/05/08 Works!)
<img src="{% static "OIP.jpg" %}"/>
<img src="{% static "temp_fig_00.png" %}"/>
settings.py in chartingtest project folder
#Media ROOT
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
You are correct that using static files will not work, by their name static files are not supposed to change.
The solution is to create a media folder and have your application save the graphs to that folder. Your model picture should point to that folder. Like you said, in your templates you can then iterate over that model to display all the graphs.
In production, you should create a cloud storage bucket and save your images there. Then make sure your settings.py directs any requests for images to your storage bucket.
Your picture model should use models.ImageField(), not a typical CharField, image = models.ImageField(). In your template as you iterate, you should call each image with <img src="{{ picture.image.url }}"
Apart from that, I would need to look in depth at the code to see what's going on, and I don't click links on stackoverflow posts. If you'd post the code in a comment might be able to take a closer link, but try those things first!
I am trying to render html to pdf, it really works great ! only there is an issue and that is the template getting image:
I am using python xhtml2pdf library for pdf render
this is my method for render pdf:
def render_pdf(template_src, context_dict):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('Unable to process the request, We had some errors<pre>%s</pre>' % escape(html))
and this is my views.py below:
def test_view(request):
context = {
'test': 'a test string'
}
return render_pdf('test.html', context)
and this my test.html
{% load static %}
<p>hello test </p>
<img src="{% static 'ok.jpg' %}">
It gets image if i render with django default render method But the image not getting when i render for pdf.
I heard of this solution with link_callback method with this documatin: https://xhtml2pdf.readthedocs.io/en/latest/usage.html
I am not getting where to include this or how can i achive this.
Can anyone help me in this case?
I suggest modifying your html template, and use the absolute / relative path (directory path in your hard drive) of the image file instead of using {% static %} tag. static tag is only good for rendering the HTMl, but pisa cant read the image from that.
I have this code from a project that generates a PDF from html, and my images are done like this:
<img src="{{ STATIC_ROOT }}/report/logo.png" >
where STATIC_ROOT is a variable passed from render context.
This worked for me if it is still relevant.
My static folder is in my root directory.
{% load static %}
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.
In my django application, I have created a django model with an ImageField.
The problem is that the image itself is not getting rendered on the template. However, the image path is displayed on the template itself.
Also when I look in my media folder, I can see that the images that I uploaded are stored there.
My media root configuration in settings.py is as follows:
MEDIA_URL = '/media/'
MEDIA_ROOT = ("D:/Work-Backup/LiClipse Workspace/vTryON_DJango_Integration/vTryON/templates/media"
)
My models.py is as follows
from django.db import models
class VTryON(models.Model):
modelId = models.CharField(max_length=100)
slug= models.SlugField(unique=True)
image=models.ImageField(upload_to="images/framethumbs/", help_text="not more than 1MB", default ='D:/Work-Backup/LiClipse Workspace/vTryON_DJango_Integration/vTryON/templates/static/images/frame2.jpg')
def __unicode__(self):
return unicode(self.modelId)
and my template is
<html lang="eng">
<head>
<title>vTryOn Attempt Using Django Framework</title>
</head>
<body class="body">
{{frame.image}}
</body>
</html>
The image path that is displayed on the template looks like this
images/framethumbs/fr_5.jpg
I have created a folder images/framethumbs under the MEDIA_ROOT url where all the images are stored. can it be a permission issue?
If so then, how and where do I give permissions?
I am using a Windows 7 PC. Thanks in advance.
Please make sure you have an entry in urls.py to server the static files, if not add this to urls.py file..
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Now to get the image you should use an image tag like this...
<img src="{{ frame.image.url }}" />
Hope this helps.