在HTML按钮上调用Django单击 [英] Call Django on HTML button click

查看:468
本文介绍了在HTML按钮上调用Django单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Django项目创建基本的排序功能,但是当我单击排序"按钮时,我不知道如何调用排序功能

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视图:

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 name="sort-btn" id="sort-btn">sort</button>

推荐答案

您需要使用<form>标签包装<button>,如下所示:

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

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

,并且在您的urls.py模块中,应从views.py模块中指向具有特定视图的actionUrl,如下所示:

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),
]

您应该详细了解Django上的请求生命周期:

you should more read about request lifecycle on Django:

  1. 用户提交请求
  2. Django尝试获取请求的URL和urls.py
  3. 中定义的路由之间的第一个匹配项
  4. 请求已传递到匹配的视图
  5. 视图得到执行,通常需要进行一些模型处理
  6. 视图返回的响应(模板)为HttpResponse
  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

这篇关于在HTML按钮上调用Django单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆