【问题标题】:Django class based view with FormMixin and ListView带有 FormMixin 和 ListView 的基于 Django 类的视图
【发布时间】:2013-10-22 05:53:10
【问题描述】:

我在将 Django 视图与 Django 模板连接时遇到问题。我正在尝试将基于类的视图与 FormMixin 和 ListView 一起使用。

class Merchants(FormMixin, ListView):
    """
    A view of that shows a list of all the merchants.
    """
    template_name = "reporting/merchants.html"
    model = models.Merchant
    context_object_name = "merchants"

    def get_queryset(self):
        queryset = super(ViewClassName, self).get_queryset()
        search_query = self.request.GET.get("q", None)
        if search_query:
            queryset = queryset.filter(name__ilike=search_query)
            return queryset

我的目标是在我的模板中使用我的 get_queryset 函数来允许用户搜索商家。此表单正在发布给自己,但不幸的是它没有返回任何内容。我已经阅读了有关 FormMixins 的 Django 文档,但仍然无法弄清楚。任何帮助都将不胜感激。

<form action= "">
<input name="q" placeholder="search for merchant">
<button type="submit">Search </button>
</form> 

谢谢!

【问题讨论】:

  • FormMixin 在这里没有做任何事情,可以删除。

标签: django django-templates django-views


【解决方案1】:

你有一个缩进问题:

if search_query:
    queryset = queryset.filter(name__ilike=search_query)
    return queryset # <--- this should be outside of if statement

应该是:

if search_query:
    queryset = queryset.filter(name__ilike=search_query)
return queryset

【讨论】:

  • 感谢您的建议,不幸的是,在修复缩进错误后,我的页面上仍然没有任何搜索功能。还有其他想法吗?
猜你喜欢
  • 2018-03-05
  • 2011-09-18
  • 2018-03-12
  • 2012-10-23
  • 1970-01-01
  • 2022-01-07
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多