如何将对象数组从基于Django类的视图发送到索引.html文件?

2024-10-03 21:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

目标:

我想使用FullCalendar(https://fullcalendar.io/)显示数据库中的事件对象。FullCalendar接受事件对象数组作为属性。在

我的问题是:

我可以用事件对象将上下文数据发送回模板,但据我所知,我只能使用Django的模板标记系统与数据交互。*编辑:当我用ptoHistory替换硬编码数组时,我在chrome控制台中收到以下错误:

jquery-3.1.1.min.js:2 Uncaught ReferenceError: ptoHistory is not defined at HTMLDocument. ((index):141) at j (jquery-3.1.1.min.js:2) at k (jquery-3.1.1.min.js:2)

索引.html:

{% extends 'base.html' %}

{% block content %}

//ACCESSING THE CONTEXT DATA LIKE THIS WORKS BUT I CAN'T USE ptoHistory IN MY FULLCALLENDAR SCRIPT 
{% for history in ptoHistory %}
 <li>{{obj.leave_type}}</li>
{% endfor %}

<div class="container">
  <div id="calendar">
    <!-- Calendar is injected here -->
  </div>

<!----------------------- SCRIPTS ----------------------------->
<script>

$(document).ready(function() {

  $('#calendar').fullCalendar({
    defaultView:'month',
    editable: true,
    // MY ARRAY OF OBJECTS WILL REPLACE THIS HARDCODED ARRAY
    events: [
      {
        title: 'All Day Event',
        start: '2017-01-12',
      },
      {
        title: 'Meeting',
        start: '2017-01-13T10:30:26',
        end: '2014-06-13T12:30:00'
      },
    ],


  });

});

</script>


{% endblock content%}

在索引视图.py公司名称:

^{pr2}$

有人能给我指出正确的方向吗?在


Tags: 数据对象div模板ishtmljs事件
1条回答
网友
1楼 · 发布于 2024-10-03 21:28:12

你说得对,这行不通。Django模板系统能够处理python对象,因为它们在模板完成渲染之前就已经执行了。在

不过,您仍然可以用javascript指定python列表,但不能使用python对象,而是json字符串。解决方案基本上是使用values()在视图中只合成您需要的内容。我不知道PtoHistory需要哪些字段,但您可以:

# views.py
import json
def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    ptoHistory = json.dumps(list(PtoHistory.objects.values()))
    # or do this if you only need several fields' value
    # ptoHistory = json.dumps(list(PtoHistory.objects.values('field1', 'field2')))
    context['ptoHistory'] = ptoHistory

    return context

// in javascript
$(document).ready(function() {

  $('#calendar').fullCalendar({
    defaultView:'month',
    editable: true,
    var histories = {{ ptoHistory|safe }};

相关问题 更多 >