Dynamic Django urls redirects to the wrong function

Milanor

So what I am trying to do is create urls such that the user can see complaints either by passing a particular parameter or sort by upvotes by default if no parameter is passed.

urls.py

path('', views.exploreComplaints, name='explore-complaints'),
path('?sort_by=<str:sorting_parameter>/', views.exploreComplaints, name='explore-complaints-by-parameter'),

views.py

def exploreComplaints(request, sorting_parameter="upvotes"):
    complaints = Complaint.objects.all()
    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)

The sorting parameter does not work when I go to a URL, the value of sorting_parameter is always upvotes, even when I go to a url with ?/sort_by=name in the end. Where am I wrong?

Edit: Complaint Model:

class Complaint(models.Model):
    complaint_title =                   models.CharField(max_length = 1000, null = True)
    complaint_filer =                   models.ForeignKey(User, null = True, on_delete = models.CASCADE)
    complaint_description =             models.TextField(null = True)
    complaint_status =                  models.CharField(max_length = 10, default = 'active')
    complaint_request_image =           models.ImageField(null = True, blank = True, upload_to = 'complaints', default = 'complaints/default-image.jpg')
    complaint_place =                   models.CharField(max_length = 1000, null = True)
    complaint_under_investigation_by =  models.CharField(max_length = 1000, null = True, blank = True)
    complaint_upvotes =                 models.IntegerField(default = 0)
    complaint_upvotes_users =           models.TextField(default=',', blank = True)
    complaint_downvotes_users =         models.TextField(default=',', blank = True)
    tags = TaggableManager()

    def __str__(self):
        return self.complaint_title
Savva Surenkov

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Excluding URLs from Django redirects

Django pagination for dynamic urls

Django urls dont work redirects to single url

Django : Fetch API redirects to wrong URL

Firebase Function with Firebase Hosting redirects to wrong URL

Dynamic URLs for hierarchy tree on Django

How to make Django The redirects app higher than urls.py?

Why is Django is looking at wrong urls file?

Django urls multiple parameters matching to wrong pattern

Django URLs file redirecting the different URLs to the wrong html files

The form editing the existing form does not save and redirects to wrong. Django

Wrong redirects when using defaultRouter() for ModelViewSet in Django-REST-framework

URLS Redirects with Cypress automation

Request goes to the wrong function in Django

Rails redirects to the wrong address

HTML Redirects to wrong

Django: sidebar with dynamic URLs: how to dynamically create URLs which have dynamic folders in the path

Is there anything wrong with my Django urls.py code?

Django views function skip urls keywords

Scrapy redirects to homepage for some urls

301 redirects for some of the urls not working

Dynamic htaccess redirects in WordPress

Django urls.py: passing dynamic url parameter into include()

How to write dynamic (Django) URLs for serving images using Whitenoise on Heroku?

Django serving wrong template at the wrong address with malformed urls.py (redactor app)

execute api function on button click using Django urls - Django/Python

Anchor tag redirects to wrong path

React Router redirects to wrong page

Button redirects the wrong form in HTML