Django won't serve an image from MEDIA_URL - python

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

Related

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.

Images are not loading into the home page from static

I dont know why image is not display on the home page. Please see my code. I am on windows running python3 and Django 2.1. Is there any setting need to be done in files somewhere in Django folders like any config file? Please guide
Settting File:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
URL file:
from django.contrib import admin
from django.urls import path
from django.urls import include, path
import jobs.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home', jobs.views.home, name='home'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Model File
from django.db import models
# Create your models here.
class Job(models.Model):
image = models.ImageField(upload_to='images/')
summary = models.CharField(max_length=300)
Home Page File
<html lang="en">
{% load static %}
<head>
And where I want to show the image is end of a div
<img src="{% static '9.jpg' %}" height="200"></img>
</div>
</section>
In settings.py you will need to add settings for MEDIA_ROOT and MEDIA_URL. That is what the ImageFile upload_to relates to. See the documentation here.
You can then for example reference the image in the home page template as follows:
<img src="{{ '/media/images/9.jpg' }}">

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

Display images form the admin panel

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

Media Files not Displaying in Django

I am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for gallery images with a filefield), the image is stored in /media/images correctly. I have my media settings set in settings.py as follows:
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
import gallery.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('gallery.urls')),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Gallery urls.py:
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^', views.homepage, name = 'home'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Gallery views.py:
def homepage(request):
texts = Sitetext.objects.all()
gal = Galleryimg.objects.all()
gal.order_by('position')
return render(request,'index.html', {"text1":texts[0].text,"text2":texts[1].text,"text3":texts[2].text,"text4":texts[3].text,"title1":texts[0].title,"title2":texts[1].title,"title3":texts[2].title,"title4":texts[3].title,"gallery":gal})
And then this is the part of the template code that accesses the image:
{% for g in gallery %}
<div class="col-md-3 col-sm-4 col-xs-6">
<img class="img-responsive" src="g.imgfile.url" />
</div>
{% endfor %}
When I create a gallery image, a broken image pops up, but the image is not accessed correctly.
I do this and I am able to serve media files from the Django development server:
urlpatterns += [
url(r'^media/(?P<path>.*)$', django.views.static.serve, {
'document_root': settings.MEDIA_ROOT}),]
It should be enough to include that just in the project urls.py.
The issue with yours could be that your media URL entry in urls.py is not correct. You seem to be not matching the actual URL of the media file, which is probably something like /media/something.png. You seem to be just qualifying on /media/. I also think your regex should be ^media/, not /media/.
Remove the static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) part, from your gallery.urls file.
Replace src="g.imgfile.url" with src="{{ g.imgfile.url }}".
Aside question: Why do you pass this big dictionary ({"text1":texts[0].text,...) to your template? It is error prone and bad practice. You should just pass 'texts': texts and inside your template iterate over them with a {% for text in texts %} forloop. So, the render method should be something like render(request, 'index.html', {'texts': texts, 'gallery': gal}).

Categories

Resources