How to not use blank input values in a query when submitted in a form


How do I not let my form use blank inputted data in a query?

I want the user to be able to fill in either the Incident ID field or the Equipment ID field. I want the user to have the option to leave either field blank. I want the query to search only what is inputted.

For example: If a user enters in Incident ID '6' and leaves Equipment ID '', I want the query to work using Incident ID.

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']) &

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 =
                context = { "form": form,
                            "incident_list": incident_list}
                return render(request, template, context)
            # 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)


Try this:

def search(self):

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

this is an alternate form of the answer provided by Ajay Gupta

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

This video can help you solving your question :)
By: admin