如何使用可以为空的CheckboxSelectMultiple创建搜索

时间:2018-07-10 14:59:33

标签: django search

嗨,我正在尝试创建一个搜索,它会有一些CheckboxSelectMultiple。问题是,当该字段之一为空时,它在/ technology /处返回错误MultiValueDictKeyError,但是当我选择每个字段之一时,它均能正常工作,但是当我尝试进行分页时,在/ technology /处也收到此错误MultiValueDictKeyError

form.py

class TechnologySearchForm(forms.Form):
    CATEGORY_CHOICES = (
        (0,'Acabada'),
        (1,'Em Desenvolvimento'),
    )

    KIND_CHOICES = (
        (0, 'Produto'),
        (1, 'Processo'),
        (2, 'Software')
    )
    PATENT_CHOICES = (
        (0,'Depositada'),
        (1,'Licenciada'),
        (2,'Não Possui')
    )
    PATENT_TYPE_CHOICES = (
        (0, 'Patente De Invenção'),
        (1, 'Modelo de Utilidade')
    )


    title = forms.CharField(label="Título", max_length=50, required=False, widget=forms.TextInput(attrs={'class':'form-control'}))
    description = forms.CharField(label="Descrição", max_length=50, required=False,  widget=forms.TextInput(attrs={'class':'form-control'}))
    application_area = forms.CharField(label="Área de Aplicação", max_length=50, required=False,  widget=forms.TextInput(attrs={'class':'form-control'}))
    category = forms.ChoiceField(label="Categoria", choices=CATEGORY_CHOICES, widget=forms.CheckboxSelectMultiple(),required=False)
    kind = forms.ChoiceField(label="Tipo de Tecnologia", choices=KIND_CHOICES, widget=forms.CheckboxSelectMultiple(),required=False)
    patent = forms.ChoiceField(label="Patente", choices=PATENT_CHOICES, widget=forms.CheckboxSelectMultiple(),required=False)
    patent_type = forms.ChoiceField(label="Tipo de Patente", choices=PATENT_TYPE_CHOICES, widget=forms.CheckboxSelectMultiple(),required=False)

我的列表视图

class TechnologyListView(LoginRequiredMixin, ListView):
    model = Technology
    template_name = "technology/technology.html"
    paginate_by = 6


    def get_context_data(self, **kwargs):
        data = super(TechnologyListView, self).get_context_data(**kwargs)
        data['imagearea'] = self.request.GET
        data["filter_form"] = TechnologySearchForm(self.request.GET)
        return data

    def get_queryset(self, *args, **kwargs):
        qs = super(TechnologyListView, self).get_queryset(*args, **kwargs) 
        query = self.request.GET
        queryset = Technology.objects.filter(user=self.request.user)
        if query:
            qs = queryset.filter(
                Q(title__icontains=query['title']) &
                Q(description__icontains=query['description']) &               
                Q(category__in=query['category']) |
                Q(kind=query['kind']) |
                Q(patent__exact=query['patent']) |
                Q(patent_type__exact=query['patent_type'])
            )
         return qs

我的html

{% extends "techbase.html" %}
{% load static %}
{% block content %}
{% include "includes/carousel.html" %}
    <br>
    <div class="container-fluid" >
        <div class="row">
            <div class="col-sm-2">
                <div style="margin-top:15% ">
                    <h1 class="title text-center">Filtro:</h1>
                    <form method="GET" action="{% url 'technology:tech_index' %}" novalidate>
                        {{ filter_form }}   
                        <br>                  
                        <input type='submit' value='Procurar' class='btn'>                    
                        <a class="btn btn-primary" href="{% url 'technology:tech_index' %}">Limpar Filtro</a>
                    </form>
                </div>

            </div>
            <div class="col-sm-10">
                <ul class="nav nav-pills nav-pills-shop">
                    <li class="mr15 active">
                        <a href="{% url 'technology:create_tech' %}"><i class="fa fa-bolt">
                        </i>Adicionar Tecnologia</a>                            
                    </li>
                </ul>
                <h1 class="title text-center">Minhas Tecnologias</h1>
                <div class="tab-content tab-shop mt15">
                    <div id="home" class="tab-pane row fade in active">
                        {% for item in object_list %}        
                        <div class="col-lg-4 col-md-4 col-sm-6 mb30">
                                <div class="view  no-margin" style="background-color: #cfcfcf">
                                    <!-- Blog Thumb -->
                                    <div class="product-container">

                                        {% if item.area_img %}                                                      
                                            <img class="img-responsive full-width" style="width:100%; height:200px" src="{{item.area_img.image.url}}" alt="..."> 
                                        {% else %}
                                            <img class="img-responsive full-width" style="width:100%; height:200px" src="{% static 'images/notavailable.png' %}" alt="...">                                                
                                        {% endif %}                                                                                          

                                    </div>
                                    <div class="mask">
                                        <div class="image-hover-content">
                                            <!-- Zoom + Blog Link -->
                                            <a href="{% url 'technology:detail_tech' item.pk %}"  >
                                                <div class="image-icon-holder"><span data-toggle="tooltip" data-placement="top" title="Visualizar" class="ion-eye image-icons"style="color:#fff"></span></div>
                                            </a>
                                            <a href="{% url 'technology:update_tech' item.pk %}">
                                                <div class="image-icon-holder"><span  data-toggle="tooltip" data-placement="top" title="Editar" class="ion-edit image-icons" style="color:#fff"></span></div>
                                            </a>
                                            <a data-toggle="modal" data-target="#delete-{{item.pk}}">
                                                <div class="image-icon-holder"><span data-toggle="tooltip" data-placement="top" title="Deletar" class="ion-ios7-trash image-icons" style="color:red"></span></div>
                                            </a>

                                            <div class="modal fade" id="delete-{{item.pk}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                                                <div class="modal-dialog" role="document">
                                                    <div class="modal-content text-center">
                                                    <form action="{% url 'technology:delete_tech' pk=item.pk %}" method="post">
                                                        {% csrf_token %}
                                                        <div class="modal-header">
                                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                                            <h2>Deletar</h2>
                                                        </div>
                                                        <div class="modal-body">
                                                            <p>Você deseja realmente deletar "{{ item }}"?</p>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-success" data-dismiss="modal">Voltar</button>
                                                            <input class="btn btn-danger" type="submit" value="Confirmar" />
                                                        </div>
                                                    </form>
                                                    </div>
                                                </div>
                                            </div>

                                        </div><!-- /image hover content -->
                                    </div><!-- /mask-->
                                </div>
                                <div class="shop-product content-box-shadow">
                                    <a href="{% url 'technology:update_tech' item.pk %}"><h2>{{item.title}}</h2></a>
                                    <p>{{item.description|truncatechars:40}}</p>
                                </div>
                            </div>
                            {% if forloop.counter|divisibleby:4 %}
                            </li>
                            <li>
                            {% endif %}
                    {% endfor %}
                </div>
            </div>
            {% include "includes/paginator.html" %}
        </div>
    </div>
{% endblock content %}

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试一下,选择为空时解决方案

https://gist.github.com/davidbgk/651080