【问题标题】:cant make connections betwen uploaded image and template django无法在上传图片和模板 django 之间建立连接
【发布时间】:2020-09-20 18:37:14
【问题描述】:

我正在尝试通过管理面板为我的帖子模型上传一张图片,但我无法在我的模板中显示它,请帮助 这是我的帖子模型 我得到这个错误请帮助我 值错误在 / 'Img' 属性没有与之关联的文件。

class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE ,null=True)
    title = models.CharField(max_length=200,default='a')
    text = models.TextField(default='a')
    Img = models.ImageField(upload_to='images/',null =True)

对于 urls.py,我使用了以下代码:

if settings.DEBUG: # new
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

和views.py:

def post_list(request):
    posts= Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'post/index.html', {'posts': posts})

最后是我的 index.html 模板:

{% for post in posts %}

                    <div class="blog-post-thumb ">
                        <div class="blog-post-image ">
                            <a href="single-post.html ">


                                <img src="{{post.Img.url}}" class="img-responsive " alt="Blog Image ">
                            </a>
                        </div>
                        <div class="blog-post-title ">
                            <h3><a href="single-post.html ">{{ post.title }}</a></h3>
                        </div>
                        <div class="blog-post-format ">
                            <span><a href="# "><img src="images/author-image1.jpg " class="img-responsive img-circle ">A</a></span>
                            <span><i class="fa fa-date "></i> published: {{ post.published_date }}</span>
                            <span><a href="# "><i class="fa fa-comment-o "></i>  Comments</a></span>
                        </div>
                        <div class="blog-post-des ">
                            <p>{{ post.text|linebreaksbr }}</p>
                            <a href="single-post.html " class="btn btn-default ">Continue Reading</a>
                        </div>
                    </div>
                {% endfor %}

【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:

    第一次改变

        posts=Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    

    这个到这个

        posts= Post.objects.all()
    

    因为您的帖子模型中没有发布日期字段

    如果不工作则添加

        <a href="single-post.html ">
    
    {% if post.Img %}
    
                <img src="{{post.Img.url}}" class="img-responsive " alt="Blog Image ">
    {% endif %}
        </a>
    

    在setting.py中

    MEDIA_ROOT=os.path.join(BASE_DIR,'media')
    MEDIA_URL='/media/'
    

    它应该可以工作,因为您的代码在我的 Django 服务器中工作。

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 2020-02-12
      • 2014-04-10
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多