Django:是否可以从 ASP.NET MVC 等模板调用视图

Django: is this possible to call view from template like ASP.NET MVC

我正在研究 Django 框架。我正在搜索从模板调用视图的函数。

在Asp.NET MVC中,我们可以通过这种方式从视图(模板)调用动作(视图)。

@Html.Action("Controller Name", "Action Name") or

@Html.Action("Action Name")

简单来说,我想在其他模板中获取模板html。

def index(request):
    return render(request, 'index.html')

def my_list(request):
    q = MyModel.objects.all()
    return render(request, 'mylist.html',{'my_list':q})

index.html

<html>
<head></head>
<body>

#want to call my_list view

</body>
</html>

mylist.html

<script>
    #lot of script here
</script>

{% for record in my_list %}
    <p>{{ record }}</p>
{% endfor %}

我从搜索中得到的解决方案使用 html 表单或 jquery post 或获取请求。

my_list 视图包含查询集对象。我不想在索引视图中直接调用此查询。这是局部视图。

此类问题有哪些解决方案?

谢谢

这是可行的,但似乎您正在尝试重新发明 inclusion template tags

@register.inclusion_tag('mylist.html')
def my_list():
    q = MyModel.objects.all()
    return {'my_list': q}

然后在index.html:

<html>
    {% load my_tags %}
    <head></head>
    <body>
        {% my_list %}
    </body>
</html>

使用 include 标签。 您可以使用 with 语句将上下文传递给模板。
这与 @Html.Action 不同,但非常相似。
https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#include