I have my table and filter all set up and working but I wish to have an error functionality added to it in such a way that when I query a data which exist in the db, it should show me the result normally, however, when I input a qs which does not exist, it should show me a message on the table that says "record does not exist" instead of a blank table.
Here is my view:
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from django_tables2 import RequestConfig
from django_tables2.export import TableExport
from .models import Employee
from .models import EmployeeFilter
from .tables import EmployeeTable
@login_required()
def employees(request):
filter = EmployeeFilter(request.GET, queryset=Employee.objects.all())
table = EmployeeTable(filter.qs)
RequestConfig(request).configure(table)
count = Employee.objects.all().count()
male_count = Employee.objects.filter(gender__contains='Male').count()
female_count = Employee.objects.filter(gender__contains='Female').count()
user_count = User.objects.all().count()
export_format = request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response("table.{}".format("csv", "xlsx"))
return render(request, "employees/employees.html", {
"table": table,
"filter": filter,
"count": count,
"male_count": male_count,
"female_count": female_count,
"user_count": user_count,
})
Form Template:
<!--filter form-->
<form action="" class="form form-inline employee-filter-form" method="get">
<legend class="mb-2">Filter employee records</legend>
<div class="fieldWrapper">
{{ filter.form.first_name }}
</div>
<div class="fieldWrapper">
{{ filter.form.last_name }}
</div>
<button aria-expanded="false" aria-haspopup="true"
class="ml-2 btn btn-danger filter-btn" type="submit">
Filter
</button>
</form>
You can handle it in your template. Just check if queryset you are passing is empty or not:
{% if queryset %}
{% for i in queryset %}
{{ i.text }}
{% endfor %}
{% else %}
Error: Queryset is empty!
{% endif %}
As Daniel mentioned above you can do also withou if
but with empty
:
{% for i in queryset %}
{{ i.text }}
{% empty %}
Error: Queryset is empty!
{% endfor %}