【问题标题】:loop through objects in django using template tags is not working使用模板标签循环遍历 django 中的对象不起作用
【发布时间】:2023-03-24 15:07:01
【问题描述】:

我有一个名为 Operation 的模型

class Operation(models.Model):
    title = models.CharField(max_length=255)
    title_tag = models.CharField(max_length=120, default='Medicine')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    img = models.ImageField(upload_to='media', null = True)
    date = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.title + ' | ' + str(self.author)

def get_absolute_url(self):
    return reverse('home')

和看起来像这样的views.py

def Operation(request):
    return render(request, 'operation.html')

class OperationView(ListView):
    object_context_name = 'operation'
    model = Operation
    template_name = 'operation.html'

class OperationDetailView(DetailView):
    model = Operation
    template_name= 'operation_details.html'

渲染所有操作的Listview的html页面如下

{% for operation in object_list %}
<article>
    <a href="{% url 'operation-detail' operation.pk %}" class="image"><img src="{{post.image}}" alt="" /></a>
    <h3>{{operation.title}}</h3> <br>
    <h6> {{operation.author}}</h6> <br>

    <p>{{operation.body | slice:":200"}}</p>
    <ul class="actions">
        <li><a href="{% url 'operation-detail' operation.pk %}" class="button">More</a></li>
    </ul>
</article>
{% endfor %}

但是它不起作用或在页面上呈现任何操作文章。有什么帮助吗?

【问题讨论】:

    标签: python html django templates django-templates


    【解决方案1】:

    如果你删除你的 context_object_name 你的循环将起作用。但是,如果您想使用该 context_object_name,您可以将循环编辑为:

    {% for operations in operation %}
    

    更多信息:docs

    【讨论】:

      【解决方案2】:

      这是因为您重命名了上下文对象的名称,要么删除它,要么使用 {%for operation in operations%}

      【讨论】:

        猜你喜欢
        • 2012-12-25
        • 2011-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多