用ImageField上传的图像不显示

时间:2019-08-23 11:19:25

标签: python django

我有这样的问题:我想从django管理员上载文章的封面图片,但是该图片未显示在模板上,并且其名称在PyCharm中用红色like in this picture书写。这是我的代码:

settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

models.py

class Article(models.Model):
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=200)
    content = HTMLField()
    # image = models.CharField(max_length=2000)
    image = models.ImageField(upload_to='static/img')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
    post_date = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(unique=True, null=True, editable=False)

    def __str__(self):
        return self.title

article.html

<div class="blog-item wide-blog-item">
  <a href="/"><img src="/{{ article.image }}" class="image"/></a>
  <h3 class="font-reg"><a href="">{{ article.title }}</a></h3>
  <div class="blog-item-meta">
  <span>{{ article.post_date }}</span>
  </div>
  <div class="blog-item-meta">
  <span style="text-transform: capitalize;">{{ article.category }} . </span>                            
  </div>
</div>

views.py

def index(request):
    context = {
        'category_list': Category.objects.all(),  # navbarda gostermek uchun
        'articles': Article.objects.all(),
    }
    return render(request, 'articles.html', context)


def article(request, article_slug, article_category):
    try:
        context = {
            'article': Article.objects.get(slug=article_slug),
            'category_list': Category.objects.all(),  # navbarda gostermek uchun
            'category': Category.objects.filter(name=article_category),  # url-de category name gostermek uchun
        }
    except Article.DoesNotExist:
        raise Http404("Such article could not be found")
    return render(request, 'article.html', context)

0 个答案:

没有答案