Django Image should be displayed but isnt - python

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

Related

How to show model images in Django?

I have such models.py file
class Product(models.Model):
CATEGORIES = {
('Computer', 'Комп\'ютер'),
('Smartphone', 'Смартфон')
}
photo = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=128, blank=False)
description = models.CharField(max_length=5000, blank=False)
price = models.PositiveIntegerField(blank=False)
category = models.CharField(max_length=30, choices=CATEGORIES)
count = models.PositiveIntegerField(blank=False)
In settings.py i DON'T have media variables/dirs
Also i try to show images in such way
{% extends 'base.html' %}
{% block title %}Каталог{% endblock %}
{% block content %}
{% for i in products %}
<img src="{ static i.photo.url }">
{{i.title}}
{% endfor %}
{% endblock %}
Result:
I add my model objects in Django Admin
please see below configuration, have you done?
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# urls/path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
your HTML file
{% if i.photo %}
<img src="{{ i.photo.url }}">
{% endif %}
You don't need the static tag.
<img src="{{ i.photo.url }}">
You can add like this.
and run the collectstatic command to
<img src="{% static '/logo.png' %}"/>
python manage.py collectstatic
In settings.py i DON'T have media variables/dirs
you have to set MEDIA_ROOT and MEDIA_URL in settings.py and set the URL of each in urls.py because by default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you’re using these defaults.
check the official doc.
step - 1
configure media and static files like this
add this in your settings.py
STATIC_ROOT = BASE_DIR / 'static_cdn'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
and add this in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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

Django not serving images based on ImageFiled

I'm having issues serving images based on the ImageField in Django.
models.py part looks like that:
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
category = models.ManyToManyField(Category)
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
main_image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='main_image')
images = models.ManyToManyField(Image, related_name='images')
class Image(models.Model):
name = models.CharField(max_length=32)
picture = models.ImageField(upload_to='pictures/', blank=True)
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
taken = models.DateTimeField(blank=True, null=True)
uploaded = models.DateTimeField(default=timezone.now)
def __unicode__(self):
return self.name
settings.py contains the MEDIA_URL and MEDIA_ROOT:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also included what I've found in other SO topics in the urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.contrib.staticfiles.urls import static, staticfiles_urlpatterns
from django.conf import settings
from markdownx import urls as markdownx
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
url(r'^markdownx/', include('markdownx.urls')),
] + staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In the end I put it in the html template like that:
{% extends 'blog/base.html' %}
{% block leftcolumn %}
{% for post in posts %}
<div class="leftcolumn">
<div class="card" style="max-width: 100%">
<h2>{{ post.title }}</h2>
<h5>published: {{ post.published_date }}, by: {{ post.author }}</h5>
<div><img src="{{ post.main_image.url }}"></div>
<p>{{ post.byline }}</p>
</div>
</div>
{% endfor %}
{% endblock %}
But the image is not shown..
I can see the image if I go to the url host:8000/media/pictures/test_photo.jpgand in general I can display images on the page (e.g. within django-markdownx field) but not through ImageField url.
Any ideas what's wrong here?
This line:
<div><img src="{{ post.main_image.url }}"></div>
should be:
<div><img src="{{ post.main_image.picture.url }}"></div>
The reason is your model Image does not have an url method. The method belongs to the ImageField, in this case picture.

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

Displaying images Django models

I am building my first website after finishing the how to tango with django tutorial and i am trying to add some images using the template language, but instead i get only little blue question mark icons
models.py
from django.db import models
class Galery(models.Model):
title = models.CharField(max_length = 120)
def __unicode__(self):
return self.title
class Image(models.Model):
galery = models.ForeignKey(Galery)
name = models.CharField(max_length = 50, unique = True)
picture = models.ImageField(upload_to='media')
description = models.CharField(max_length = 500)
materials = models.CharField(max_length = 150)
def __unicode__(self):
return self.name
galery.html
{%extends 'home/base.html'%}
{%load static%}
{%block body%}
<div class="col-lg-12">
<h1 class="page-header">My Projects</h1>
</div>
{%if image%}
{%for n in image%}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="">
<img class="img-responsive" src="{% static 'media/{{n.image.url}}' %}">
</a>
</div>
{%endfor%}
{%endif%}
{%endblock%}
settings.py (part)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
MEDIA_ROOT = os.path.join(PROJECT_PATH,'media')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
STATICFILES_DIRS = (
STATIC_PATH,
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
EDIT: forgot to mention that i uploaded some images from the admin
EDIT2: in my urls.py i have
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
Django by default does not serve user-uploaded images. Set it up by adding the following URL conf:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is only for development. In production you will need to serve your files in a more scalable way (either directly from the HTTP server or even better, from a file storage service such as S3, or a CDN.)
For more info: https://docs.djangoproject.com/en/1.6/howto/static-files/#serving-files-uploaded-by-a-user-during-development

Categories

Resources