django loop static files directory - python

Iam trying to loop thru images in static/folder. I can loop thru images in main 'static' folder but when i put them in 'static/folder' iam not sure how to do it in html.
my html lines(works when img in main 'static' folder)
{% for file in files %}
<img src=" {% static file %}" height="800">
<p>File name:{{ file }}</p>
{% endfor %}
my views.py
def album1(request):
images = '/home/michal/PycharmProjects/Family/gallery/static/'
files = os.listdir(os.path.join(images))
context = {'files': files}
return render(request, 'gallery/album1/main.html', context)
If i change views to:
def album1(request):
images = '/home/michal/PycharmProjects/Family/gallery/static/'
files = os.listdir(os.path.join(images, 'folder'))
context = {'files': files}
return render(request, 'gallery/album1/main.html', context)
It loops filenames in 'static/folder/' as expected, but then i cant figure out how to change it in html ,as its adding file names to: /static/{{ file }} instead to /static/folder/{{ file }}.
I think iam missing something or something need changing in load static on this particular page?
{% load static %} # either here
<img src=" {% static file %}"> # or here?

You prepend the filenames with the name of the folder:
from os.path import join
def album1(request):
images = '/home/michal/PycharmProjects/Family/gallery/static/'
files = os.listdir(join(images, 'folder'))
context = {'files': [join(folder, file) for file in files]}
return render(request, 'gallery/album1/main.html', context)
You can slice in the template with the |slice template filter [Django-doc]:
{% for file in files|slice:':21' %}
<img src=" {% static file %}" height="800">
<p>File name:{{ file }}</p>
{% endfor %}
But it is more efficient to do this in the view, since you save cycles on by performing less join calls, and furthermore the templates are less efficient than Python code.

Related

Django database stored images showing only text descriptions

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.

Django: Using a for loop to view all images from my db - using img src

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

Unzipping file submission without storage in Django

I'm currently building an application that will be used and maintained by another developer shortly in the future. What I want is the ability to upload a zip file, unzip and process the contents, and discard the file without ever actually storing it in the Django file storage system. These are the relevant parts of what I have right now:
views.py:
def upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
if str(myfile.name).endswith('.zip'):
## THIS STORES THE FILE -- NOT WHAT I WANT
#fs = FileSystemStorage()
#filename = fs.save(myfile.name, myfile)
uploaded_file_url = str(myfile.name)
return render(request, 'webapp/upload.html', {
'uploaded_file_url': uploaded_file_url
})
file_error = "There was an error processing the file"
return render(request, 'webapp/upload.html', {
'file_error': file_error
})
return render(request, 'webapp/upload.html')
upload.html
{% extends "./base.html" %}
{% block content %}
<body>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: {{ uploaded_file_url }}</p>
{% endif %}
{% if file_error %}
<p>There was an error in the file submission.</p>
{% endif %}
</body>
{% endblock %}
I know that checking if a file ends with .zip is not necessarily indicative of whether it's actually a zip file or not but it is sufficient for my purposes right now. myfile is a UploadedFile and I'm trying to find a way to unzip and process the contents but I'm not sure how to go about this. I could just store it in the FileSystem and then process it from there but I'd like to avoid storing it at all if possible. Any suggestions on how to do this would be greatly appreciated.

Iterate through a static image folder in django

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 %}

Uploading image from Imagefield in django

I am new to Django.I have the following code on my html file:
{% load staticfiles %}
<form method="post"> {% csrf_token %}
<input type="file" name="file">
<button>Submit</button>
</form>
{{file}}
<img class="hl" src="{{ MEDIA_URL }}photos/abc.png" /></a>
<img class="hl" src="{% static 'blog/images/sec.png' %}" /></a>
and my views.py for the above code is:
if request.method == 'POST':
if 'file' in request.POST:
f = request.POST['file']
a = MyUser(email="frt#wer.com", date_of_birth=date.today())
a.photo.save('somename.png', File(open(f, 'r')))
a.save()
context = {'file': f}
return render(request, 'home.html', context)
Now browsers do not return the absolute path of the file from user's local device, it just gathers filename because ofsome security issues but a.photo.save('somename.png', File(open(f, 'r'))) this part of my code needs absolute path of user local device that is something like /home/abc/Pictures/sec.png all i get is sec.png and hence i am unable to upload.
From python manage.py shell:
>>>a = MyUser(email="frt#wer.com", date_of_birth=date.today())
>>>a.photo.save('somename.png', File(open('/home/abc/Pictures/sec.png', 'r')))
>>>a.save()
This works fine. Is there some workaround. I dont want to use Form.
I would suggest that if you want to allow for a file upload that you use a File form rather than a workaround. A simple and very succinct example can be found here:
Need a minimal Django file upload example

Categories