Django 3.0 images: Unable to display images in template

大兔子大兔子 提交于 2020-06-29 05:04:35

问题


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)

回答1:


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)



回答2:


try this on shop.html ,Check the docs here.

<img src="{{ b.cover.url }}" alt="book-image">



来源:https://stackoverflow.com/questions/61616197/django-3-0-images-unable-to-display-images-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!