【问题标题】:how to return multiple file html in render request django?如何在渲染请求django中返回多个文件html?
【发布时间】:2021-10-19 07:47:55
【问题描述】:

我想在 django 视图中返回多个 html 文件中的多个值 我试过了,但这是一个错误

def my_view(request):
#bla bla bla...
context ={
   'value_1':value,
    #....
}
return  render(request,{'file_1.html','file_2.html','file_2.html'},context)

我已经将它分成 3 个不同的视图,但问题是它们具有相同的源,如果我将它们分开,我有 4 分钟的执行时间,那么最好将它们组合起来

【问题讨论】:

  • 每次渲染一次只能使用一个文件。也许将它们合二为一?
  • 你可以在项目的urls.py中导入views.py文件夹并添加路径为path('', views.index, name='index'),然后通过url调用html页面而不是渲染
  • 我们如何做到这一点?我没试过

标签: django django-views django-templates


【解决方案1】:

urls.py

from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.values2, name='values1'),
    path('value2/', views.values2, name='values2'),
]

从这里你可以调用所有的 html 页面而不会给服务器带来负载

【讨论】:

  • 在我看来我这样做了,但我认为这不是我想要的,但我想要的是在不同的 html 文件中返回很多大约 10 的变量
  • 'value_1':value, 'value_2':value, in htm1: value1 会被调用,在 htm2: value2 会被调用是这样的
【解决方案2】:

您只需使用内置功能即可实现此目的。

def my_view(request):
...
context ={
   'template1_context':value1,
   'template2_context':value2,
   'template3_context':value3,
}
return  render(request,'main_template.html',context)

在你的main_template.html

{% include "template2.html" with template2_variable=template2_context %}
{% include "template3.html" with template3_variable=template3_context %}

【讨论】:

  • 是的,这就是我想要的,导出另一个模板中的值以最大限度地减少执行时间你的代码的问题是它在 main_template.html 中包含 template2.html 的所有内容我们只想要值
  • 使用 django render 一次渲染多个 html 模板是不可能的。因此,要么您只渲染一个具有单独值的 html 模板,要么使用一个 html 并使用 AJAX 请求调用不同的视图来填充您的 value2 和 value3。
猜你喜欢
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-10
  • 2011-11-29
  • 2021-09-25
  • 2012-02-11
  • 1970-01-01
相关资源
最近更新 更多