File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ from django import forms
2+
3+
4+ class QuickSearchForm (forms .Form ):
5+ search = forms .CharField (max_length = 100 , required = False )
Original file line number Diff line number Diff line change @@ -5,7 +5,8 @@ <h1>Welcome to the Pacific Connect Community Database</h1>
55 On this site, you can find details of members of the Pacific Connect Community Database
66 < br >
77 < form >
8- Search: < input type ="text " name ="search " /> < input type ="submit ">
8+ {{ form.as_p }}
9+ < input type ="submit ">
910 </ form >
1011 {% if search_text %}
1112 Search results for: {{ search_text }}
Original file line number Diff line number Diff line change 22from django .shortcuts import render
33from django .views .generic import DetailView , ListView
44
5+ from .forms import QuickSearchForm
56from .models import Person
67
78# FUNCTION BASED VIEWS
89
9- # Searching the first name and last name fields with text in the search box
10+ # Searching the first name and last name fields using a Django form
1011def list_persons_with_template (request ):
11- search_text = request .GET . get ( "search" )
12+ form = QuickSearchForm ( request .GET )
1213
1314 persons = Person .objects .all ()
14- if search_text :
15- search_filters = models .Q (first_name__icontains = search_text ) | models .Q (
16- last_name__icontains = search_text
17- )
18- persons = persons .filter (search_filters )
19- context = {"object_list" : persons , "search_text" : search_text }
15+ search_text = ""
16+ if form .is_valid ():
17+ search_text = form .cleaned_data ["search" ]
18+ if search_text :
19+ search_filters = models .Q (first_name__icontains = search_text ) | models .Q (
20+ last_name__icontains = search_text
21+ )
22+ persons = persons .filter (search_filters )
23+ context = {"object_list" : persons , "search_text" : search_text , "form" : form }
2024 return render (request , "community_db/person_list_in_base.html" , context )
2125
2226
You can’t perform that action at this time.
0 commit comments