【问题标题】:Django: passing context data between html file in different appsDjango:在不同应用程序的html文件之间传递上下文数据
【发布时间】:2021-10-19 19:23:10
【问题描述】:

如何将在我的一个视图中创建的上下文数据(在他的案例 profile_total 变量中)传递给另一个应用程序的 html 模板? 这是我的代码:

app1.views.py

def view_profile(request):
    profile_total = UserProfile.objects.all().count()
    return render(request, 'profile/user_profile.html', {'profile_total': profile_total})   

app2.stats.html

<div class="container">
<h1> Show </h1>
Profile submitted: {{ profile_total }}
</div>

现在它只显示一个空格,而不是提交的配置文件的数量。谢谢大家的帮助!

【问题讨论】:

  • 你的html不是profile/user_profile.html? (因为你提到了app2.stats.html)。
  • 您确定 (a) 您渲染了正确的模板,并且 (b) 您触发了正确的视图吗?

标签: python html django


【解决方案1】:

您可能正在寻找一个上下文处理器。这是每次渲染模板时都会运行的函数,我们可以使用这样的上下文处理器:

# app_name/context_processors.py

def profile_total(request):
    from app_name.models import UserProfile
    return {'profile_total': UserProfile.objects.all().count}

我们确实在此处调用.count() method [Django-doc] 来推迟评估查询。这样,如果您在模板中渲染 profile_total,我们将只执行数据库查询。

现在我们可以注册上下文处理器了;

# settings.py

# …

TEMPLATES = [
    {
        # …,
        'OPTIONS': {
            'context_processors': [
                # …,
                'app_name.context_processors.profile_total'
            ],
        },
    },
]

如果我们用{{ profile_total }}渲染它,我们可以在所有模板中使用profile_total

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多