From 1e4bc9c1a0397a6b77d4cfb4daac9e107cd822ab Mon Sep 17 00:00:00 2001 From: Simeon J Morgan Date: Thu, 18 Aug 2022 11:59:15 +1000 Subject: [PATCH] Session 10 - Django form --- src/community_db/forms.py | 5 +++++ src/community_db/templates/base.html | 3 ++- src/community_db/views.py | 20 ++++++++++++-------- 3 files changed, 19 insertions(+), 9 deletions(-) create mode 100644 src/community_db/forms.py diff --git a/src/community_db/forms.py b/src/community_db/forms.py new file mode 100644 index 0000000..726140d --- /dev/null +++ b/src/community_db/forms.py @@ -0,0 +1,5 @@ +from django import forms + + +class QuickSearchForm(forms.Form): + search = forms.CharField(max_length=100, required=False) diff --git a/src/community_db/templates/base.html b/src/community_db/templates/base.html index f0d8871..666ebf8 100644 --- a/src/community_db/templates/base.html +++ b/src/community_db/templates/base.html @@ -5,7 +5,8 @@

Welcome to the Pacific Connect Community Database

On this site, you can find details of members of the Pacific Connect Community Database
- Search: + {{ form.as_p }} +
{% if search_text %} Search results for: {{ search_text }} diff --git a/src/community_db/views.py b/src/community_db/views.py index 56ebb50..e46dccc 100644 --- a/src/community_db/views.py +++ b/src/community_db/views.py @@ -2,21 +2,25 @@ from django.shortcuts import render from django.views.generic import DetailView, ListView +from .forms import QuickSearchForm from .models import Person # FUNCTION BASED VIEWS -# Searching the first name and last name fields with text in the search box +# Searching the first name and last name fields using a Django form def list_persons_with_template(request): - search_text = request.GET.get("search") + form = QuickSearchForm(request.GET) persons = Person.objects.all() - if search_text: - search_filters = models.Q(first_name__icontains=search_text) | models.Q( - last_name__icontains=search_text - ) - persons = persons.filter(search_filters) - context = {"object_list": persons, "search_text": search_text} + search_text = "" + if form.is_valid(): + search_text = form.cleaned_data["search"] + if search_text: + search_filters = models.Q(first_name__icontains=search_text) | models.Q( + last_name__icontains=search_text + ) + persons = persons.filter(search_filters) + context = {"object_list": persons, "search_text": search_text, "form": form} return render(request, "community_db/person_list_in_base.html", context)