Django渲染丢弃上下文值

时间:2018-07-28 15:21:21

标签: python django

早上好Django社区:

我遇到一个奇怪的context问题。

我使用函数get_context_data返回一个字典,该字典加载到render中的context参数中。我正在为视图中的context字典添加值,这些值一旦在模板中呈现后就无法访问。

urlpatterns:

url(r'^view_tutors/(?P<pk>[0-9]+)/$', ModelInstanceView.as_view(), {'model': Tutor,
            'model_two': TutorEvent}, name='view_tutors'),

view.py:

    class ModelInstanceView(LoginRequiredMixin, DetailView):
        """
        This view shows all information specific to one instance
        of a model.
        Needs extra functionality for tutors whose info is much more complicated
        """

    def get_model_instance_dict(self, pk, model):
        fields = []
        self.model = model
        for field in list(self.model._meta.get_fields()):
            if hasattr(field, 'verbose_name'):
                fields.append(field.verbose_name)
            elif isinstance(field, ManyToOneRel):
                pass
            else:
                fields.append(str(field).split(':')[-1].split('.')[-1])
#        try:
        values = list(self.model.objects.values_list().filter(pk=pk)[0])
        print values
        if hasattr(self.model, 'related_set'):  # ?
            fields.append('Tutors at this Site')
            related_values = self.model.objects.get(gg=pk).related_set.all()
            tutors_at_site = ''
            for x in range(len(related_values)):
                tutors_at_site += str(related_values[x].first_name + ' ' + related_values[x].last_name + ', ')
            values.append(tutors_at_site[:-2])
        model_instance_dict = OrderedDict(zip(fields, values))
        # except IndexError:  # no record for the pk
        #     model_instance_dict = None
        return model_instance_dict

    def get_context_data(self, pk, **kwargs):
        model = self.kwargs['model']
        print 'THE MODEL 0', model, type(model)
        context = {
            "model_name": str(model.__name__),
            "model_select": model.objects.get(pk=pk),
            "model": self.get_model_instance_dict(pk, model),
            "id": pk,
        }
        if model.__name__ == 'Tutor':
            events = self.kwargs['model_two']
            context["edit_model_url"] = 'edit_' + str(model.__name__).lower(),
            context["events_name"] = str(events.__name__),
            context["events"] = events.objects.filter(tutor_id=pk).values()
            context["edit_events_url"] = 'edit_' + str(events.__name__).lower(),
            context["create_events_url"] = 'create_' + str(events.__name__).lower()
        print context
        return context

    def get(self, request, pk, **kwargs):
        return render(request, 'athena_app/model_detail.html', {'output': self.get_context_data(pk)})

model_detail模板:

{% debug %}

                <table border="2" class="tablemodel">
         <style>

              .model_row:hover {
                background-color: #e8d2f7;
                cursor: pointer;
              }
              .model {
                text-align: center;
              }
            </style>
            {{ output.events }}

            <tr>
              <th class="col-md-2">Event</th>
              <th class="col-md-2">Event Date</th>
            </tr>
            {% for event in output.events %}
                <tr class="model_row" onclick="document.location='/{{ output.edit_events_url }}/{{ id }}'">
                    <!-- <td>{{ output.event }}</td> -->
                    <td>{{ output.event.tutor_id }}</td>
                    <td>{{ output.event }}</td>
                </tr>
              {% empty %}
                <li>This tutor has not attended any events.</li>
            {% endfor %}
          </table>

我可以将上下文字典变量作为调试打印到我的终端中,并在context['events']中查看适当的TutorEvent查询集。但是,在模板中,{debug} 'events'键返回空白值。我可以在模板中将{ output.events }作为字典列表进行打印,但是您无法在模板中进行任何迭代,就像您在模板中看到的那样。

任何人都能提供的专业帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您正确地使用event作为循环变量遍历了output.events。但是由于某种原因,在循环内部您正在使用output.event。应该是:

    {% for event in output.events %}
            <tr class="model_row" onclick="document.location='/{{ output.edit_events_url }}/{{ id }}'">
                <!-- <td>{{ event }}</td> -->
                <td>{{ event.tutor_id }}</td>
                <td>{{ event }}</td>
            </tr>
    ...