单击 HTML 按钮调用 Django
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48438575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call Django on HTML button click
提问by Paul SZ
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 项目创建一个基本的排序函数,但是当我单击“排序”按钮时我不知道如何调用排序函数
Django view:
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:
HTML 按钮:
<button name="sort-btn" id="sort-btn">sort</button>
回答by adnanmuttaleb
you need to wrap your <button>
with <form>
tag, as following snippet:
你需要<button>
用<form>
标签包裹你的标签,如下片段:
<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:
在您的urls.py
模块中,您应该使用views.py
模块中的特定视图指向 actionUrl,如下所示:
from django.urls import path
from . import views
urlpatterns = [
path(actionUrl, views.yourSort),
]
you should more read about request lifecycle on Django:
您应该更多地了解 Django 上的请求生命周期:
- user submit request
- Django tries to get the first match between request's URL and routes defined in
urls.py
- the request is passed to the matched view
- the view get executed, usually this some model processing
- a response (template) is returned by the view as
HttpResponse
- 用户提交请求
- Django 尝试获取请求的 URL 和定义的路由之间的第一个匹配
urls.py
- 请求被传递到匹配的视图
- 视图被执行,通常这是一些模型处理
- 视图返回响应(模板)为
HttpResponse