DJANGO – 20 QUERYING DATA WITH A SEARCH FORM

Spread the love

1. In forms.py, create a form to be used for search
[python]
class ComputerSearchForm(forms.ModelForm):
class Meta:
model = Computer
fields = [‘computer_name’, ‘users_name’]
[/python]

2. Import ComputerSearchForm in views.py and update computer_list view to include a search form and POST if statement
[python]
def computer_list(request):
title = ‘List of all computers’
form = ComputerSearchForm(request.POST or None)
context = {
"title": title,
"form": form,
}
if request.method == ‘POST’:
queryset = Computer.objects.all().order_by(‘-timestamp’).filter(computer_name__icontains=form[‘computer_name’].value(),users_name__icontains=form[‘users_name’].value())
context = {
"title": title,
"queryset": queryset,
"form": form,
}
return render(request, "computers_list.html",context)
[/python]

3. Load crispy form tag {% load crispy_forms_tags %} in computer_list.html and add html form with {{form|crispy}} where you want the search form to appear
[python]
<form method="post" action="">
{% csrf_token %}
{{form|crispy}}
<input class="btn btn-primary" type="submit" value="Search" />
</form>
[/python]

4. Update the model to allow blank and null from all the search fields.
[python]
blank=True, null=True
[/python]


Spread the love

About the author

arbadjie

Hi, I'm Abdourahman Badjie, an aspiring developer with obsession for anything coding and networking. This blog is dedicated to helping people learn to develop web applications using django framework.

View all posts

7 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *