Applications that connects to a database to store data often times need to fetch data by searching the database matching the users search criteria.
Therefore, in this blog, we will configure our application (Invoice management system) to allow the users to search data. We will implement searching by invoice_name and or name of the customer. This means that the users can search for either the invoice number alone, customer name alone or both at the same time.
Below is all the step we will be following, including the codes needed to implement search option.
1. Make a form in forms.py
class InvoiceSearchForm(forms.ModelForm):
class Meta:
model = Invoice
fields = ['invoice_number', 'name']
2. Import the form and add it to the view with a condition that will determine when the search/query will be executed.
form = InvoiceSearchForm(request.POST or None)
if request.method == 'POST':
queryset = Invoice.objects.filter(invoice_number__icontains=form['invoice_number'].value(),
name__icontains=form['name'].value()
)
context = {
"form": form,
"title": title,
"queryset": queryset,
}
3. Add the form to the list_invoice.html
tamplate
NOTE: Make sure {% load crispy_forms_tags %}
is loaded since we are using crispy to style the form.
<form method='POST' action=''>{% csrf_token %}
{{form|crispy}}
<input type="submit" value='Search'/>
</form>
<br>