Django: Search form in Class Based ListView

前端 未结 7 2128
遥遥无期
遥遥无期 2020-12-04 13:22

I am trying to realize a Class Based ListView which displays a selection of a table set. If the site is requested the first time, the dataset should be displaye

7条回答
  •  渐次进展
    2020-12-04 14:10

    I think you would be better off doing this via get_context_data. Manually create your HTML form and use GET to retrieve this data. An example from something I wrote is below. When you submit the form, you can use the get data to pass back via the context data. This example isn't tailored to your request, but it should help other users.

    def get_context_data(self, **kwargs):
        context = super(Search, self).get_context_data(**kwargs)
        filter_set = Gauges.objects.all()
        if self.request.GET.get('gauge_id'):
            gauge_id = self.request.GET.get('gauge_id')
            filter_set = filter_set.filter(gauge_id=gauge_id)
    
        if self.request.GET.get('type'):
            type = self.request.GET.get('type')
            filter_set = filter_set.filter(type=type)
    
        if self.request.GET.get('location'):
            location = self.request.GET.get('location')
            filter_set = filter_set.filter(location=location)
    
        if self.request.GET.get('calibrator'):
            calibrator = self.request.GET.get('calibrator')
            filter_set = filter_set.filter(calibrator=calibrator)
    
        if self.request.GET.get('next_cal_date'):
            next_cal_date = self.request.GET.get('next_cal_date')
            filter_set = filter_set.filter(next_cal_date__lte=next_cal_date)
    
        context['gauges'] = filter_set
        context['title'] = "Gauges "
        context['types'] = Gauge_Types.objects.all()
        context['locations'] = Locations.objects.all()
        context['calibrators'] = Calibrator.objects.all()
        # And so on for more models
        return context
    

提交回复
热议问题