[Answered ]-Dynamic Django urls redirects to the wrong function

1👍

Django URL dispatcher doesn’t look at GET or POST parameters while resolving the handler.

What you need is to access request.GET mapping in the view: Django request get parameters

In your case, the view definition would look like:

urls.py

urlpatterns = [
    path('', views.exploreComplaints, name='explore-complaints'),
]

views.py

def exploreComplaints(request):
    complaints = Complaint.objects.all()
    sorting_parameter = request.GET.get("sort_by")
    if sorting_parameter == "name":
        complaints = sorted(complaints, key=lambda x: x.complaint_name)
    else:
        complaints = sorted(complaints, key=lambda x: x.complaint_upvotes, reverse=True)
    context = {'complaints':complaints}
    return render(request, 'complaints/complaints.html', context)


# or, to offload sorting on the database:

def explore_complaints(request):
    # distinguish the model field to sort by
    sorting_parameter = request.GET.get("sort_by")
    ordering_param = "-complaint_upvotes"  # default ordering

    if sorting_parameter == "name":
        ordering_param = "complaint_name"

    # add ORDER BY clause to the final query
    complaints = Complaint.objects.order_by(ordering_param)

    context = {"complaints": complaints}
    return render(request, "complaints/complaints.html", context)

Leave a comment