Display images form the admin panel - python

I want to make a app in which admin upload a image on admin panel and it display on the template. I'm know there are some question related to this but I tried all of them but still can't display image.
Django version: 2.1.4
python version: 3.6.7
In setting.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'image')
In model.py
from django.db import models
class ImageModel(models.Model):
caption = models.CharField(max_length=40)
image = models.ImageField(upload_to='uploadImage', blank=True)
def __str__(self):
return self.caption
In view.py
from django.shortcuts import render
from .models import ImageModel
def image_page(request):
images = ImageModel.objects.all()
return render(request, 'input/hello.html', {'image':images})
In urls.py
from django.contrib import admin
from django.urls import path, include
from image import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.image_page),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In imageShow.html
<img src="{{ ImageModel.image.url }}" alt="image" />
doing this show me a broken image and some time the full url of the image(where is the image is saved) What I'm doing wrong. I try to print variable images in views.py and it print my caption("image") so it means that it sending caption in img tag not the image itself? should I make a new class of ImageUpload?
thanks in advance

You need to iterate through ImageModel queryset (which you are sending as context via variable image) and show the image in template, like this:
{% for im in image %}
<img src="{{ im.image.url }}" alt="image" />
{% endfor %}

Related

Django won't serve an image from MEDIA_URL

A beginner building a personal blog. Got a simple model with an ImageField. No matter what I try the Django won't serve an image.
Judging by the console output in the Dev Tools it is looking for an image in the wrong folder. I don't know how to fix that. I tried setting up MEDIA_URL, MEDIA_ROOT and adding a urlpattern like it's being suggest here and here
I have uploaded the picture via admin panel, its location is media/images/stockmarket.jpg. But for some reason the server is looking for an image here /blog/images/stockmarket.jpg
Project name: 'wikb', 'blog' is an App:
project_file_system
models.py
from django.db import models
class Post(models.Model):
title = models.CharField('Post Title', max_length=200)
preview = models.CharField('Post Preview', max_length=400)
thumbnail = models.ImageField('Post Picture', upload_to='images/', blank=True)
view.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
def home(request):
all_posts = Post.objects.all()
hero_post = all_posts[0]
context = {'hero_post': hero_post, 'all_posts': all_posts}
return render(request, 'blog/home.html', context=context)
HTML
<div class="hero">
<a href="#" class="hero__link" style="background-image: url({{hero_post.thumbnail}})">
<article class="hero__article">
<h2 class="hero__heading">{{hero_post.title}}</h2>
<p class="hero__preview">{{hero_post.preview}}</p>
</article>
</a>
</div>
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
Global urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('blog/', include('blog.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It's my first Django project, please explain like I'm 5.
Update: I forgot to add .url when I referenced an object in templates.
In templates, you'll want to use .url to get the real URL of a FieldFile (the file contained by a FileField or ImageField):
<a href="#" class="hero__link" style="background-image: url({{ hero_post.thumbnail.url }})">

I can upload images to specific directory but can't view them in template (Page not found (404))

I am trying to add upload image to admin form in my Django project I found on GitHub. I can upload image to folder my_app(catalog)/media/images/image.png but when I try to call it in the template I can only see that image icon that appears when there is no picture.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'catalog/media')
model.py
class Book(models.Model):
image = models.ImageField(blank=True, null = True, upload_to='images')
book_detail.html
img src="{{ book.image.url}}" width="250"
views.py
class BookDetailView(generic.DetailView):
model = Book
urls.py
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', views.index, name='index'),
path('book/create/', views.BookCreate.as_view(), name='book_create'),
path('books/', views.BookListView.as_view(), name='books'),
path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is how it looks like (I print {{ book.image }} next to the picture (images/screenshot_4.png):
This is the error I get:
You may have dropped a ']' at the end of your urlpatterns or maybe I am mistaken
Ok I found out after spending way to much time on it.
img src="{{ book.image.url}}" width="250" line in template should look like
img src="../media/{{ book.image.url}}" width="250".
Hope this helps someone with the same problem.

Django Image should be displayed but isnt

I don't understand why the image isn't being displayed,
HTML
<div class="features-icons-item mx-auto mb-5 mb-lg-0 mb-lg-3">
<div class="features-icons-icon d-flex">
<img src="{{ x.pic.url }}">
</div>
model
class Item(models.Model):
title = models.CharField(max_length=200, default='item name...')
desc = models.TextField(default='Description....')
pic = models.ImageField(default='default.png', upload_to='item_pics')
views
def index(request):
itemList = Item.objects.all()
return render(request, 'main/items.html', {'itemlist': itemList})
settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I think you have not added the media url in urlpatterns.
Change the url.py in project as follows:
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)
Refer the django documentation for more Explanations Django media files

Unable to render Images in template

I have tried so many things to fix this issue but still I can't get it to work.
I can't get my MEDIA images to render correctly in the template, although the url in the page source is the correct absolute path, still the images won't appear.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
import os
class Contact(models.Model):
user = models.OneToOneField(User,null=True)
website = models.URLField(blank=True,null=True)
db = models.ImageField(upload_to=settings.MEDIA_ROOT)
def __unicode__(self) :
return unicode(self.user) or u''
views.py
from django.shortcuts import render
from .models import Contact
from django.contrib.auth.models import User
def user_page(request,user_name):
try :
user = User.objects.get(username=user_name)
except User.DoesNotExists :
return (request,'main.html')
return render(request,'main/user_page.html',{'user':user})
urls.py
from django.conf.urls import url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import views
urlpatterns = [
url(r'^(?P<user_name>\w+)/$',views.user_page , name = 'main_page'),
]
if settings.DEBUG :
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
main/user_page.html
{% load staticfiles %}
<h1>{{user.username}}</h1>
<img src="{{user.contact.db.url}}" alt="My image"/>
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATIC_DIR = (
os.path.join(PROJECT_DIR,'static'),
)
MEDIA_ROOT =os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Thanks and sorry for the bad english
db = models.ImageField(upload_to=settings.MEDIA_ROOT)
Is wrong. Quote form documentation:
FileField.upload_to
A local filesystem path that will be
appended to your MEDIA_ROOT setting to determine the value of the url
attribute.
Thus:
db = models.ImageField(upload_to="foo")
Will upload to MEDIA_ROOT + "foo".
Try doing this instead:
models.py:
class Contact(models.Model):
user = models.OneToOneField(User,null=True)
website = models.URLField(blank=True,null=True)
db = models.ImageField(upload_to=some_folder_here)
def __unicode__(self) :
return unicode(self.user) or u''
def get_db_url(self):
return "{}{}".format(settings.MEDIA_URL, self.db)
views.py:
def user_page(request,user_name):
try :
user = User.objects.get(username=user_name)
photo = Contact.objects.filter(user=user)
except User.DoesNotExists :
return (request,'main.html')
context = {
'user': user',
'photo': photo
}
return render(request,'main/user_page.html', context)
html:
{% load staticfiles %}
<img src="{{ photo.get_db_url }}" alt="My image" />

Django 1.6 image upload and media path

So I have a project on webfaction where I need to create two different environments, one to server django and one to server static files.
So when I upload an image from admin panel I can see the image is placed in root i defined but with full path. When i return the image in my view i get my domain.com/full/media/root/path/imagename
this generates a broken link - when i go to mydomain.com/uploads/image_name, I can see image file is there however my link is pointing to full path rather than root_url,
Could you please help me with this? I really dont understand how i can correct this image link in my view
<img src="{{ MEDIA_URL }}{{ mymodel.my_image }}" alt="{{ name }}" width="150" height="200" />
I do understand there are so many subjects similar to this here however none of them could direct me correctly in regards to how to hide or change path root to "uploads"
I have which works fine in my admin
class Movie(models.Model):
name = models.CharField(max_length=50)
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join( '/home/user/webapps/project/uploads/' , filename)
my_image = models.ImageField(upload_to = get_file_path, null=True, blank=True)
def __unicode__(self):
return self.name
In my settings:
MEDIA_ROOT = '/home/user/webapps/project/uploads/'
MEDIA_URL = '/uploads/'
and project url:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Thank you all in advance
At first for your model you should create an image field and in there you should define where you want to upload your image:
class mymodel(models.Model):
name = models.CharField(max_length=50)
my_image = models.ImageField(blank=True, null=True,upload_to='/home/user/webapps/project/uploads/')
After that in your template when you want to show your image after getting your model object from your database try this:
<img src="{{ mymodel.my_image.url }}" alt="{{ mymodel.name }}" width="150" height="200" />
You can use:
{{ mymodel.my_image.url }}

Categories

Resources