python - ManyToManyField 渲染中的 auth.user.none 和 <QuerySet []>

标签 python django

我尝试显示喜欢我的网站上用 Django 编写的某些图像的用户数量。 图像模型如下所示:

class Image(models.Model):
    (***)
    users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
                        related_name='images_liked',
                        blank=True)

当我在模板中使用时:

{{image.users_like.all}}

我明白了:

查询集[]

当我在模板中使用时

{{image.users_like}}

我明白

auth.User.None

这很奇怪,因为在我的管理页面中我有信息表明有人喜欢这张照片。

下面是我的 View 功能:

def image_detail(request, id, slug):
    image = get_object_or_404(Image, id=id, slug=slug)
    return render(request,
              'images/image/detail.html',
              {'section': 'images',
              'image': image})

编辑

我的管理页面,在“用户喜欢”部分中显示已经喜欢该照片的用户的用户名。 PrtSc如下:

photyo

完整 block

<h1>{{ image.title }}</h1>
`<p>{{image.users_like.all}}</p>
{% load thumbnail %}
{% thumbnail image.image "300" as im %}
    <a href="{{ image.image.url }}">
        <img src="{{ im.url }}" class="image-detail">
    </a>
{% endthumbnail %}
{% with total_likes=image.users_like.count users_like=image.users_like.all %}
    <div class="image-info">
            <div>
                <span class="count">
                    <span class="total">{{ total_likes }}</span>
                    like{{ total_likes|pluralize }}
                </span>
                <a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button">
                    {% if request.user not in users_like %}
                        Like
                    {% else %}
                        Unlike
                    {% endif %}
                </a>
            </div>
        {{ image.description|linebreaks }}
    </div>

    <div class="image-likes">
        {% for user in image.users_like.all %}
            <div>
                <img src="{{ user.profile.photo.url }}">
                <p>{{ user.first_name }}</p>
            </div>
        {% empty %}
            Nobody likes this image yet.
        {% endfor %}
    </div>
{% endwith %}

最佳答案

在上面的评论中回答。调用时 QuerySet 为空。将用户添加到 image.user_like 后,问题消失了。谢谢 Solarissmoke。

关于python - ManyToManyField 渲染中的 auth.user.none 和 <QuerySet []>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59578574/

相关文章:

python - 切割结构化 numpy 数组

python - 声明几个类似表单字段的 DRY 方式

python - 轮廓中点之间的距离opencv

python - 带有数据库查询的 Django charfield 模型

python - celery worker 无法连接到 docker 实例上的 redis

python - django-rest-framework、多表模型继承、ModelSerializers 和嵌套序列化程序

django - clean 方法不适用于 URLField

python - Python 中的类型转换

Python子进程脚本完成后继续运行

python - 如何通知python日志记录处理程序可能发生崩溃并应刷新日志?