'图像'属性没有与之关联的文件 - django

时间:2018-02-05 11:57:58

标签: python django image

我有一个博客项目,在运行django dev服务器时收到上述错误。我已通过管理面板上传了一张图片,然后按预期将其保存在posts / media文件夹中。请任何人帮忙吗?

我的项目(缩短版)如下所示:

 - blogproject
     - posts 
         - media
         - static
         - templates
             - posts
             - base.html
             - getAllPosts.html
    - blog
        - urls.py
        - settings.py
        - models.py
  

SETTINGS.PY

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [STATIC_DIR, ]
STATIC_URL = '/static/'
MEDIA_DIR = os.path.join(BASE_DIR, 'posts/media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
  

URLS.PY

[...]

urlpatterns += static(settings.STATIC_URL, 
document_root=settings.STATIC_ROOT)

urlpatterns += static(settings.MEDIA_URL, 
document_root=settings.MEDIA_ROOT)
  

models.py

class Post(models.Model):
    title = models.CharField(max_length=200)
    summary = models.CharField(max_length=500, default=True)
    body = models.TextField()
    pub_date = models.DateTimeField(default=timezone.now)
    category = models.ManyToManyField('Category')
    author = models.ForeignKey(User, default=True)
    titleSlug = models.SlugField(blank=True)
    authorSlug = models.SlugField(blank=True)
    image = models.ImageField(upload_to="images/%Y/%m/%d", null=True)

def save(self, *args, **kwargs):
    self.titleSlug = slugify(self.title)
    self.authorSlug = slugify(self.author)
    super(Post, self).save(*args, **kwargs)

def __str__(self):
    return self.title
  

getAllPosts.html

<!DOCTYPE html>
{% extends "posts/base.html" %} 
{% load static %}
{% load template_tags %}

{% block content %} 
{% if latest_posts %}
   {% for post in latest_posts %}

   <a href="{% url 'getPost' slug=post.titleSlug %}">
      <img src="{{ MEDIA.URL }} {{post.image.url}}" alt="image-
{{post.title}}"/>
   </a>

0 个答案:

没有答案