如何在表单中提交时不在查询中使用空白输入值

时间:2015-07-07 16:59:19

标签: django forms python-3.x django-views

如何让我的表单在查询中使用空白输入数据?

我希望用户能够填写事故ID字段或设备ID字段。我希望用户可以选择将任一字段留空。我希望查询只搜索输入的内容。

例如:如果用户输入事件ID' 6'并离开设备ID'',我希望查询能够使用事件ID。

forms.py

from django import forms
from django.db.models import Q

from .models import Incident
from .models import Equipment


class IncidentForm(forms.Form):
    incident_id = forms.CharField(required=False)
    equipment_id = forms.ModelChoiceField(Equipment.objects.all(), required=False, widget=forms.TextInput)

    #def clean(self):
    # I'd use the clean method to force the user to provide either an incident or equipment value

    def search(self):
        return Incident.objects.filter(
            Q(id=self.cleaned_data['incident_id']) &
            Q(equipment_id=self.cleaned_data['equipment_id'])
        )

views.py

from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render
from .forms import IncidentForm
from django.views.generic.edit import FormView 

from .models import Incident


def index(request):

    template = "index.html"

    if request.method == 'GET':
        form = IncidentForm(request.GET)
        #incident_list = None
        if 'equipment_id' in request.GET or 'incident_id' in request.GET:
        incident_list = None
            if form.is_valid():
                incident_list = form.search()
                context = { "form": form,
                            "incident_list": incident_list}
                return render(request, template, context)
        else:
            # form is empty show all OPEN incidents
            form = IncidentForm()
            incident_list = Incident.objects.filter(open = 'True').order_by('-incident_date_time_reported')
            context = { "form": form,
                        "incident_list": incident_list}
            return render(request, template, context)

2 个答案:

答案 0 :(得分:0)

试试这个:

def search(self):

cust_id = self.cleaned_data['incident_id'] or ''
equip_id =  self.cleaned_data['equipment_id'] or ''
return Incident.objects.filter(
        Q(id=cust_id) &
        Q(equipment_id=equip_id)
    )

答案 1 :(得分:0)

这是Ajay Gupta提供的另一种答案

self.cleaned_data.get('incident_id', '')