你好,我在Django使用基于类的视图,我想创建一个搜索表单,让用户在我的应用程序中找到他们自己最喜欢的产品,并带有多个过滤器和排除项,但我做不到.我的代码在这里,如果任何人可以修改它以使其正确,请帮助我:

Models.py

from django.db.models import models
from django.core.validators import RegexValidators


class Product(models.Model):
    num=RegexValidators(r'^[0-9a-zA-Z]*$')
    title = models.CharField(max_length=100)
    embed_id = models.CharField(max_length=15, validators=[num])
    description = models.TextField(null=True, blank=True)

Forms.py

from django import forms


class ProductSearchForm(forms.Form):
    title = forms.CharField(required=False)
    embed_id = forms.CharField(required=False)
    description = forms.CharField(required=False)

Views.py

from django.views.generic import ListView
from .models import Product
from .forms import ProductSearchForm


class ProductListView(ListView):
    model = Product
    form_class = ProductSearchForm
    template_name = 'pages/product/list_products.html'

    def get_queryset(self):
       queryset = super().get_queryset()
       form = self.form_class(self.request.GET)
       if form.is_valid():
           title = form.cleaned_data.get('title')
           embed_id = form.cleaned_data.get('embed_id')
           description = form.cleaned_data.get('description')
           if title:
              queryset = queryset.filter(title__icontains=title)
           if embed_id:
              queryset = queryset.filter(embed_id__icontains=embed_id)
           if description:
              queryset = queryset.filter(description__icontains=description)
           return queryset

   def get_context_data(self, [**kwargs):
      context = super().get_context_data(self, **kwargs):
      context['form'] = self.form_class(self.request.GET)
      return context

Product_earch.html

<form method="get" action="{% url 'product_list' %}">
{{ form.as_p }}
<input type="submit" value="Search">
</form>
{% if object_list %}
<ul>
{% for product in object_list %}
<li>{{ product.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No product found.</p>
{% endif %}

我知道如何在基于函数的视图中处理这个问题,但我想创建它的Generic.listview.

推荐答案

我试着用你的代码不能运行.

这就是我的方法:

Views.py

from django.views.generic import ListView
from .models import Product
from .forms import ProductSearchForm


class ProductListView(ListView):
    model = Product
    form_class = ProductSearchForm
    template_name = 'product.html'
    context_object_name = 'products'
    
    def get_queryset(self):
        queryset = super().get_queryset()
        form = self.form_class(self.request.GET)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            embed_id = form.cleaned_data.get('embed_id')
            description = form.cleaned_data.get('description')
            if title:
                queryset = queryset.filter(title__icontains=title)
            if embed_id:
                queryset = queryset.filter(embed_id__icontains=embed_id)
            if description:
                queryset = queryset.filter(description__icontains=description)
        return queryset

    def get_context_data(self, **wars):
        context = super().get_context_data(**kwargs)
        context['form'] = self.form_class(self.request.GET)
        return context

all data

data

search data

results

Django相关问答推荐

如何在REST框架中以SON格式返回错误,而不是HTML格式返回错误?

Django的update_or_create失败,尽管指定了kwargs'

模仿没有像预期的那样工作(Django)

Django查询一个查询集的输入结果,以查找没有出现在另一个模型中的对象

通过父模型查询子对象-Django

根据当前对象中的多对多字段过滤对象

在模板中调用 FileField 对象会呈现不正确的路径

如何根据查询集中的条件返回多个聚合?

django 管理员登录突然要求 csrf 令牌

AttributeError:'Manager'对象在Django中没有属性'get_by_natural_key'错误?

可插拔应用程序的Django默认设置约定?

在 Django 管理员中嵌套内联?

用户组和权限

如何使用 SQL 的IN等字段上的数组过滤 django 查询集?

django 有条件地过滤对象

django 模板 if 或语句

导入错误无法在windows环境下导入名称execute_manager

Django 不调用模型清理方法

如何在不同的元素上添加注释?

Python/Django - 避免在源代码中保存密码