代码之家  ›  专栏  ›  技术社区  ›  Ronaldo Lanhellas

从HTML到Python文件调用函数

  •  1
  • Ronaldo Lanhellas  · 技术社区  · 6 年前

    我有一个索引.html带有“卡片”列表的页面,每张卡片都有一个“点击选择”链接。

    当用户单击此链接时,我想调用python中的函数来选择此项,请参见:

    def selectItem(request, item):
        #so something with this item
    

    因此,在我的html页面中:

    <div class="card-action">
                                <a href="{{ selectItem(myitem) }}">Selecionar</a>
                            </div>
    

    这不管用。正确的方法是什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   willeM_ Van Onsem    6 年前

    你不能调用那样的函数。浏览器用HTTP请求请求数据,服务器用(HTTP)响应响应。这样的请求有一个URL,Django可以将请求和URL路由到将计算响应的正确视图。

    因此,我们需要构造一个可以调用的视图。你的电话已经很近了:

    # app/views.py
    
    from django.http import HttpResponse
    
    def select_item(request, item_id):
        # so something with this item_id
        # ...
        return HttpResponse()

    id (例如存储在 对应 一个物体)。

    现在在 urls.py

    # app/urls.py
    
    from django.urls import path
    from app.views import select_item
    
    urlpatterns = [
        path('select_item/<int:item_id>/', select_item, name='select_item_view'),
        # ...
    ]

    这个 urlpatterns 需要包含在根目录中 URL模式

    现在在HTML模板中,我们可以生成与此视图匹配的URL,类似于:

    <div class="card-action">
      <a href="{% url 'select_item_view' item_id=myitem.id %}">Selecionar</a>
    </div>

    Django将确保 href select_item 使用正确的参数查看。