ListView queryset无法将上下文数据传递给Template

时间:2019-04-24 14:41:26

标签: django

我的Search API遇到问题。即使查询集从模型中提取数据,queryset的结果也无法通过我的template

如果搜索为空,则查询集应返回与Models关联的所有current project,否则,它应返回符合查询条件的模型。

我已经测试了查询的结果,它返回了模型中的记录,但是无法将实例显示到模板中。

我的SEARCH ListView:

class ModelSearchListView(ListView):
    model = Model
    template_name = 'predictions/model_listview.html'
    context_object_name = 'models'
    paginate_by = 2

    def get_queryset(self):
        query  = self.request.GET.get('q')
        proj_pk = self.kwargs.get('pk') 
        proj = get_object_or_404(Project, id=proj_pk)
        if query:
            result = Model.objects.filter(Q(project=proj.id) & (Q(name__contains=query) | 
            Q(algorithm_type__contains=query) |
            Q(predictors__contains=query) |
            Q(target_column__contains=query))).order_by('-date_created')
            # print('result: ', result)
        else:
            result = Model.objects.filter(project=proj.id).order_by('-date_created')
            print('result: ', result)
        return result

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        project = Project.objects.filter(id=self.kwargs.get('pk')).first()

        context['current_project'] = project.id

我的搜索表格:

<form class="form my-2 my-lg-0" method="GET" 
                  action="{% if current_project %}
                    {% url 'model-search-listview' current_project %}
                  {% else %}
                    {% url 'model-search-listview' object.project.id %}
                  {% endif %}">

                <div class="input-group">
                    <input class="form-control  " type="text" name="q" value="{{ request.GET.q }}" aria-label="Search"
                        placeholder="Search">
                    <span class="input-group-btn">
                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="Search">
                            Search
                        </button>
                    </span>
                </div>
            </form>

模板:

{% if not models %} #Always TRUE because models is empty
        <h5>No prediction models created for this project!</h5>
{% else %}
        #Loop never executed
        {% for model in models %} # models HERE ALWAYS returns empty
            [SOME CODE HERE]

        {% endfor %}
{% endif %}

1 个答案:

答案 0 :(得分:2)

您需要返回新的上下文

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    project = Project.objects.filter(id=self.kwargs.get('pk')).first()

    context['current_project'] = project.id
    return context