unable to display images from model usingo django - python

in settings.py
MEDIA_ROOT = os.path.join(BASE_DIR,'pictures')
MEDIA_URL = '/pictures/'
in models.py
class Campaign(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
# this is many to one relationship, on_deleting user, profile will also be deleted
campaign_title = models.CharField(max_length=200, blank=True)
campaign_image = models.ImageField(default="default_campaign.png",upload_to="campaign_pictures")
in views.py
def landing_page(request):
campaigns = Campaign.objects.all().order_by('-id')
print(campaigns)
return render(request, 'core/landing_page.html',{'campaigns':campaigns})
in landing_page.html
{% for campaign in campaigns %}
<img src="{{campaign.campaign_image.url}}">
{% endfor %}
issue
if file name is abc xyz.jpg, it gets saved into /pictures/campaign_pictures as abc_xyz.jpg
in html template, the src of image should be '/pictures/campaign_pictures/abc_xyz.jpg' but it shows only '/pictures/abc%20xyz.jpg'

I think you missed in urls.py file
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Also correct it with
campaign_image = models.ImageField(default="default_campaign.png",upload_to="campaign_pictures/")

You can define the 'upload_to' as a callable function and use the os.path to join the directory name with the media url.
Your field will call a function which will provide the path.
campaign_image = models.ImageField(default="default_campaign.png",upload_to=get_campaign_path)
and define your function like this
import os
def get_campaign_path(instance, filename):
return os.path.join('campaign_pictures/',filename)
Reference:
https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.FileField.upload_to

Related

Django ImageField Uploaded to Different Path than Reported by url property?

I'd like to allow users to upload profile pictures and then to display them.
Here's my model.py:
from django.db.models import CharField, ImageField, Model
class Eater(Model):
name = CharField(max_length = 30)
image = ImageField(upload_to = 'images/eaters/')
def __str__(self):
return str(self.name)
Here's my urls.py:
from django.conf import settings # settings is an object, not a module, so you can't import from it. :(
from django.conf.urls.static import static
from django.urls import path
from .views import EaterView, IndexView, post, sudo
app_name = 'socialfeedia'
urlpatterns = [
path('', IndexView.as_view(), name = 'index')
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) # Static returns a list of path, not a path itself.
This is at the end of my settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR.joinpath('media/')
Here's a line out of my index.html:
<img class="post-profile-picture" src="{{ post.eater.image.url }}" alt="?"/>
I successfully uploaded a file into this field - it got stored at:
mysite/media/images/eaters/test_picture_64.jpg
The image loads successfully if I visit it here:
http://127.0.0.1:8000/socialfeedia/media/images/eaters/test_picture_64.jpg
However, the img that shows up in my generated file is this:
<img class="post-profile-picture" src="/media/images/eaters/test_picture_64.jpg" alt="?">
This file doesn't resolve - I just see a ? (the alt) instead. Should I be using something else to get the correct path to the file instead? Something like this maybe?
{% media post.eater.name %}
(Except no such thing as media exists as far as I can tell...)
It should be including socialfeedia/ (the app name) at the start of the url but it isn't... it doesn't seem very much like what I've seen of Django so far to expect me to manually hardcode that in...
my guess is to move
+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) # Static returns a list of path, not a path itself.
from urls.py file of your app socialfeedia to the global urls.py file under the project package and don't forget to set the namespace socialfeedia in the corresponding urls:
from django.conf import settings
from django.urls import path, include
from django.contrib import admin
[..]
urlpatterns = [
[..]
path('socialfeedia/', include('socialfeedia.urls', namespace='socialfeedia')), # HERE
path('admin/', admin.site.urls), # Admin Area
]
# DEBUG = True
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
let me know if this helps you.
Adding {% get_media_prefix %} at the beginning of src worked for me but I'm pretty sure it's not the right solution.
<img class="post-profile-picture" src="{% get_media_prefix %}{{ post.eater.image.url }}" alt="?"/>

DJANGO - upload image stored locally to model ImageField attribute

I have my images downloaded inside the subroot images in my media folder and I'm trying to generate new models which will contain the photo inside the images folder. This is what my model and my view look like:
class Post(models.Model):
...
image = models.ImageField(upload_to="images", blank=True, null=True)
def generate_posts(request):
for i in range(20):
title_ = f'title{i}'
body_ = f'text for post number : {i}'
author_ = f'author{i}'
network_ = randomize_social()
post = Post(title=title_, body=body_, author=author_, social_network=network_)
if randomize_picture():
post.image.save("logo.png", File("images/svante.jpg"), save=True)
else:
post.image = None
post.save()
areGenerated = True
return render(request, "posts/generate_posts.html", {'areGenerated':areGenerated})
The logo.png file is created inside the images folder, but it's blank, 0kb size and when I follow the /generateposts url, I receive this error message:
AttributeError at /generateposts
'str' object has no attribute 'read'
What can I do to solve this problem?
Did you make changes to your settings file? you need to make changes such as
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and don't forget to add these to your urls:
from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Image not showing in Django [duplicate]

This question already has answers here:
How to display images from model in Django?
(3 answers)
Closed 5 years ago.
I don't know why the images aren't showing in Django. Something to do with the media root?
settings code
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')'
models code
from django.db import models
from django.core.urlresolvers import reverse
Create your models here.
class Post(models.Model):
## Post Properties
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
summary = models.CharField(max_length=255)
content = models.TextField()
published = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='img',default='media/placeholder.png')
class Meta:
ordering = ['-created']
def __unicode__(self):
return u'%s'% self.title
def get_absolute_url(self):
return reverse('blog.views.post', args=[self.slug])
I didn't add a url for the picture, could that be a problem?
urls
urlpatterns = [
url(r'^post/(.*)', blogViews.post),
url(r'^about/$', blogViews.about),
url(r'^$', blogViews.index),
url(r'^admin/', admin.site.urls),
index.html code
<img src="{{post.image}}">
<p> {{post.image}} </p>
**Views.py **
from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpResponse
from .models import Post
# Create your views here.
def index(request):
posts = Post.objects.all()
return render(request, 'index.html', {'posts': posts})
def post(request, slug):
return render_to_response('post.html', {
'post': get_object_or_404(Post,slug=slug)
})
def about(request):
return render(request, 'about.html', {})
In the website all that shows is a blank picture as well as the file name (either 'placeholder.png' which is the default or img/... which I uploaded through admin)
Edit:
This was marked as a duplicate, I saw that post and tried to change my code to reflect that code but it wasn't working. Figured it would be better to post my own.
Thanks in advance, first question on this site!
Try this,
<img src="{{post.image.url}}">
Also, add in your urls.py,
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
For learning more about serving static, refer the documentation here...

Django rest framework api - image url is not returning properly

I am facing problem in returned image url, which is not proper.
My return image url is "http://127.0.0.1:8000/showimage/6/E%3A/workspace/tutorial_2/media/Capture1.PNG"
But i need
"http://127.0.0.1:8000/media/Capture1.PNG"
When i click on image_url then image open in new browser tab
But currently its shown error:
view.py
from showimage.models import ShowImage
from showimage.serializers import ShowImageSerializer
from rest_framework import generics
# Create your views here.
class ShowImageList(generics.ListCreateAPIView):
queryset = ShowImage.objects.all()
serializer_class = ShowImageSerializer
class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = ShowImage.objects.all()
serializer_class = ShowImageSerializer
model.py
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
# Create your models here.
class ShowImage(models.Model):
image_name = models.CharField(max_length=255)
image_url = models.ImageField(upload_to=settings.MEDIA)
serializer.py
from rest_framework import serializers
from showimage.models import ShowImage
class ShowImageSerializer (serializers.ModelSerializer):
class Meta:
model = ShowImage
fields = ('id', 'image_name', 'image_url')
settings.py
MEDIA=os.path.join(BASE_DIR, "media")
urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
I am new in python and also in django-rest-framework.
Please also tell me how we extend models or serialize class
You might want to try this in your settings:
MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, "media")
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in your models:
class ShowImage(models.Model):
image_name = models.CharField(max_length=255)
image_url = models.ImageField(upload_to="") # or upload_to="images", which would result in your images being at "http://127.0.0.1:8000/media/images/Capture1.PNG"
Finally, i solve this road block with the help of
#Remi
Thanks #Remi
But some other change i do so that i elaborate solution and fix this issue.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, "media")
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your code seems correct except one thing you have passed settings.MEDIA in uploads image. you don't need to pass settings.MEDIA in uploads.
try this
image_url = models.ImageField(upload_to='Dir_name')
Dir_name will create when you'll run script.

Django 1.6: Can't display a picture from a model in template.

I'm trying to display picture from the model, but it doesn't show anything. I uploaded the image using the admin panel and I can see the picture in the uploads folder. But when I try to display it in the templates, it doesn't show anything. I don't have anything is the settings file related to it such as media root, media url, because I'm not sure what to put for them
Here is the template where I'm trying to show it
<img src="{% url 'getDocProfilePicture' doctor.id %}">
Here is the models.py
class Doctor(models.Model):
name = models.CharField(max_length=30)
specialization = models.ForeignKey(Specialization)
clinic = models.ForeignKey(Clinic)
seekers = models.ManyToManyField(DoctorSeeker, through='Review')
language = models.ManyToManyField(Language)
education1 = models.CharField(max_length=100)
education2 = models.CharField(max_length=100, null = True)
gender_choices = ( ('M', 'Male'), ('F','Female'),)
gender = models.CharField(max_length=5, choices = gender_choices, null=True)
profile_pic = models.ImageField(upload_to='uploads/', null=True)
statement = models.TextField(null=True)
affiliation = models.CharField(max_length=100, null = True)
here is views.py
def getDocProfilePicture(request, id):
d = Doctor.objects.get(id=doctor_id)
return HttpResponse(d.profile_pic.read())
Urls.py
url(r'^getDocProfileicture/ (?P<id>\d+)/$', views.getDocProfilePicture, name='getDocProfilePicture'),
You no need such complex logic for display image.
{{ doctor.profile_pic.url }}
You don't need to use url template tag here and have a special separate view.
Just get the url from the ImageField:
<img src="{{ MEDIA_URL }}/{{ doctor.profile_pic.url }} ">
I know this question is old but I had the same problem and this solved in my case:
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_DIR = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")
MEDIA_URL = '/media/'
urls.py
Then, my urls.py was missing this line of code to discover the /media/ folder and show the content:
urlpatterns += staticfiles_urlpatterns()
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}, name="media_url"),
) + urlpatterns
Hope it can help someone.

Categories