Search code examples
djangodjango-filters

Filter with ChoiceField (Django)


forms.py

status_list = (
    ('', ''),
    ('c', 'cancelado'),
    ('elab', 'em elaboração'),
    ('p', 'pendente'),
    ('co', 'concluido'),
    ('a', 'aprovado')
)

class StatusSearchForm(forms.Form):
    status = forms.ChoiceField(
        choices=status_list, widget=forms.Select(attrs={'class': 'form-control'}))

template

Status {% for radio in status_search_form.status %} {{ radio }} {% endfor %}

views.py

class ProposalList(ListView):
    template_name = 'core/proposal/proposal_list.html'
    model = Proposal
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(ProposalList, self).get_context_data(**kwargs)
        context.update({'status_search_form': StatusSearchForm(), })
        return context

    def get_queryset(self):
        p = Proposal.objects.all().select_related()
        q = self.request.GET.get('search_box')
        if q is not None:
            try:
                p = p.filter(
                    Q(id__icontains=q) |
                    Q(work__name_work__icontains=q) |
                    Q(work__customer__first_name__icontains=q) |
                    Q(category__category__startswith=q) |
                    Q(employee__user__first_name__startswith=q) |
                    Q(seller__employee__user__first_name__startswith=q) |
                    Q(created__year=q))
            except ValueError:
                pass
        s = self.request.GET.get('status')
        if s is not None:
            p = p.filter(status__exact=s)
        elif s == '':
            p = p
        return p

Question: I wanted when I chose the first option of 'status' , which in this case is empty, he returned all records normally , the problem is that it is returning

http://localhost:8000/proposal/?status=&search_box=

And it does not return anything . But in this case I want to return all .

What would be the best solution?


Solution

  • def get_context_data(self, **kwargs):
            status_classes = {'c': 'fa-close status-cancelado',
                              'elab': 'fa-circle status-elab',
                              'p': 'fa-circle status-pendente',
                              'co': 'fa-check status-concluido',
                              'a': 'fa-star status-aprovado'}
            context = super(ProposalMixin, self).get_context_data(**kwargs)
            context.update({'status_search_form': StatusSearchForm(), })
            context['status'] = [(item, item_display, status_classes[item])
                                 for item, item_display in STATUS_FILTER]
            return context
    
        def get_queryset(self):
            super(ProposalMixin, self).get_queryset()
            p = Proposal.objects.select_related().all()
    
            status = self.request.GET.get('status')
            if status in ('c', 'elab', 'p', 'co', 'a'):
                p = p.filter(status=status)
    
            # http://pt.stackoverflow.com/a/77694/761
            q = self.request.GET.get('search_box')
            if not q in [None, '']:
                p = p.filter(
                    Q(id__startswith=q) |
                    Q(work__name_work__icontains=q) |
                    Q(work__customer__first_name__icontains=q) |
                    Q(category__startswith=q) |
                    Q(employee__first_name__startswith=q))
    return p