9

I'm trying to make a basic sort function for a Django project, but I don't know how to call the sort function when I click the 'sort' button

Django view:

def sort_btn(request):
if request.GET.get('sort-btn'):
    cits = Citizen.objects.all().order_by('name')
return render_to_response(request, 'civil_reg/index.html', {'cits': cits})

HTML button:

<button name="sort-btn" id="sort-btn">sort</button>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Paul SZ
  • 127
  • 1
  • 2
  • 12
  • this is lead to KeyError since there is no sort-btn value was passed in the request. You need to atleast create a html input control with a value and send a request – Shift 'n Tab Jan 25 '18 at 08:34
  • This answer would help [here](https://stackoverflow.com/questions/17599035/django-how-can-i-call-a-view-function-from-template/19761466#19761466) – Aditya Rajgor Jan 08 '22 at 16:06

2 Answers2

22

you need to wrap your <button> with <form> tag, as following snippet:

<form action='actionUrl' method='GET'>
<button type='submit'> sort me</button>
</form>

and in your urls.py module you should point the actionUrl with specific view from the views.py module as follow:

from django.urls import path

from . import views

urlpatterns = [
    path(actionUrl, views.yourSort),
]

you should more read about request lifecycle on Django:

  1. user submit request
  2. Django tries to get the first match between request's URL and routes defined in urls.py
  3. the request is passed to the matched view
  4. the view get executed, usually this some model processing
  5. a response (template) is returned by the view as HttpResponse
adnanmuttaleb
  • 3,388
  • 1
  • 29
  • 46
  • Thanks so much. One question, now I made an entirely new webpage ('action URL') for sorting by name, will I have to do another three pages if -say- I wanted to make another three sort functions? Or is there a better way? – Paul SZ Jan 25 '18 at 09:50
  • 2
    you are welcome, no you do not have to create three templates, you just assign a different value in each view to your 'cits' key in the context object. as clarification: {'cits': byNamecits} {'cits': byAreacits}...etc. – adnanmuttaleb Jan 25 '18 at 12:00
2

I don't know about your program but my implementation is the full as it is that worked.

<button name="button" type="submit" onclick="location.href='{% url "actionUrl" %}'"> Send</button>

I am trying to call a function in views named "sendEmail"

path('actionUrl/', views.sendEmail,name='actionUrl')

And above one is the line which I included in urls file.

ChaddRobertson
  • 605
  • 3
  • 11
  • 30
Kush Singla
  • 355
  • 3
  • 7