Skip to content

Commit

Permalink
Session 10 - Django form
Browse files Browse the repository at this point in the history
  • Loading branch information
wsot committed Aug 18, 2022
1 parent 8fb5d86 commit 1e4bc9c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
5 changes: 5 additions & 0 deletions src/community_db/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django import forms


class QuickSearchForm(forms.Form):
search = forms.CharField(max_length=100, required=False)
3 changes: 2 additions & 1 deletion src/community_db/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ <h1>Welcome to the Pacific Connect Community Database</h1>
On this site, you can find details of members of the Pacific Connect Community Database
<br>
<form>
Search: <input type="text" name="search" /><input type="submit">
{{ form.as_p }}
<input type="submit">
</form>
{% if search_text %}
Search results for: {{ search_text }}
Expand Down
20 changes: 12 additions & 8 deletions src/community_db/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down

0 comments on commit 1e4bc9c

Please sign in to comment.