来自用作外键的ImageField的图像URL

时间:2019-06-24 17:35:05

标签: django django-models django-templates django-2.2

我正在尝试使用此标签{{post_details.header_image.url}}在模板中查看图像。当我这样做时,图像不会出现。

models.py

class ImageUpload(models.Model):
    name = models.CharField(
        max_length=50,
        )
    file = models.ImageField(
        upload_to='images/%Y/%m/%d',
        )

class BlogPost(models.Model):
    title = models.CharField(
        max_length=70,
        unique=True,
        )
    slug_post = models.SlugField(
        'Slug',
        max_length=70,
        unique=True,
        )
    contents = models.TextField(
        'Contenuti',
        blank=True,
        )
    header_image = models.ForeignKey(
        ImageUpload,
        on_delete=models.CASCADE,
        related_name="blog_header_image",
        blank=True,
        )

views.py

def singlePost(request, slug_post):
    post_details = get_object_or_404(BlogPost, slug_post=slug_post)
    context = {
        "post_details": post_details,
        }
    template = 'blog/reading/single_post.html'
    return render(request, template, context)

single_post.html

  <img src="{{ post_details.header_image.url }}" class="img-fluid" alt="{{ post_details.title }}">
  <h1>{{ post_details.title }}</h1>
  <p>{{ post_details.contents }}</p>

我可以看到标题和内容,但是图像标签显示为空白。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您错过了该字段本身。

<img src="{{ post_details.header_image.file.url }}" ...>