gpt4 book ai didi

Django 如何重用所有 View 共有的 View 功能

转载 作者:行者123 更新时间:2023-12-04 03:14:38 26 4
gpt4 key购买 nike

我有一个 Django 模板,我们称它为 index.html,它分为 3 个部分(页眉、内容和页脚)。在标题部分,我有一个搜索栏,其中包含一个下拉菜单,允许用户从中选择一个选项并根据所选选项搜索内容。我希望该标题部分包含在我 future 的所有 View /模板中,并且仍然显示包含所有选项的下拉菜单。

这是我目前在我的 View 文件中的内容

def index(request):
return render(
request,
'home.html',
{'categories': get_all_categories()}
)


def cart(request):
return render(request, 'cart.html', {'categories': get_all_categories()})


def help(request):
return render(request, 'help.html', {'categories': get_all_categories()})


def about(request):
return render(request, 'about.html', {'categories': get_all_categories()})


def contact(request):
return render(request, 'contact.html', {'categories': get_all_categories()})


def search(request):
return render(request, 'search.html', {'categories': get_all_categories()})


def get_all_categories():
return Category.objects.all()

这就是我的cart.html {% 扩展 "index.html"%}

{% block content %}

<div>
<h1> My Cart </h1>
</div>

{% endblock %}

这是 contact.html 的内容 {% 扩展 "index.html"%}

{% block content %} 

<div>
<h1> Contact </h1>
</div>

{% endblock %}

这是 home.html 包含的内容 {% 扩展 "index.html"%}

{% block content %}

<div>
<h1> Home </h1>
</div>

{% endblock %}

这现在有效,但我想知道是否有更好的方法来解决这个问题,这样我就不必在所有 View 中重复相同的代码。

最佳答案

你可以写一个自定义 context processor在您呈现的每个模板中包含该变量。

例如,编写如下所示的上下文处理器(在 context_processors.py 中,例如):

def category_context_processor(request):
return {
'categories': get_all_categories(),
}

并将其包含在 settings.py 中:

TEMPLATES = [
...
'OPTIONS': {
'context_processors': [
...
'myapp.context_processors.category_context_processor',
],
},
}

现在,变量 categories 在您呈现的每个模板中都可用(无论如何使用 render 调用或 RequestContext),无论您实际从 View 传递的上下文。

关于Django 如何重用所有 View 共有的 View 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42173712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com