Django分类筛选时启动服务器报'builtin_function_or_method'无model属性错误
Django品牌筛选功能报错:'builtin_function_or_method' object has no attribute 'model' 解决方法
错误根源
报错由两处代码问题导致:
filter/views.py误用Python内置函数all作为queryset参数,而非Post模型的查询集对象filter/filters.py中fields的格式不符合django-filter的语法要求
修复方案及修正代码
1. 修正filter/views.py
导入Post模型,并将queryset参数替换为正确的模型查询集:
from django.shortcuts import render from .filters import IndexFilter from search.models import Post # 新增导入Post模型 def filter(request): index_filter = IndexFilter(request.GET, queryset=Post.objects.all()) context = { 'index_filters': index_filter, } return render(request, 'filter.html', context)
2. 修正filter/filters.py
将fields改为列表格式(如需指定筛选规则,可使用字典格式如{'brand': ['exact']}):
import django_filters from search.models import Post class IndexFilter(django_filters.FilterSet): class Meta: model = Post fields = ['brand'] # 修正为符合要求的列表格式
3. 可选:修复模板路由指向(若存在路由匹配问题)
模板表单的action当前指向{% url 'index' %},但现有路由中仅存在name='filter'的路径,若index路由未定义,建议修改为:
<form method="get" action="{% url 'filter' %}"> {{ index_filters.form }} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form>
验证修复
重启服务器后,访问筛选页面即可正常加载品牌筛选表单,提交后可按品牌过滤Post数据。
内容的提问来源于stack exchange,提问作者LeBrone
相关产品推荐
相关产品推荐

