Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Django on HTML button click

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>
like image 238
Paul SZ Avatar asked Jan 25 '18 08:01

Paul SZ


1 Answers

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
like image 143
adnanmuttaleb Avatar answered Oct 05 '22 23:10

adnanmuttaleb