Display image in template with Django - python

I am trying to display images into articles in my blog project built with Django. Here is the related code:
settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "/media/"
urls.py (project):
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py:
class Article(models.Model):
title = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
author = models.CharField(max_length=80)
text = models.TextField(null=True)
date = models.DateTimeField(auto_now_add=True, auto_now=False,
verbose_name="Date de parution")
image1 = models.ImageField()
image2 = models.ImageField()
image3 = models.ImageField()
def __str__(self):
return self.titre
views.py:
def article(request, id, slug):
article = get_object_or_404(Article, id=id, slug=slug)
return render(request, 'blog/post.html', {'article': article})
post.html:
<img src="{{ article.image1.url }}"/>
<img src="{{ article.image2.url }}"/>
<img src="{{ article.image3.url }}"/>
However, it does not work. Images do not appear. Any suggestions ?

There shouldn't be any forward slashes before or after media, it should simply be .join(BASE_DIR, 'media'). also you don't need to add upload_to('media') because the root is media. You are not advised to add images in media root, you should create an img folder inside media folder, and then add upload_to('img/') in your imagefield.
Regarding inserting image preview inside a textbox/textfield, yes it is possible, but it should be a separate question, although I think there are many identical questions on it.

Related

Django - Show multiple images

I'm trying to show all the image correlated to a chapter.
I cannot figure out what is wrong, base on what I found online it should work, but no images are display.
Only the outer div is coming out on html source.
By debugging the template I also notice that the for loop is taking all the chapters in the DB, not only the chapter I selected.
I think I need to restrict the ChapDetail view query somehow.
Can someone advise me on this two issue?
model.py
def image_dir_path(instance, filename):
book = instance.chap.book.slug
chapter = instance.chap.slug
return os.path.join(book, chapter, str(uuid.uuid4().hex))
class Chapter(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
default=settings.AUTH_USER_MODEL
)
book = models.ForeignKey(
Book,
related_name='chapters',
on_delete=models.CASCADE,
default=''
)
title = models.CharField(max_length=130, unique=True)
slug = models.SlugField(max_length=150, blank=True)
created_at = models.DateField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('chap_detail')
class ShowImages(models.Model):
chapter =models.ForeignKey(
Chapter,
on_delete=models.CASCADE,
default='',
related_name="pics"
)
picture = models.FileField(upload_to=image_dir_path, default='')
def __str__(self):
return self.picture.name
view.py
class ChapDetail(generic.ListView):
model = Chapter
template_name = 'chapters/chapter_detail.html'
urls.py
app_name = 'chapters'
urlpatterns = [
path('<str:book>', views.BookChaps.as_view(), name='chap_list'),
path('<str:book>/<str:slug>/', views.ChapDetail.as_view(), name='chap_detail'), # both slug fields
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
template
<div style="padding-top: 10px; display: block;">
{% for i in chapter.picture_set.all %}
<div>
<img src="{{ i.picture.url }}" alt="Not found">
</div>
{% endfor %}
</div>
media folder:
For restricting you query you can use the methode .filter() Filter Django Docs
It would be something along the line Chapter.objects.filter(id=id).
You can get the id (or other filter param) from you path params in the url.
For the missing pictures, are you sure your MEDIA URL is set correct in the settings?

Django 3.0 images: Unable to display images in template

I have model named Book in models.py file.
And based on this model, a view has been created to display images as products.
Which renders books(products) on shop.html template.
Problem is that i am unable to get their cover images which are saved across each publishers id who is seller of those books.
This is code of shop.html (in which i am trying to display image).
<div class="container mt-4">
<div class="row">
{% for b in books|slice:":10" %}
<div class="col-lg-2 col-md-3 col-sm-4">
<div class="book-card">
<div class="book-card__book-front">
<img src={{MEDIA_URL}}{{b.cover.url}} alt="book-image">
</div>
</div>
<div class="book-card__title">
{{ b.title }}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
This is the model in which i am putting covers of books against publisher's ids (names)
def book_cover_path(instance, filename):
return os.path.join(
"covers", instance.publisher.user.username, str(
instance.pk) + '.' + filename.split('.')[-1]
)
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField('Title', max_length=255)
authors = models.ManyToManyField(Author, related_name='books_written')
publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published')
price = models.DecimalField('Price', decimal_places=2, max_digits=10)
description = models.TextField('Description')
upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True)
categories = models.ManyToManyField(Category, related_name='book_category')
cover = models.ImageField(upload_to=book_cover_path, null=True,blank=True)
class Meta:
unique_together = ('title', 'publisher')
get_latest_by = '-upload_timestamp'
This is view in views.py
def shop(req):
bookz = Book.objects.order_by('title')
var = {'books': bookz, 'range': 10}
return render(req, 'bookrepo/shop.html', context=var)
This is media setting in settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
This is my folder structure i did put covers in media/covers/publisher/image.jpg EVEN i tried something like this media/media/covers/publisher/image.jpg
This is structure of media directory
I am getting NOT FOUND error in django console
Not found error like these
I think this have to do something with url i m trying to create must be missing something.
Otherwise b.title is working fine. Issue is just with image retrieval.
IF anyone don't understand book_cover_path function they can just tell me the way to make url as if books are lying in media/covers/image.jpg because i am unable to do this ALSO. As,
cover = models.ImageField(upload_to='covers', null=True,blank=True)
replace this line
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
to
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
because it is the Absolute path to the directory that will hold the file.
and replace
<img src={{MEDIA_URL}}{{b.cover.url}} alt="book-image">
to
<img src="{{b.cover.url}}" alt="book-image">
and add these lines in projects url.py file
from django.conf import settings
from django.conf. urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
try this on shop.html ,Check the docs here.
<img src="{{ b.cover.url }}" alt="book-image">

The 'cover' attribute has no file associated with it. Django

I want to display person pictures in a table with their name and surname columns. When i put as source static it show pictures but when i send request to database it didn't show. And its already insert data to database and picture to /media/images/.
view.py:
def viewpost(request):
person_list = Persona.objects.all()
if request.method == 'POST':
if request.POST.get('name') and request.POST.get('surname') and request.POST.get('address'):
person = Persona()
person.name = request.POST.get('name')
person.surname = request.POST.get('surname')
person.address = request.POST.get('address')
person.age = request.POST.get('age')
person.cover = request.FILES['cover']
person.save()
return HttpResponseRedirect('/viewpost')
else:
return render(request, 'mysite/viewpost.html', {'persons': person_list})
model.py:
class Persona(models.Model):
name = models.CharField(max_length=255, unique=False)
surname = models.CharField(max_length=255, unique=False)
address = models.TextField()
age = models.CharField(max_length=255, unique=False)
cover = models.ImageField(upload_to='images/')
and template:
<td ><img src="{{person.cover.url}}" class="img-responsive" width="40px" id="pop" data-toggle="modal" data-target="#myModal"/></td>
Without having settings and template code it´s difficult to get the whole picture, but here you have some tips:
To show static files in a template remember to use the {% load static %} tag.
Anyway, user uploaded files live better in a media folder, not in static. You should include it in your settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
If problem is not solve. Try this.
in urls.py add this in bottom:
from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in html template
<form method="post" enctype="multipart/form-data">
in settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

Django media file path is incorrect, missing a directory

Currently using Django 1.9.
Image files in my model are uploading properly to
project\media\FILEPATH.jpg
However, images are attempting to be displayed using the filepath without \media. For example, when I go to my localhost http://127.0.0.1:8000/media/FILEPATH.jpg in my browser, I get a 404 because Django's get request is looking for:
project\FILEPATH.jpg
How do I get django to serve my media files properly with \media\?
More information if it may be of any use:
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.dirname(os.path.join(BASE_DIR, 'media'))
model:
image = models.ImageField(upload_to='media', blank='true')
project urls.py I have the following after urlpatterns as per the documentation:
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Thank you for any help!
models.py
class Post(models.Model):
ptype = models.ForeignKey('blog.Type', related_name='posts')
title = models.CharField(max_length = 100)
text = models.TextField()
published_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
class Image(models.Model):
post = models.ForeignKey('blog.Post', related_name='images')
image = models.ImageField(upload_to='media', blank='true')
views.py
class Posts(generic.ListView):
model = Post
context_object_name = 'posts'
template_name = 'blog/posts.html'
posts.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<p>{{post.title}}</p>
<p>{{post.text}}</p>
{% for image in post.image_set.all %}
<img src="{{ image.image.url }}">
{% endfor %}
{% endfor %}
{% endblock %}
Ok
When your declare the upload on the model, Django detect automatically that your route of media is BASE_DIR/media, when you put somthing in upload_to on the model you are declare that this image have to saved on BASE_DIR/media/something
Example: if I want to save the user's images into media I have to make this on the model
image = models.ImageField(upload_to='users/', blank='true')
and my image will saved on localhost/media/users/FILEPATH.jpg
All this url after media/ is saved on your field of 'image' so your image field will say just 'users/FILEPATH.jpg' but not the localhost/media/
Thats why you need to write the /media/ in you src
<img src="/media/{{ image.image }}">
and if you save the image on the field named 'image' your will not need the .url.
Try it.

django broken thumbnails

I am trying to make a blog with an imagefield for my posts. I have imageupload working in the django admin panel but I have broken thumbnails. If I click on the images I got a 404 error with the following:
Using the URLconf defined in firstblog.urls, Django tried these URL patterns, in this order:
^$ [name='home']
^admin/
The current URL, images/heroimage/, didn't match any of these.
in my models.py I have:
from django.db import models
from django.db.models import permalink
class posts(models.Model):
author = models.CharField(max_length = 45)
title = models.CharField(max_length = 100)
bodytext = models.TextField()
timestamp = models.DateTimeField()
image1 = models.ImageField(upload_to="images/heroimage/", default='')
category = models.ForeignKey('blog.Category', default='')
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_blog_post', None, { 'slug': self.slug })
class Category(models.Model):
title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_blog_category', None, { 'slug': self.slug })
What I'm trying to do is to have the image that was uploaded to the post, displayed on the site.
Here is my index.html where I try to call the image to the post.
<div class="container">
<h1>First Blog</h1>
{% for post in posts %}
<div class="posts">
<p> <img src="{{blog.image1.url}}" /> {{ blog }}</p>
<h2>{{ post.title }}</h2>
<h3>Posted on {{ post.timestamp }} by {{ post.author }}</h3>
<p> {{ post.bodytext }}</p>
</div>
<hr>
{% endfor %}
</div>
my django project I created was called firstblog , I then have an app named blog. In the root of my project folder "firstblog" I have a folder for images and then a sub folder inside that one called heroimage.
Can anyone help me get this working?
Thanks
It is appended to your MEDIA_ROOT setting.
https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.FileField.upload_to
Set a media root for uploaded files the to retrieve the files, ill give you an example:
# settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# models
class Blog(models.Model):
main_image = models.ImageField(default='none/none.jpg', upload_to='blog'
# template
<img src="/media/{{ blog.main_image }}">
# media folder after
media/blog/imageuploaded.jpg
media/none/none.jpg # This file was already created
To upload to the static directory change
MEDIA_ROOT = STATIC_ROOT or STATICFILES_DIRS[0]
Though this is absolutely not recommended!

Categories

Resources