我正在尝试将搜索栏添加到ListView。当我点击搜索结果显示正常但当我点击结果的第二页时,我得到了整个结果。
class LegsIndex(FormMixin, generic.ListView):
form_class = MyForm
model = Legs
paginate_by = 5
template_name = "legs/legshome.html"
def get_queryset(self):
return self.model.objects.published()
def get_context_data(self, **kwargs):
context = super(LegsIndex, self).get_context_data(**kwargs)
return context
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
self.form = self.get_form(form_class)
search = request.GET.get('search', None)
if search:
self.object_list = self.get_queryset().filter(title__icontains=search)
else:
self.object_list = self.get_queryset()
context = self.get_context_data(object_list=self.object_list, form=self.form)
return self.render_to_response(context)
这样做的正确方法是什么。我需要在表格中设置过滤这些字段,否则显示所有数据。
class MyFilterForm(Form):
search = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Looking For ...'}), required=False)
counties = forms.ModelMultipleChoiceField(queryset=Legs.objects.values_list('country', flat=True).distinct(),
widget=forms.CheckboxSelectMultiple(), required=False)
cities = forms.ModelMultipleChoiceField(queryset=Legs.objects.values_list('city', flat=True).distinct(),
widget=forms.CheckboxSelectMultiple(), required=False)
class Meta:
fields = '__all__'
答案 0 :(得分:1)
问题的评论部分:
您可以简单地将请求从视图传递到表单并将其更新为:
#View
class LegsIndex(FormMixin, generic.ListView):
....
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs.update(request_data=self.request)
return kwargs
#Form
class MyFilterForm(Form):
#form fields
def __init__(self, *args, request_data=None, **kwargs):
super().__init__(*args, **kwargs)
self.fields['search'].initial = request_data.GET.get('search', '')
答案 1 :(得分:0)
我构建了一个解决这个问题的库,ListView是可搜索和可分页的,它不会丢失查询参数