Skip to content

Commit 67997f4

Browse files
committed
Session 10 - Django form
1 parent 4a80446 commit 67997f4

3 files changed

Lines changed: 19 additions & 9 deletions

File tree

src/community_db/forms.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from django import forms
2+
3+
4+
class QuickSearchForm(forms.Form):
5+
search = forms.CharField(max_length=100, required=False)

src/community_db/templates/base.html

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff 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 }}

src/community_db/views.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,25 @@
22
from django.shortcuts import render
33
from django.views.generic import DetailView, ListView
44

5+
from .forms import QuickSearchForm
56
from .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
1011
def 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

0 commit comments

Comments
 (0)