【问题标题】:How to acces the the django ManyToMany Field in django Template如何访问 django 模板中的 django ManyToManyField
【发布时间】:2019-05-24 01:11:49
【问题描述】:

我的模型中有一组属性,其中一个属性是类型多对多字段。我可以访问模板中的所有属性,而不是一个多对多字段。

我已尝试在我的模板中进行以下操作

{% for post in all_posts %}
{{ post.likes }}
{% endfor %} 

models.py

class Posts(models.Model):
title = models.CharField(max_length=250, blank=False)
content = models.CharField(max_length=15000,
                           help_text="Write Your thought here...")
creation_time = models.DateTimeField(auto_now_add=True, editable=False)
likes = models.ManyToManyField(User, blank=True, related_name='likes')

views.py

def home(request):
    template = loader.get_template('home.html')
    all_posts = Posts.objects.all()
     context = {
         'all_posts': all_posts,
     }
     return HttpResponse(template.render(context, request))

当我使用{{ post.likes }} 时,页面上呈现的是 auth.User.None

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    您必须遍历所选帖子的所有赞

    试试这样的:

    {% for post in all_posts %}
        {% for like in post.likes.all %}
            {{ like }}
        {% endfor %}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 2011-01-10
      • 2021-10-18
      • 1970-01-01
      • 2019-09-20
      • 2012-07-04
      • 2019-08-07
      • 2014-11-22
      相关资源
      最近更新 更多