images are not showing in django - python

hi when i am saving images from my admin they are saved in project directory like this images/images/myimg.jpg.. but when i am trying to display them in my template like this
<img src="{{About.image.url}}" alt="profile photo">
the image do not displays.. when i inspect the page in chrome... it shows image source unknown..
<img src="(unknown)" alt="profile photo">
please see the files ..
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS =[
os.path.join(BASE_DIR,'portfolio/static')
]
STATIC_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'images')
project 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('admin/', admin.site.urls),
path('home/', include("home.urls")),
path('blog/', include("blog.urls")),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT )
the model having image is inside a app named 'home'
models.py of home app
from django.db import models
import datetime
# Create your models here.
class About(models.Model):
image = models.ImageField(upload_to = 'images')
desc = models.TextField()
home/views.py
from django.shortcuts import render
from home.models import *
from django.views.generic import ListView
# Create your views here.
def index(request):
abt = About.objects.all()
return render(request,'home/index.html',{'abt': abt.first()})
def Experience(request):
Exp = Experience.objects.all()
return render(request,'home/Experience.html',{'Exp': Exp})
class MyView(ListView):
context_object_name = 'name'
template_name = 'home/index.html'
queryset = About.objects.all()
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['Experience'] = Experience.objects.all()
context['Education'] = Education.objects.all()
context['Award'] = Award.objects.all()
context['Membership'] = Membership.objects.all()
context['About'] = self.queryset
return context

if about you're passing queryset so try looping them and accessing each image
{% for data in About %}
<img src="{{data.image.url}}" alt="profile photo">
{% endfor %}

Related

Imagefield in Django HTML Variable

I'm new to Django and trying to create a website with uploading image via Django Admin.
I'm trying to view image uploaded in Imagefield in my HTML.
But i just can't get the image working right.
Banner.objects.all() doesn't seems able to get all the image file located in media folder.
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('admin/', admin.site.urls),
path('', include('blog.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from django.utils import timezone
from django.contrib.auth.models import User
from PIL import Image
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now) #auto_now=True //auto date
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Banner(models.Model):
title = models.CharField(max_length=100)
images = models.ImageField(upload_to='images',null=True,blank=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import(
ListView,
DetailView
)
from .models import *
# Create your views here.
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted'] #arrange date posted with latest on top
paginate_by = 6
def Banner_view(request):
banner = Banner.objects.all()
return render(request, 'blog/home.html',{'banner':banner})
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
#uploaded file in base directory "media"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
home.html
{% for b in banner %}
<div>
<img src="{{ b.images.url }}">
</div>
{% endfor %}
you should have write this way
you should use / for path detect
images = models.ImageField(upload_to='images/', null=True,blank=True)

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

DJANGO MEDIA_URL returns to same page instead of showing image

There are lots of answer on how to upload media files, what are the correct configuration and how to serve it on our application.
But my project seems to work nothing.
The aim is simple: User uploads an image. Django displays it on.
models.py
class UploadImageModel(models.Model):
image = models.FileField()
title = models.CharField(max_length=100, null=True, blank=True)
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'', include("Image.urls")),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import render
from django.views import View
from .forms import UploadImageModelForm
from .models import UploadImageModel
# Create your views here.
class UploadImage(View):
def get(self, request, *args, **kwargs):
form = UploadImageModelForm()
context = {
"form":form,
}
return render(request, "index.html", context)
def post(self, request, *args, **kwargs):
form = UploadImageModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.title = str(instance.image)
instance.save()
context = {
"form":form,
"instance":instance,
}
return render(request, "index.html", context)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "Static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "Media")
index.html
{% if instance.image %}
<img src="{{instance.image.url}}" alt="Image"/>
{% endif %}
ERROR: After uploading an image named <something>.jpg, if I visit, 127.0.0.1:8000/media/1.jpeg, browser does not displays image, instead it shows index.html page.
SO how to serve this media file correctly?
This line is a catch-all for every URL:
url(r'', include("Image.urls")),
Without seeing the contents of Image/urls.py I can only suggest replacing that line with an explicit pattern that executes the index view, such as:
url(r'^$', my_index_view),

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" />

ImageField class in django 1.8 not displaying image in the template

According to the code the image should be displayed on the index.html template but there seems to be some problem with the img src
My models.py
from django.db import models
class Rockinfo(models.Model):
rock_name = models.CharField(max_length=200,default="ac/dc")
rock_img = models.ImageField(upload_to="%Y/%m/%d",default="1992/08/92")
rank = models.IntegerField(default=0)
def __str__(self):
return self.rock_name
My admin.py
from django.contrib import admin
from .models import Rockinfo, Rockvids
class ChoiceInline(admin.TabularInline):
model = Rockvids
extra = 10
class RockinfoAdmin(admin.ModelAdmin):
fieldsets = [
('The Fucking Band', {'fields': ['rock_name']}),
('Image', {'fields': ['rock_img']}),
]
inlines = [ChoiceInline]
list_display = ('rock_name', 'rock_img')
list_filter = ['rank']
search_fields = ['rock_name']
admin.site.register(Rockinfo, RockinfoAdmin)
my application's urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
]
My project's models.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^rockinglist/', include('rockinglist.urls', namespace="rockinglist")),
url(r'^admin/', include(admin.site.urls)),
]
My views.py file
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Rockvids, Rockinfo
class IndexView(generic.ListView):
template_name = 'rockinglist/index.html'
context_object_name = 'latest_rockinfo_list'
def get_queryset(self):
return Rockinfo.objects.order_by('-rank')[:5]
The index.html file
{% if latest_rockinfo_list %}
<ul>
{% for rockinfo in latest_rockinfo_list %}
<h1>{{ rockinfo.rock_name }}</a></li>
<img src="img\{{ rockinfo.rock_img }}" alt="ac/dc">
{% endfor %}
</ul>
{% else %}
<p>No</p>
{% endif %}
I think the problem is with the root of the image.Somehow django cannot reach the images.I want to display the rock_name along with the associated rock_img. Can someone help me figure this out.Thanks in advance.
In your project's urls.py, add this:
# your other imports here ...
# ...
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLs ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In your settings.py file, make sure you have this:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
In your templates:
<img src="{{ rockinfo.rock_img.url }}" alt="ac/dc">
Note: If BASE_DIR is not defined in your settings, put this on top of your settings file:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
First of all check if MEDIA_URL is provided in you settings. Django doesn't server media during development so you have to have the following in your project's 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)
after this you can access your image in template with
{{ rockinfo.rock_img.url }}

Categories

Resources