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 -->
Related
I have such models.py file
class Product(models.Model):
CATEGORIES = {
('Computer', 'Комп\'ютер'),
('Smartphone', 'Смартфон')
}
photo = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=128, blank=False)
description = models.CharField(max_length=5000, blank=False)
price = models.PositiveIntegerField(blank=False)
category = models.CharField(max_length=30, choices=CATEGORIES)
count = models.PositiveIntegerField(blank=False)
In settings.py i DON'T have media variables/dirs
Also i try to show images in such way
{% extends 'base.html' %}
{% block title %}Каталог{% endblock %}
{% block content %}
{% for i in products %}
<img src="{ static i.photo.url }">
{{i.title}}
{% endfor %}
{% endblock %}
Result:
I add my model objects in Django Admin
please see below configuration, have you done?
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# urls/path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
your HTML file
{% if i.photo %}
<img src="{{ i.photo.url }}">
{% endif %}
You don't need the static tag.
<img src="{{ i.photo.url }}">
You can add like this.
and run the collectstatic command to
<img src="{% static '/logo.png' %}"/>
python manage.py collectstatic
In settings.py i DON'T have media variables/dirs
you have to set MEDIA_ROOT and MEDIA_URL in settings.py and set the URL of each in urls.py because by default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you’re using these defaults.
check the official doc.
step - 1
configure media and static files like this
add this in your settings.py
STATIC_ROOT = BASE_DIR / 'static_cdn'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
and add this in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I seem do not understand what i am doing wrong. I have done research online to see if there is any changes, but yet none. Bellow is what i did
settings.py
STATIC_URL = '/static/'
STATIC_ROOT=[
os.path.join(BASE_DIR,"static"),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
url.py
urlpatterns +=static (settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
model.py
class product(models.Model):
imageone = models.ImageField(upload_to="productimage",null=True,blank=False)
views.py
def home(request):
product= product.objects.all()
context={'proudct':product}
template_name="name.html"
return render(request,template_name,context)
in template
{% for products in product %}
<img src="{{proudcts.imageone.url}}">
{% endfor %}
When i upload image from the admin, i get image location at http://127.0.0.1:8000/media/productimage/homepagebizalAfric.jpg, but image does not display. What i my doing wrong ?
The spelling in
context={'proudct':product}
{{proudcts.imageone.url}}
is correct?
\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)
I'm trying to upload a picture from ImageField in template, but it is not displayed. Code and screenshots will explain better.
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = '/media/veracrypt1/django/pycaba/pycaba/media/'
models.py
image = models.ImageField()
views.py
def thread(request, boardname, thread_id):
board = boardname
thread = thread_id
op_post = get_object_or_404(Posts, board=board, id=thread_id)
return render(request, 'board/thread.html', {'op_post':op_post})
thread.html
{% extends 'board/base.html' %}
{% block content %}
<div class="op_post">
<img src="{{op_post.image.url}}">
</div>
{% endblock content %}
thread.html source in browser
enter image description here
What Django version are you using? Have you included static file urls in you url patterns?
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}))