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.
Related
I have been working on a social media website where you can upload images and videos and follow other users.
I managed to upload and display uploaded files to the website.
I used FileField to load the image and video files, but when I implement it in my Template it shows both spaces, because there both using the same source url {{ source.file.url }}
models.py
class Post(models.Model):
title = models.CharField(max_length=150)
file = models.FileField(upload_to='uploads/%Y-%m-%d')
models code works perfectly
feeds.html
{% if post.file.url %}
<video class="video-context" width="500px" height="500px" controls>
<source src="{{ post.file.url }}" type="video/mp4">
</video>
{% endif %}
{% if post.file.url %}
<img class="image-context" src="{{ post.file.url }}" type="image/jpg" type="image/jpeg">
{% endif %}
heres a sreenshot empty video player over img
Now the problem is that both File Types are going trough one Model: FileField. The source is {{ source.file.url }} , the HTML is searching both files, but there only either image or video, so what can i do with the other empty file?
How can I hide it?
You can use the download link without specifying the file type.
<a href src="{{ post.file.url }}">
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
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 %}
I am trying to get all image link present in a folder. Currently, I am assigning the link manually. But, I want my django to get all images from a specific folder irrespective of their names.
<li>
<img src="{% static "styles/jamia/1.jpg" %}">
</li>
<li>
<img src="{% static "styles/jamia/2.jpg" %}">
</li>
I am looking for something like:
{% for file in {% static "styles/jamia/" %} %}
<img src="{{file}}" alt="">
{% endfor %}
All images are present in jamia folder.
This isn't something Django has built in. But Django is just Python, and you can use normal Python file functions to get your list in the view:
files = os.listdir(os.path.join(settings.STATIC_ROOT, "styles/jamia"))
This seems to have been answered in parts before, but probably requires some searching for all the answers. So in an attempt to provide a complete answer to this questions in one place:
In views.py you would want to do something like the other answer says:
context_dict = {}
files = os.listdir(os.path.join(settings.STATIC_DIR, "styles/jamia/"))
context_dict['files'] = files
return render(request, 'home.html', context=context_dict)
Then in your html template you can loop over your images. In addition, we make use of with to join the root to the static file with those names pulled out in the views.py, but you could have concatenated the whole path in views and not needed with. So, in home.html:
{% for file in files %}
{% with 'images/'|file as image_static %}
<img src="{% static image_static %}" alt="">
{% endwith %}
{% endfor %}
I've been looking at the sorl-thumbnail's documentation, and I still can't figure out how to:
upload images to sorl-thumbnail.
selectively show images from sorl-thumbnail.
(for example, load a specific image from sorl-thumbnail from a view and show it, with customized size, etc.)
Could you give some specific examples on how to use this library in a django view?
If you want greater flexibility you can generate the thumbnail right in the view. The following is straight from the sorl-thumbnail documentation:
from sorl.thumbnail import get_thumbnail
im = get_thumbnail(my_file, '100x100', crop='center', quality=99)
im then is the same thing as what you'd get back from the thumbnail template tag. So, you can add that variable to the template context, or just some part of it. For example if you just wanted the URL:
my_context = {
'image_url': im.url,
}
You can use sorl.thumbnail using the thumbnail template tags. Here's an example:
{% load thumbnail %}
{% thumbnail recipe.image "430x250" as thumb %}
<img src="{{ thumb.url }}" width="{{ thumb.width }}" height="{{ thumb.height }}" alt="{{ recipe.title }}" />
{% endthumbnail %}
You don't upload images to sorl.thumbnail or load them from sorl.thumbnail. After proper configuration it will resize and store the images automatically and you can use the thumbnail template tag to get the proper URL of the image.
When I have to use sorl-thumbnail I make difference between 2 kind of images:
Django objects with ImageField
When I have an object in Django with an ImageField I render it with thumbnail like this:
# Let's supose our object imagefield is called img
{% thumbnail obj.img "100" upscale=false as im %}
<img src="{{ im.url }}"/>
{% empty %} # In case the object doesn't have an image, use generic one
{% thumbnail "img/empty_img.jpg" "236" upscale=false as im %}
<img src="{{ im.url }}" />
{% endthumbnail %}
{% endthumbnail %}
Images by url/path
To load images using local path of the project:
{% thumbnail "img/myImage.jpg" "236" upscale=false as im %}
<img src="{{ im.url }}" />
{% endthumbnail %}
Important: Remember that thumbnail concatenates the MEDIA_URL to the path you provide, so in this case you need a path like yourapp/media/img/myImage.jpg
To load images using an URL is easy and sample:
{% thumbnail "http://www.nextgen-gallery.com/wp-content/uploads/2008/12/abend.jpg" "236" upscale=false as im %}
<img src="{{ im.url }}" />
{% endthumbnail %}