loading local files in django - django

I have a folder in c:\images, images here are updated by another app. Then I wanted a Django application to read those images on the admin site. The django applicationis sitting in c:\inetpub\wwwroot\myapp I have tried adding below lines in settings.py
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(CURRENT_PATH, '../../images').replace('\\','/')
MEDIA_URL = 'images/'
I also tried including the whole path in django admin as below in admin.py
def img_field(self, obj):
return format_html('<img src="{}" width="500" height="500" />'.format("c:\images\phot1.png"))
If i put online image link it works fine as below:
def img_field(self, obj):
img = "https://www.thebalancesmb.com/thmb/5G9LJXyFzbTVS-Fj_32sHcgJ8lU=/3000x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/start-online-business-with-no-money-4128823-final-5b87fecd46e0fb00251bb95a.png"
return format_html('<img src="{}" width="500" height="500" />'.format(img))
How can i get around this?

I got it I just needed to add the below lines in urls.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
#urls here
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
It is working fine.

Related

ImageField url attribute

Django 3.0.6
models.py
class Image(models.Model):
def image_tag(self):
return mark_safe('<img src="{}" width="150" height="150" alt={} />'.format(self.image_300_webp_1.url,
self.alt))
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
Test:
>>> from image.models import Image
>>> i = Image.objects.first()
>>> i.image_tag()
'<img src="/media/home/michael/PycharmProjects/pcask/pcask/media/image/1/1_300_1x.webp" width="150" height="150" alt=asdf />'
The problem:
Real path is /media/image/1/1_300_1x.webp. Could you tell me why it is: media + absolute path to the image? And how to get the correct path?
add Media url to urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
please see the docs!
Upload to was written wrongly. Wrong variant is commented.
def _get_upload_to(_, filename):
# dir_to_create = '{}/image/{}/'.format(MEDIA_ROOT, extrapolated_image_id)
dir_to_create = 'image/{}/'.format(extrapolated_image_id)

Why cannot I see the image file in django?

I tried to load an image file, but it didn't work. I uploaded the image file by admin. Thanks for the help!
here is my code
in urls.py
path('main/archive/<int:video_id>/', views.loadphoto, name='loadphoto'),
in views.py
def loadphoto(request, video_id):
target_img=get_object_or_404(Record, pk=video_id)
context={'target_img':target_img.picture}
in models.py
class Record(models.Model):
record_text = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
picture=models.ImageField(blank=True)
def __str__(self):
return self.record_text
in img.html
<img src="target_img">
Main
First You Need To Join Your Media directory to your app
Here is the Way You Can Do That:
First You Need To Add This in Your Setting.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASEDIR,'your folder directory')
#for example app/media or something
Then You Need To Create Media Url Here is The Way:
Then You Need To Add in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('main/archive/<int:video_id>/', views.loadphoto,name='loadphoto'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then You Need To Add This in Your Html File
<img src='{{ target_img.url }}'>
You Can See More Details Here:
https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.fields.files.FieldFile.url
ImageField is derived from FileField. In order to display the image in your template, you should provide its url, see https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.fields.files.FieldFile.url
The source attribute should instead by populated as follow:
<img src="target_img.url">

Django ImageField Image Not Displaying

I'm trying to use Django 2.0. I'm using the development 'runserver' right now, so please keep in mind that I'm not in production yet. I am familiar with the differences between the two with regard to static files.
I have a Blog Post model. In the admin, I want to be able to add an image to my model using ImageField. I'd like it to be optional, and provide a default image if none is added.
I am able to load images in admin. I am unable to render my image in my template. The console shows that Django is trying to GET my image, but my configurations have not worked so far.
Here's my model and relevant field:
from PIL import Image
class Post(models.Model):
....
thumbnail = models.ImageField(default='/img/default.png', upload_to='img', blank=True, null=True)
....
My model works well aside from the ImageField. My View works well, and I don't think there is any issue there.
Here is my urls.py
....
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
....
path('posts/', views.PostListView.as_view(), name='post_list'),
path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'),
path('post/random/', views.random_post, name='random_post'),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I'm not at all sure about how to handle static files vs. media files in my urls.py, especially with changes to Django in version 2.0.
Here's my relevant settings.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
....
'django.contrib.messages.context_processors.media',
....
]
},
},
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
I am equally unsure of what to put in my settings.py concerning media. My static CSS files are working just fine. I have a logo image in my static files that is rendering in my base template.
Here is my template tag for the ImageField:
<img class="card-image mr-3" src="{{ post.thumbnail.url }}" alt="Generic placeholder image">
Lastly, my /static folder and my /media folder are in the same directory. These are both in my app directory, /blog.
Can anyone see any blaring errors here, or can they make suggestions? My issue is the default image is not loading. The default image IS in the correct directory /media/img/. The console warning says "Not Found: /media/img/default.png".
Thanks in advance. Any suggestions will be helpful.
Django ImageField for Admin Panel
There is important thing you have to define your MEDIA_URL in urls.py.
Without this definition framework doesn't gives to you permission to access image
Setting.py
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
urls.py
if settings.DEBUG: # new
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Models.py
class Product(models.Model):
title = models.CharField(max_length=150)
image=models.ImageField(blank=True,upload_to='images/')
def __str__(self):
return self.title
def image_tag(self):
return mark_safe('<img src="{}" height="50"/>'.format(self.image.url))
image_tag.short_description = 'Image'
Admin.py
class ProductAdmin(admin.ModelAdmin):
list_display = ['title','image_tag']
readonly_fields = ('image_tag',)
Printing the media root helped me solve this issue. Thanks Alasdair.
I don't think there was any issue with my model field above.
The urls.py code that I ended up using is directly from Django docs for Django 2.0 in handling static files https://docs.djangoproject.com/en/2.0/howto/static-files/.
The changes I made to Settings were done thanks to printing my MEDIA_ROOT in the console. I changed the syntax and the direction of a slash (blog\media). I also deleted the context processor shown above in my TEMPLATES options.
Here's what works for me:
models.py
thumbnail = models.ImageField(default='img/default.png', upload_to='img', blank=True, null=True)
urls.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'blog\media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)
Template tag
<img class="card-image mr-3" src="{{ post.thumbnail.url }}" alt="Generic placeholder image">

Images not loading Django website

Images on my django website are not loading for some reason
This is my models.py
thumbnail = models.ImageField(upload_to='images/',blank=True)
This is my settings.py lines
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
if DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'static/static-only')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/static'),
)
This is my views.py
class BlogIndex(generic.ListView):
queryset = models.Entry.objects.published()
template_name = "index.html"
paginate_by = 5
In url.py
if settings.DEBUG:
urlpatterns +=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
In index.html i did this
<img class="img-rounded" src = "{{object.thumbnail.url}}"/>
pip freeze
Django==1.11.2
django-ckeditor==5.2.2
django-crispy-forms==1.6.1
django-markdown==0.8.4
django-pagedown==0.1.3
Markdown==2.6.8
olefile==0.44
Pillow==4.1.1
The Images are getting saved in the static/media/images directory
But the images are not loading in the web page...
When i try to right-click and view the image It shows this error SCREEN SHOT
Other objects are working perfectly.. Only the images aren't loading
You need the media url in the src:
<img class="img-rounded" src = "{{object.thumbnail.url}}"/>
should be:
<img class="img-rounded" src = "{{MEDIA_URL}}{{object.thumbnail.url}}"/>
or something similar
<img class="img-rounded" src = "/static/media/uploads/{{object.thumbnail.url}}"/>
The Issue is fixed, (Got assistance from a facebook group)
The issue was a url pattern in the views.py
The screen shot that I put had a line
Raised by : blog.views.Blogdetail
Apparently i had a urlpattern
url(r'^(?P<slug>\S+)/$', views.BlogDetail.as_view(), name='entry_detail'),
My pattern for blog detail view has match \S+ - so any string of characters that has no spaces in
Which will match pretty much any pattern that hasn't matched previously and any other url pattern which are below this particular url will not be accessed
Changed the url pattern to the following and I was good to go
url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(),name='entry_detail'),
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
in this model you can see Overwrite of exist IMG, return img as base string:
models.py
from django.db import models
from django.core.files.storage import FileSystemStorage
from base64 import b64encode, b64decode
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name, max_length=700):
if self.exists(name):
os.remove(os.path.join(settings.MEDIA_ROOT, name))
return name
def upload_location(instance, filename):
return os.path.join('defaultfolder', instance.phone, filename)
class ImgModel(models.Model):
name= models.CharField(max_length=100)
img = models.FileField(storage=OverwriteStorage(),
upload_to=phone_upload_location,
null=True,
blank=True,
max_length=700)
def image_to_base64(self, model_picture_path):
if model_picture_path:
try:
with open(model_picture_path.path, "rb") as imageFile:
str = b64encode(imageFile.read())
return "data:image/jpg;base64,%s" % str.decode()
except IOError:
return model_picture_path.url
else:
return None
.html
<img src="{{ MEDIA_URL }}foo.jpg">
I faced this issue and I tried lot of things but imges wont load then I tried out a simple trick but this did the job. What I did was, in my settings.py file, I included the STATIC_DIR varaible just after BASE_DIR. Below is my settings.py file
Settings.py
#Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,"static")
#Other content
STATIC_URL = '/static/'
STATICFILES_DIRS=(
STATIC_DIR,
)
Check this out maybe this will help!
How to fix images answer is
mention above index.html
{% static 'travello/images/' as baseUrl %}
path
then

Image in Django admin is generated with wrong URL

I'm trying out Django and ran into the following problem:
I have a model class Property which has various attributes amongst which is an image. The image property is defined as:
image = models.FileField(
upload_to = 'properties',
default = 'properties/house.jpeg')
The directory properties is a sub directory of images which is defined in settings.py as:
MEDIA_ROOT = '/Users/.../Development/pms/images/'
MEDIA_URL = 'http://localhost:8000/images/'
Derived from similar posts on SO regarding this topic, I added the following to my Property model:
def admin_image(self):
return '<img src="images/%s" width="100"/>' % self.image
admin_image.allow_tags = True
I then added admin_image() as a property to the list display:
list_display = ('admin_image', ...)
When I check the URL for the image in the admin application, I get the following:
http://127.0.0.1:8000/admin/properties/property/images/properties/house.jpeg/
This generates a 404 as the URL is generated incorrectly. Firstly the path is incorrect and secondly there's a trailing / at the end of the URL.
I'm obviously missing something... What do I do wrong?
EDIT:
Thanks to #okm for the various pointers. I did the following:
Added the following to my urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
... original url patterns ...
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^images/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
Then in settings.py set MEDIA_ROOT:
absolute/filesystem/path/to/images
And in settings.py set MEDIA_URL:
/images/
According to the doc & here, try self.image.url instead of '...' % self.image