【问题标题】:How to call a view function with argument from template and return a python object in Django?如何使用模板中的参数调用视图函数并在 Django 中返回 python 对象?
【发布时间】:2016-10-01 05:27:59
【问题描述】:

这里是问题 现在我想用参数从模板/html调用一个视图函数 最喜欢的功能

def function(PageToken,ID):
  '''Do Something Here'''
  comments = [[User1,Comment1],[User2,Comment2]]
  return comments

以及我如何调用这个函数并使用类似

{%for comment in comments %}
  <li>                          
    {{comment.1}}
    {{comment.2}}
  </li>
 {%endfor%}

我不想 重新加载页面 如何做到这一点

【问题讨论】:

  • 你可以使用AJAX来做到这一点。
  • 不需要关闭问题,有明确的原因和代码sn-p

标签: javascript python html ajax django


【解决方案1】:

您可以定义自己的带有参数的自定义模板过滤器。

# in custom_tags.py  
from django import template

register = template.Library()

def build_comments(pagetoken, id):
    # build comments 
    return comments # it can also be queryset  
register.assignment_tag(build_comments)

在模板中:

{% load custom_tags %}

{% build_comments pagetoken id as comments %}
{% for comment in comments %}
    <li>                          
       {{comment.1}}
       {{comment.2}}
    </li>
{% endfor %}

完整文档 ---> here

【讨论】:

  • 谢谢你的回答对我非常有用,但调用 pass 超过 2 个参数,如 {{a|cut:"a" "tt"}} 或 {{a|cut:"a"," tt"}}?
  • @MingChu 是的,您可以传递任意数量的参数。 {% build_comments arg1 arg2 arg3 ... as comments %}
  • 谢谢,这正是我需要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 2022-11-29
  • 1970-01-01
  • 2011-01-08
  • 2013-07-27
  • 2012-09-06
相关资源
最近更新 更多