this is the code in my models file:
from django.db import models
class Studio(models.Model):
.....
.....
metroimage = models.ImageField(upload_to='images', blank=True)
this is the code on the template file:
{% for place in studio %}
.....
.....
<img class="metro" src="{{ place.metroimage.url }}"><b>{{ place.metro }}</b><br>
{% endif %}
but when the page displays i get this (this is source-code)
.....
.....
<img class="metro" src="/http://momo.webfactional.com/media/images/m3.png"><b>Zara</b><br>
what's with the forward slash before http? i can't get the uploaded image to display...
I'd guess your MEDIA_URL settings (in settings.py) is to blame for the extra slash.
Related
To clarify my title, I have a database set up in my Django application that takes information from albums, including album covers. The image saves in the database, goes to the correct MEDIA_ROOT specified in my settings.py file, and shows the correct url path when checking the request path. I am using the latest version of Django and have Pillow installed to add the images into the database through the admin site.
Previously, when the file path was wrong, Django served a 404 error and couldn't find the file. Now that the path is correct, it loads for a moment and then says "server not found". When I inspect the image, it says that the "connection used to fetch this resource was not secure." however I am running the server locally and am not in a production enviroment, and all answers related to this issue seem to come from running the server in production.
When I attempt to open the image in a new tab, the tab says "Server not found" after attempting to load the filepath: "http://albums/filename_oja97pG.png" (you can see here the unsercure http response. I replaced the file name for privacy reasons.)
I am unsure what would be causing this issue. Here is my code:
models.py
class Album(models.Model):
title = models.CharField(
max_length=200,
validators=[MinLengthValidator(2, "Must be at least two characters.")]
)
release_date = models.DateField()
picture = models.ImageField(upload_to='albums/', blank=True)
content_type = models.CharField(max_length=256, blank=True, help_text='The MIMEType of the file')
description = models.TextField(blank=True)
def __str__(self):
return self.title
settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
urls.py
urlpatterns = [
path('', views.MusicView.as_view(), name='music'),
path('albums/<int:album_id>', views.AlbumView.as_view(), name='album_detail'),
]
projects urls.py
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class AlbumView(DetailView):
model = Album
template_name = 'music/album_detail.html'
def get(self, request, album_id):
al = Album.objects.get(pk=album_id)
if al is not None:
context = {
'album' : al,
}
return render(request, self.template_name, context)
else:
raise Http404('Album does not exist.')
html template being served
{% extends 'base.html' %}
{% block welcome %}
{{ album.title }}
{% if album.content_type %}
<img src="/{{ BASE_DIR }}/{{ album.picture }}">
{% endif %}
{% endblock %}
Thanks for the help. Let me know what other information I can provide. I have attempted to load in other borwsers and have gotten the same problem.
You can try to use the url directly from the ImageFile field, so in your template:
{% extends 'base.html' %}
{% block welcome %}
{{ album.title }}
{% if album.content_type %}
<img src="{{ album.picture.url }}">
{% endif %}
{% endblock %}
I am trying to store images on a database and then display them on a Django template. For some reason Django is only showing the alt (alternate - html attribute) instead of the actual image.
This is the template
{% extends "myapp/layout.html" %}
{% load static %}
{% block body %}
<div class="sidenav">
Gallery
About
Contact
</div>
<div class="main">
<h2>Gallery</h2>
{% for image in images %}
<img class="gallery" src="{% static '{{image.image.url}}' %}" alt="{{image.description}}">
{% endfor %}
</div>
{% endblock %}
This is my model
from django.db import models
# Create your models here.
class Image(models.Model):
image = models.ImageField(upload_to='images/')
description = models.CharField(max_length=50)
def __str__(self):
return "Description of image: " + self.description
This is what I'm seeing
These are normally media urls, so you render these with:
<img class="gallery" src="{{ image.image.url }}" alt="{{image.description}}">
You need to add the views regarding media files to the urlpatterns, as described in the documentation.
or if these really only contain a path relative to the static folder, you work with:
<img class="gallery" src="{% static image.image.url %}" alt="{{image.description}}">
But it is not very likely that this is the case.
Regardless what the Note that Django only serves static/media files in debug mode (DEBUG = True). If you run this on production, you will need to configure apache/nginx/… to serve static/media files.
I am currently learning Django and making my first steps. I try to build a webgallery to learn all the basic stuff. I successfully displayed some images using static files. So I tried saving Images through ImageFields and "upload_to" in my DB, saving it to my static directory. I tried to display everyone of them with a for loop in an tag. My img displays properly with using a {% static %} tag but when I try to insert a {{ }} Tag it isn't working, although it's the same url it doesn't work.
I tried changing my STATIC FILE in settings.py
I tried various other forms of nesting my {{}} in there
Reading the docs to staticfile https://docs.djangoproject.com/en/2.2/howto/static-files/
This thread Display an image located in the database in Django
This thread https://docs.djangoproject.com/en/2.2/topics/files/#using-files-in-models
My Code:
<p>Overview</p>
{% block content %}
<div>
{% for image in images %}
{{ image.img_photo }} <!-- webgalleries/test.jpg -->
{% load static %}
<img src="{% static 'webgalleries/test.jpg' %}" alt="{{ image }}"> <!-- working -->
<img src="{% static '{{ image.img_photo }}' %}" alt="{{ image }}"> <!-- not working -->
{% empty %}
<p>No content</p>
{% endfor %}
</div>
{% endblock content %}
I expect the output to be an img from my static directory.
A hint, some advice or other forms of help is highly appreciated.
Thank you so much!
okay if you want to display images from database you should do these steps :
1- go to your settings.py and write this code there ,
MEDIA_ROOT= os.path.join(BASE_DIR,"media")
MEDIA_URL= "/media/"
2- then create new folder in your project called 'media' and create folder inside 'media' called 'images' (finally result will be like this 'media/images' )
3- go to your model.py in your class that having 'img_photo'
and you should write the model like this
class Images(models.Model):
img_photo = models.ImageField(upload_to='images/',null=True, blank=True)
def get_image(self):
if self.img_photo and hasattr(self.img_photo, 'url'):
return self.img_photo.url
else:
return '/path/to/default/image'
def __str__(self):
return self.img_photo
4- go to admin.py then write :
from yourapp.models import Images
then add this line below
admin.site.register(Images)
then open your terminal or console and write :
1- python manage.py makemigrations
2- python manage.py migrate
5- in html code you must write :
{% for image in Images %}
<img src="{{ image.get_image }}" >
{% endfor %}
go to admin panel and upload any photo for test
Images cannot be shown in html.I wrote codes in models.py
class POST(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images/', blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
in views.py
def top(request):
content = POST.objects.order_by('-created_at')[:5]
return render(request, 'top.html',{'content':content})
in top.html
<div>
{% for item in content %}
<div>
<h2>{{ item.title }}</h2>
<img src="{{ item.image }}"/>
</div>
{% endfor %}
</div>
When I access in browser, html is shown.<h2>{{ item.title }}</h2> is shown but <img src="{{ item.image }}"/> is not there.When I see page source in GoogleChrome,<img src="/images/photo.jpg"/> is shown. But when I click the url,404 error happens.My application has image/images folder, in images folder surely my uploaded picture is in there.I really cannot understand why this happens.I wrote MEDIA_ROOT&MEDIA_URL in settings.py so I think image is shown in browser. How should I fix this?
make sure your /images folder is visitable in Django. an easy way to get it done is to add the "images" folder in settings.py. like:
IMAGE_URL = '/images/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "images"),
'/images/',
]
Then in your html file add {% load images %} on the top.
First make sure you have these lines in your project urls file
# Your imports ....
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [.......]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in your template use
{{ item.image.url }}
Use relative folder:
<img src=".{{ item.image }}"/>
resulting in
<img src="./images/photo.jpg"/>
and check if the upload worked and the image is there.
Try this: <img src="/image{{ item.image }}"/>
/ : means "Root"
. : means "Current directory"
so if your root application has image folder you need to start your path with /image
In my project i had set my media folder like this:
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns = [
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
then in my models.py i create a class like this one:
class PD_Pictures(models.Model):
pic_IDmod = models.ForeignKey(PD_Models, related_name='modello')
pic_image = models.ImageField()
pic_descr = models.CharField(max_length=50)
def __str__(self):
return self.pic_descr
at this point in my function in views.py I extract all values in db related to PD_Picture:
prod_img = PD_Pictures.objects.all()
.....
return render(
request,
'base_catalog.html',
{
'bike_mod': bike_models,
'prod_img': prod_img,
'cat_list': cat_list,
'menu_list': menu_list['menu'],
'pcontent': menu_list['cont'],
'form': c_form
},
context
)
and in my template, i would ti display related images:
{% for pic in prod_img %}
<div class="4u">
<span class="image fit"
<img src="{{ pic.pic_image }}" alt="" />
</span>
</div>
{% endfor %}
Well, at this point when I insert a new image in db, in table the path is newimage.jpg, physically on my server the image was stored in /media/newimage.jpg, how can I extract the value from the table and concatenate to the media path in my template? (<server>/media/newimage.jpg)
I have tried to use upload_to='/models/' in my ImageField but the only effect is to save image into another model folder into main model.
just try like this
{% for pic in prod_img %}
<img src="{{ pic.pic_image.url }}" alt="" />
{% endfor %}
From django official doc:
FieldFile.url
A read-only property to access the file’s relative URL by calling the url() method of the underlying Storage class.
if you try to print in your template {{ pic.pic_image }} you'll receive the db field value, while with {{ pic.pic_image.url }} the url() method from django.core.files.storage.Storage will call, and your base settings
would seem to be correct
Can you make this into your template and see what path is given?
{% for pic in prod_img %}
<p>{{ pic.pic_image }</p>
{% endfor %}