使用ForeignKey的Get_absolute_url在Django模板中不起作用

时间:2018-02-13 19:52:58

标签: django django-templates

我正在尝试在Django View中返回JsonResponse:

onCreate()

notifications_dropdown.html:

return JsonResponse(render_to_string(
            'notifications/notifications_dropdown.html',
            {'new_notifications': new_notifications}),
            safe=False)

我的通知模型有ForeignKey:

{% if new_notifications %}
    {% for notification in new_notifications %}
        <a class="dropdown-item" href="{{ notification.task.get_absolute_url }}">
            <span class="text-success">
                <strong><i class="fas fa-info fa-fw"></i>{{ notification.title }}</strong>
            </span>
            <span class="small float-right text-muted">{{ notification.created|date:"SHORT_DATETIME_FORMAT" }}</span>
            <div class="dropdown-message small">{{ notification.text }}</div>
        </a>
        <div class="dropdown-divider"></div>
    {% endfor %}
{% endif %}

问题是 {{notification.task.get_absolute_url}} 什么都不返回。但是当我在shell中获得相同的通知对象时,它返回正确的url。此外,我在其他模板中使用 {{task.get_absolute_url}} ,它按预期工作。

任何想法,为什么 {{notification.task.get_absolute_url}} 在模板中不起作用?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我有

new_notifications = Notification.objects.filter(
            user=request.user,
            status=Notification.NEW
        ).values()

.values()没有包含任务对象。它刚刚返回 task_id