Issue
what I'm trying to achieve here is if context is empty or if STUDENT variable is empty, instead of returning all students. it should return none and in template it shows No results found. currently when nothing is stored in q my template render all the students.
in views.
def student_home(request):
q = request.GET.get('q') if request.GET.get('q') != None else ""
students = Student.objects.filter(Q(first_name__icontains=q) | Q(last_name__icontains = q) | Q(grade__icontains=q))
context = {'students': students}
return render(request, 'StudentManager/home.html', context)
search-bar in NAVBAR.
<form class="d-flex" role="search" action='{% url 'student_home' %}'>
<input class="form-control me-2" type="search" name='q' placeholder="Search Student" aria-label="Search">
<button type="submit" class="btn" style="background: #fff2df;">Search</button>
</form>
Solution
You get all students with q = ""
because Student.objects.filter(first_name__icontains="")
means for django return all Student
where first_name
is not None
.
Try this
def student_home(request):
q = request.GET.get('q', None)
if q:
students = Student.objects.filter(Q(first_name__icontains=q) | Q(last_name__icontains = q) | Q(grade__icontains=q))
else:
students = []
context = {'students': students}
return render(request, 'StudentManager/home.html', context)
Answered By - weAreStarsDust
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.