简体   繁体   English

努力使用 django 显示图像

[英]Struggling to display images using django

I am creating a blogging website using django framework and so I am struggling to display images on dynamic pages.我正在使用 django 框架创建一个博客网站,所以我很难在动态页面上显示图像。 Here is my code:这是我的代码:

models.py:模型.py:

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts')
    updated_on = models.DateTimeField(auto_now=True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now=True)
    status = models.IntegerField(choices=Status, default=0)
    cover_image = models.ImageField()
    captioned_image = models.ImageField()
    caption = models.CharField(max_length=300)

    class Meta:
        ordering = ['-created_on']
    
    def __str__(self):
        return self.title

views.py:视图.py:

def post(request, slug):
    post = Post.objects.get(slug = slug)
    context = {'post': post}
    return render(request, template_name='blogger/pages.html', context=context)

within my html:在我的 html 中:

<img class="img-fluid" src="{{post.cover_image.url}}" />

I am unsure what I am doing incorrect here as text is correctly displaying in my code dynamically, just unable to work with images.我不确定我在这里做错了什么,因为文本在我的代码中动态正确显示,只是无法使用图像。

Provide an "upload_to" for your image field so that your images upload there.为您的图片字段提供“upload_to”,以便您的图片上传到那里。

cover_image = models.ImageField(upload_to="Folder")

There's a couple things that might be going wrong.有几件事可能会出错。 Are you using the development server that comes packaged with Django or a production server?您使用的是 Django 随附的开发服务器还是生产服务器? Django doesn't serve media files during development by default.默认情况下,Django 在开发过程中不提供媒体文件。 You need to enable it by putting this in your url.py您需要通过将其放入url.py来启用它

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    ...]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

Also, make sure you have MEDIA_ROOT AND MEDIA_URL configured.此外,请确保您已配置 MEDIA_ROOT 和 MEDIA_URL。 The most basic way of doing this is adding this to your settings.py最基本的方法是将其添加到您的 settings.py

# Base url to serve media files
MEDIA_URL = '/media/'

# Path where media is stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

If neither of these fix the issue, it might be helpful for us to see the output of your terminal where the server is running and/or what the network tab in your developer tools looks like (make sure to just select images so it's easier to read)如果这些都不能解决问题,那么查看运行服务器的终端的 output 和/或开发人员工具中的网络选项卡的外观可能会对我们有所帮助(确保仅 select 图像,这样更容易读)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM