单击 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:05:01  来源:igfitidea点击:

Call Django on HTML button click

htmldjangofunctionsorting

提问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.pymodule you should point the actionUrl with specific view from the views.pymodule 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 上的请求生命周期:

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