你好,我在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.