\project_structure
-app
\project
-settings.py
-...
\picture
-panda.jpg
I've uploaded the picture into picture.
class Goods(models.Model):
pic = models.ImageField(upload_to='picture')
And the data in database is picture/panda.jpg
Now,how can i show it in html?
I wrote this in html:
<p>{{each.pic}}</p>
<img src='{{ each.pic.url }}' />
And the source codes in browser is this:
picture/panda.jpg
<img src='picture/panda.jpg' />
The image was linked to http://localhost:8000/my_sell/picture/panda.jpg.And couldn't show.
How can i solve this,I've tried add media_root in settings.py and useless.
I did not check this but almost all code are taken from my working projects :).
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'media')
)
models:
from django.core.files.storage import FileSystemStorage
from django.conf import settings
image_storage = FileSystemStorage(
# Physical file location ROOT
location=u'{0}/my_sell/'.format(settings.MEDIA_ROOT),
# Url for file
base_url=u'{0}my_sell/'.format(settings.MEDIA_URL),
)
def image_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/my_sell/picture/<filename>
return u'picture/{0}'.format(filename)
class Goods(models.Model):
pic = models.ImageField(upload_to=image_directory_path, storage=image_storage)
views:
from django.shortcuts import render
def view_picture(request):
c = dict()
c['goods'] = Goods.objects.all()
return render(request, 'template.html', c)
templates:
{% for product in goods %}
{% if product.pic %}
<img src="{{ product.pic.url }}">
{% endif %}
{% endfor %}
Edited: Don't forget to add MEDIA_URL into root urls.py
if settings.DEBUG
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
I would like to display a list of files from the MEDIA_ROOT on my server in a form in the frontend of a Django app.
Below what I am trying to accomplish:
My actual code below. I am showing only the classes, functions and files impacted by the issue. At the end of the question you will find a link to the full project if something is missing.
views.py (I have two functions because I tried both approaches)
class SelectPredFileView(TemplateView):
"""
This view is used to select a file from the list of files in the server.
"""
model = FileModel
fields = ['file']
template_name = 'select_file_predictions.html'
success_url = '/predict_success/'
files = os.listdir(settings.MEDIA_ROOT)
def my_view(request):
my_objects = get_list_or_404(FileModel, published=True)
return my_objects
# TODO: file list not displayed in the HTML, fix
def getfilelist(self, request):
filepath = settings.MEDIA_ROOT
file_list = os.listdir(filepath)
return render_to_response('templates/select_file_predictions.html', {'file_list': file_list})
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
models.py
from django.db import models
from django.conf import settings
class FileModel(models.Model):
file = models.FileField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
path = models.FilePathField(path=settings.MEDIA_ROOT, default=settings.MEDIA_ROOT)
urls.py
from django.contrib import admin
from django.conf import settings
from django.urls import path, re_path
from django.views.static import serve
from django.conf.urls import url, include
from django.conf.urls.static import static
from App.views import UploadView, UploadSuccessView, IndexView, SelectPredFileView, PredictionsSuccessView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^App/', include('App.urls'), name="App"),
url('index/', IndexView.as_view(), name='index'),
# Urls to upload the file and confirm the upload
url('fileupload/', UploadView.as_view(), name='upload_file'),
url('upload_success/', UploadSuccessView.as_view(), name='upload_success'),
# Urls to select a file for the predictions
url('fileselect/', SelectPredFileView.as_view(), name='file_select'),
url('predict_success/', PredictionsSuccessView.as_view(), name='pred_success'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path('__debug__/', include(debug_toolbar.urls)),
re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),
] + urlpatterns
select_file_predictions.html
{% extends "index.html" %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
{% for file in my_objects %}
<input type="checkbox" name={ file } value="{ file }"><br>
{% endfor %}
<button type="submit" class="btn btn-primary">Upload file</button>
</form>
{% endblock %}
ISSUE: the file are not shown in the html template.
If you want to dive deep, the full code of the application is here: https://github.com/marcogdepinto/Django-Emotion-Classification-Ravdess-API
Questions I checked without being able to solve this issue:
1) Iterate through a static image folder in django
2) Django - Render a List of File Names to Template
3) List directory file contents in a Django template
I would do something like this:
views.py
from os import listdir
from os.path import isfile, join
import settings
from django.views.generic.base import TemplateView
class MyFilesView(TemplateView):
template_name = "select_file_predictions.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# List of files in your MEDIA_ROOT
media_path = settings.MEDIA_ROOT
myfiles = [f for f in listdir(media_path) if isfile(join(media_path, f))]
context['myfiles'] = myfiles
return context
select_file_predictions.html
{% extends "index.html" %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
{% for myfile in myfiles %}
<input type="checkbox" name={{ myfile }} value="{{ myfile }}"><br>
{% endfor %}
<button type="submit" class="btn btn-primary">Upload file</button>
</form>
{% endblock %}
i followed this tutorial about displaying profile pictures on website, i did everything correctly (i hope so) but instead of returning example.com/media/posters/pic1.jpg it returns example.com/pictures/pic1.jpg (real example)
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
views.py
def index(request):
movies = {'movies' : movie.objects.all()}
return render(request, 'index.html', movies)
models.py
class movie(models.Model):
poster = models.ImageField(upload_to='posters')
and html
{% for a in movies %}
<img src="{{ a.poster }}" alt="">
{% endfor %}
i added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to urls.py file
also, i had to use a.poster instead of poster.image.url, it just returned unknow, different django version i assume
You need {% get_media_prefix %}.
I am trying to load an image from a folder within 'media' folder (media/tshrirts) onto template using django. Below is my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = '/media/'
#MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = 'media'
**I tried both the roots none of them work.
Below is my models.py
from django.db import models
# Create your models here.
class tshirts(models.Model):
brand=models.CharField(max_length=50)
name=models.CharField(max_length=100)
price=models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='tshirts/')
def __str__(self):
return self.name
this is part of the tshirts.html Why image.url is none??
<div class='tshirts'>
{% for eachtshirt in alltshirts %}
<div class='tshirt'>
{{eachtshirt.brand}}
<p>{{eachtshirt.name}}</p>
<p>{{eachtshirt.price}}</p>
<img src="{{eachshirt.image.url}}"/>
{% if eachshirt.image.url == None %}
<p>{{"Image Not Found"}}</p>
{% endif %}
</div>
{% endfor %}
</div>
finally, urls.py
urlpatterns = [
.
.
.
url(r'^tshirts/',include('tshirts.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After I uploaded the image as an admin and clicked the link, the image was properly displayed.
http://127.0.0.1:8000/media/tshirts/t-shirt2.jpg - the image was displayed here.
How can I fix this, please let me know thanks!!!
Screenshot for the page
The root of your media, should include the BASE_DIR, like the following:
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
You have a typo in your template, you'are accessing {{eachshirt.image.url}} without t. the correct is
{{eachtshirt.image.url}} <!-- with t : each tshirt -->
something fail in my Django project, because the images that I load in the imagefields don't show in the view.
https://www.dropbox.com/sh/fvx6sfmxgm08xo6/AABVR-AQGeF52pCxlzVaLuDaa?dl=0
The crab's photo it's load with "static", but the second, that it's imagefield's photo.
enter image description here
Model:
class foto(models.Model):
nombre=models.CharField(max_length=50)
imagen=models.ImageField(upload_to='fotos/')
def __str__(self):
return self.nombre
View:
def general(request):
lista=foto.objects.all()
context={'material':lista}
return render(request,'indice.html',context)
settings:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
'/media/fotos/',
)
html:
{% load staticfiles %}
<html>
<head>
<title>Album de fotos</title>
</head>
<body>
<img src="{% static 'cangrejo.jpg' %}" />
{% if material %}
{% for a in material %}
<li>{{a.nombre}}: {{a.imagen}}</li>
<img src="{{a.imagen}}" />
{% endfor %}
{% else %}
<p>No hay fotos</p>
{% endif %}
</body>
</html>
Admin's URLS:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('colecion.urls')),
]
View's URLS:
from django.conf.urls import url, include
from colecion import views
urlpatterns =[
url(r'^$',views.general),
]
Edit: I already solve the problem!
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'ciencia/static')
models.py
foto=models.ImageField()
html
<img src="{% static alfa.foto %}" />
From the docs:
MEDIA_URL - "Absolute filesystem path to the directory that will hold user-uploaded files."
MEDIA_ROOT - "URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments."
Your current config's MEDIA_URL doesn't look right. It should be a URL, you have it set to a filesystem path. Try something like
MEDIA_URL = '/media/'
Add this to urls.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change {{a.imagen}} to {{a.imagen.url}}
I am creating one app using following two url's , homepage.html and detail.html.
*models.py*
class News(models.Model):
primary_image = models.ImageField("Main Image ",upload_to = "static/uploadedImg/main",)
secondary_Image = models.ImageField("Sub Image",upload_to = "static/uploadedImg/sub",)
In settings.py I had defined MEDIA and MEDIA_ROOT
I want to display random primary_image in homepage.html with primary_image as a link.
*articles.html*
<div id = "randommainImage">
<img src = "{{random_object.primary_image}}">
</div>
NewArticles
articles
db.sqlite3
manage.py
media
NewsArticles
README.md
static
NewsArticles\articles
admin.py
forms.py
models.py
static
Templates
tests.py
urls.py
views.py
Also, I want to display both primary_image & secondary_Image in a detail.html
Can anybody help me?
If you've defined correctly MEDIA and MEDIA_ROOT, to display the first image in the article.html template you use:
<img src = "{{ MEDIA_ROOT }}{{ random_object.primary_image }}" />
and likewise in the detail.html template:
<img src = "{{ MEDIA_ROOT }}{{ random_object.primary_image }}" />
<img src = "{{ MEDIA_ROOT }}{{ random_object.secondary_image }}" />
If you have these in your settings properly then you're ready to go:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
MEDIA_URL = '/media/'
A folder called media will be created to upload all the images in that folder.
Your image fields should look like this, I don't get why are you creating a folder for them in the static folder..
primary_image = models.ImageField(upload_to='uploadedImg/main/')
secondary_image = models.ImageField(upload_to='uploadedImg/sub/')
So your primary image will be in media/uploadedImg/main/img.png
View can look like:
def index(request):
context_dict = {}
news = News.objects.all()
context_dict['news '] = news
return render(request, 'index.html', context_dict, )
And to get the primary image you'll use {{ news.primary_image.url }} in your template.
edit>
Add this in your urls.py
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))