【问题标题】:How can I get all users images in template,django如何在模板中获取所有用户图像,django
【发布时间】:2015-02-09 04:22:09
【问题描述】:

所以,我正在尝试用 Django 写博客,但现在我遇到了 cmets 问题。 在每个帖子下面我都有用户 cmets ,带有评论作者姓名、图片和评论。

评论类:

class Comments(models.Model):
    body = models.TextField()
    author = models.ForeignKey(User, related_name= 'upser')
    image = models.OneToOneField(UserProfile , related_name='im')
    timestamp = models.DateTimeField(auto_now=True)
    post = models.ForeignKey(Post, related_name='comments')

    class Meta:
        ordering = ('-timestamp',)

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='oser')
    picture = models.ImageField(upload_to='profile_images', blank=True)

    def __unicode__(self):
        return self.user

所以,我有与 UserProfile 类连接的 cmets 类,其中我有用户的图像。

这就是我在模板中显示所有 cmets 的内容:

 {% for comment in comments %}
            <li>

            <div class="media" style="margin-top: 10px">
                    <a class="pull-left" href="#">
                        <img class="media-object" src={{ MEDIA_ROOT }}/{{ PLACE FOR USER'S PICTURE }} alt="" width="80px" height="80px" >
                    </a>

                    <div class="media-body">
                        <h4 class="media-heading">{{ comment.author}}
                            <small>{{ comment.timestamp }}</small>
                        </h4>
                            {{ comment.body }}
                    </div>
                </div>


            </li>
        {% endfor %}

还有一个问题,如果我有 Comments 对象,我如何从模板访问用户图像?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    我不知道您为什么需要 image 属性,它是 UserProfile 模型的外键。

    您可以在模板中执行此操作: {{comment.author.oser.picture.url}}

    执行以下操作:

    获取评论,获取作者,找到对应UserProfile的“oser”属性,然后获取图片属性的图片url。

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      你的模型对我来说有点奇怪,或者不太符合你的描述:

      你有一个“评论”类(不应该是“评论”,因为它包含一条评论吗?)它有一个正文、作者、时间戳、它所属的帖子......很好。但是您命名为“图像”的字段实际上是 user_profile,对吗?此外,OneToOneField 意味着 Comment(s) 对象和 UserProfile 之间存在一对一的关系......很可能不是您想要的!

      其实你已经有了作者,所以这足以得到图片...所以作者是用户-> user_profile -> 图片。还是我对您的模型和问题理解有误?

      【讨论】:

        猜你喜欢
        • 2017-07-03
        • 1970-01-01
        • 2017-07-29
        • 2014-08-08
        • 1970-01-01
        • 2015-10-31
        • 2012-11-22
        • 2014-06-28
        相关资源
        最近更新 更多