check if passed context is Empty in Template

Viewed 26

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>
   
2 Answers

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)

Your questions is confused: in your code, it does not exist a STUDENT variable.

you can just check students variable in your template:

{% if not students %}
No results found
{% endif %}
Related