Django ImageField upload_to path - python

I'm having trouble understanding and using Django's ImageField.
I have a model:
class BlogContent(models.Model):
title = models.CharField(max_length=300)
image = models.ImageField(upload_to='static/static_dirs/images/')
description = models.TextField()
My file system is currently:
src
|---main_project
|---app_that_contains_blog_content_model
|---static
|---static_dirs
|---images
When I run the server and go to the Admin page, I can add BlogContent objects. After choosing an image for the image field, the image has a temporary name. However, after I save this object I can't find the image in the folder specified by the upload_to path.
What is the correct way to do this?

Your image would be uploaded to the media folder, so it's better to change path in the model like images/, and they will be upload to media/images
In settings.py add this
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In url.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And then, if you want to display all this image, use something like this
in view.py
BlogContent.objects.all()
And render it like this:
{% for img in your_object %}
<img src="{{ img.image.url }}" >
{% endfor %}

static in upload_to doesnot make sense, since user-uploaded images go into media/ folder.. you need these:
image = models.ImageField(upload_to='blog/%Y/%m/%d')
and all images land in:
media/blog/2016/01/02/img_name.jpg
you access it in template like this:
<img src="{{ blog.image.url }}">
in settings:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

You should use media path, instead static. See docs

Related

Django: How to show a picture from my database in a template?

I'm using Django, and trying to display a picture from my database. However, I am unable to.
Most of the code I am using is from this article.
This is my code.
My model("ingredient") uses:
title = models.CharField(max_length=50, primary_key=True)
pictureLink = models.ImageField(upload_to="media")
The pictureLink I provided in my database is:
C:\Users"Me"\Desktop"project"\image\leaves.png
My views.py contains:
def say_hello(request):
allimages = Ingredient.objects.all()
return render(request, 'hello.html', {'images' : allimages})
My HTML code is the following:
{% for img in images %}
<tr>
<td>{{img.title}}</td>
<td><img src="{{ingredient.pictureLink.url}}" width="120"/></td>
</tr>
{% endfor %}
In settings.py I put the following:
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_ROOT = os.path.join(BASE_DIR, 'image')
MEDIA_URL = '/image/'
Where am I making a mistake? I'm a beginner with Django, so all feedback is appreciated!
first change your settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = "/media/"
STATIC_URL = '/media/static/'
STATICFILES_DIRS = (BASE_DIR / 'media/static', )
STATIC_ROOT = 'media/staticfiles/'
second create a folder named media in your path
then add this to urlpatterns in your app urls.py to this:
url(r'^media/(?P<path>.*)/$', serve, {'document_root': settings.MEDIA_ROOT}, name = 'media'),
Do not forget to import these in the urls.py file in your application folder
from django.conf import settings
from django.conf.urls import url
from django.views.static import serve

Django - Unable to display an image from folder within media folder

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

Cant see image from project directory

I tried to handle this but I gave up. I have folder with images and I want to display my some image in html view but It wont work.
I followed this tutorial enter link description here
this my project tree:
As you can see I tried to create plenty of directories to make it work.
This is my settins:
STATIC_URL = '/static/'
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "media"),
# '/webstore/',
# ]
MEDIA_ROOT = '/webstore/media/'
MEDIA_URL = '/media/'
this is my html view where I try to display my image
<img src="/media/example.jpg" />
this is my urls.py file
from django.conf.urls import url, include
from django.contrib import admin
from djangoproject import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^', include('webstore.urls')),
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MEDIA_URL is the base URL to serve the media files uploaded by users, and MEDIA_ROOT is the local path where they reside.
so try to use it on your setting.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
and on your main urls.py
urlpatterns = [
....
]
if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and should the entire image will be saved in your djangoproject/media/
one more thing don't forget to add {% load staticfiles %} on top your html file. {% load staticfiles %} tells Django to load the staticfiles template tags that are provided by the django.contrib.staticfiles application.
MEDIA_ROOT is the absolute filesystem path to the directory that will hold user-uploaded files.
STATIC_ROOT is the absolute filesystem path to the directory from which you’d like to serve these files.
Since, you would like to serve images, give the absolute path of your static directory to STATIC_ROOT.
Give relative path with respect to your STATIC_ROOT in STATIC_URL.
Also, change your urls.py with the static_url and static_root.
Another Suggestion: Easier way to display an image is to upload it to image servers like imgur and give the url of the image in the html.
For e.g. :
<img src="http://i.stack.imgur.com/nbegK.png" />
The only thing you have to do is
MEDIA_ROOT = '/absolutepath/to/djangoproject/webstore/media/'
Then you have already
MEDIA_URL = '/media/'
and try
<img src="/media/example.jpg" />

how to access upload images

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

Django not show images

Pls tell me. Why ../static/image.jpg show images, and ../media/image.jpg now show
Need write url? Need change Setting? i dont fiend answer in documentation.
pls help.
2 night search answer.
Need upload from admin-panel photo and show in templates.
<img src="{{ tovar.product_img.url }}">
To display image you need load the static files in your template before referencing them. This is how you should display a picture in your template:
{% load staticfiles %}
<img src="{% static 'image.jpg' %}">
This image needs to be stored in your static folder. ../YourApp/YourApp/static/image.jpg is where I keep my static folder. Obviously it would be better to structure it further with images folder inside the static folder etc..
In your settings file you need the following lines:
# Static asset configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
This should do the trick for you.
In settings.py
MEDIA_ROOT = '/path/to/yourmediafolder/'
MEDIA_URL = '/media/' # whatever but it should same in `urls.py`
In urls.py
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Then in template
<img src="{{ MEDIA_URL }}images/imagename.jpg"/>
Note: Here image should be as '/path/to/yourmediafolder/images/imagename.jpg'
Complete example:
I have an image test.jpg as '/home/me/test.jpg
MEDIA_ROOT = '/home/' # or /home/me/ but change url in image src
MEDIA_URL = '/media/'
#urls.py same as above
In template
<img src="{{ MEDIA_URL }}me/test.jpg"/> # or <img src="{{ MEDIA_URL }}test.jpg"/> as or condition above in MEDIA_ROOT.
Note that {{ MEDIA_URL }}me , no / between them because MEDIA_URL='/media/
You can test by:
http://domain.com/media/me/test.jpg # or http://domain.com/media/test.jpg as OR condition in MEDIA_ROOT
in local:
http://localhost:8000/media/me/test.jpg #in locally
This works (in the html img tag):
src="(left squiggly, percent) static poc.image.name (percent, right squiggly):
...and thanks to whoever pointed out that ImageField has a name in addition to a (useless) path and (useless) url e.g.:
>>> from nutr.models import *
>>> poc=POC.objects.get(pk=87)
>>> poc.name
'Edgar'
In Django==2.0.2 use {% get_media_prefix %}
From the docs

Categories

Resources