【问题标题】:render multiple template from a single view in django从 django 中的单个视图呈现多个模板
【发布时间】:2018-09-29 12:08:31
【问题描述】:

我想将上下文数据发送到一个 html 并希望呈现不同的 html。 登录后用户被重定向到此仪表板视图。这里我想渲染两个 html 文件,上下文值将被发送到一个 html 比如说 temp1.html 文件,但用户可以看到 temp2.​​html 文件。在 temp2.​​html 和其他 html 文件中,我将包含 temp1.html 文件。有什么办法吗? 视图.py

def dashboard(request):
    print('in dashboard view')
    object = UserSelection.objects.get(user=request.user)

    if object.user_type == 'candidate':
        val_cand = CandidateDetail.objects.filter(candidate_username=request.user)
        if val_cand:
            print('Candidate filled data') #Already filled data
            data = CandidateDetail.objects.get(candidate_username=request.user)
            return render(request, 'dashboard.html',{'obj':object.user_type, 'data':data})
        else:
            print('new user') #Registered but not filled data
            return render(request, 'dashboard.html', {'obj':object.user_type})

    else:
        val_emp = EmployerDetail.objects.filter(name=request.user)
        if val_emp:
            print('Employer filled data') #Already filled data
            data = EmployerDetail.objects.get(name=request.user)
            return render(request, 'dashboard.html',{'obj':object.user_type, 'data':data})
        else:
            print('new user') #Registered but not filled data
            return render(request, 'dashboard.html', {'obj':object.user_type})

【问题讨论】:

  • 你能解释一下如何在一个 html 中显示两个 html 文件吗?
  • 我将上下文数据发送到 temp1.html 文件,根据某些条件会有一些价值。我的项目中有很多 html 文件,我将使用 {% include 'file_name' %} 标签包含 temp1.html 文件。 @Raja Simon
  • 如果parent html 文件可以访问variable 通过视图发送功能,那么child html 文件也可以访问它。那是你要的吗。?或者您想将其他变量传递给子 html 吗?
  • 是的,但在同一个视图中,我希望用户被重定向到 temp2.​​html 文件,并且只有数据将被发送到 temp1.html 文件。 def dash(request): val_cand = CandidateDetail.objects.get(candidate_username=request.user) return render(request, 'temp2.​​html') return render(request, 'temp1.html', {'value':val_cand})我想要这样的东西@Raja Simon
  • 重定向是什么意思?这太令人困惑了,这个问题可能因为Unclear what you are asking 而很接近请用更多信息编辑您的问题...

标签: django python-3.x django-templates django-views


【解决方案1】:

您不能在单个视图中呈现两个 html 文件。请为所需的行为使用 Django 模板语言。

即)如果您将obj 传递给dashboard.html 并且内部的html文件也可以访问obj。

dashboard.html

{{ obj }}

{% include 'test1.html' %}
{% include 'test2.html' %}

您可以使用关键字参数向模板传递额外的上下文:

{% include 'test1.html' with obj=obj additional_context='blah' %}

test1.html

{{ obj }} 

【讨论】:

    猜你喜欢
    • 2014-11-26
    • 1970-01-01
    • 2019-03-10
    • 2019-11-14
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多