如何在每个视图中呈现联系人(Django)
联系人表格放在页脚。大多数不同的视图都有页脚部分如何在每个视图中呈现联系人(Django),django,django-forms,django-views,Django,Django Forms,Django Views,联系人表格放在页脚。大多数不同的视图都有页脚部分 def about-page(request): return render(request, 'about.html') def faq-page(request): return render(request, 'faq.html') def home-page(request): return render(request, 'home.html') 以上所有模板都有“包含”页脚部分: {% include 'foot
def about-page(request):
return render(request, 'about.html')
def faq-page(request):
return render(request, 'faq.html')
def home-page(request):
return render(request, 'home.html')
以上所有模板都有“包含”页脚部分:
{% include 'footer.html' %}
这还包括联系方式:
{% include 'contact.html' %}
所以,现在如果我想在所有页面上呈现联系人表单,我必须在上下文中传递它。比如:
def about-page(request):
form = ContactForm()
return render(request, 'about.html',{'form':form})
def faq-page(request):
form = ContactForm()
return render(request, 'faq.html',{'form':form})
def home-page(request):
form = ContactForm()
return render(request, 'homeabout.html',{'form':form})
是否有任何通用功能,我可以通过不重复将表单添加到所有页面。因为我可以访问整个站点中的许多页面。如果它是一个函数,我看不到任何扩展的方法。您是否考虑过切换到基于类的视图?这样,您可以执行以下操作:
类基本视图(FormView):
form=ContactForm()
班级主页(BaseView):
模板名称='home.html'
类常见问题解答页面(BaseView):
模板名称='faq.html'
在本例中,BaseView将是包含表单的父视图,您可以在所有子类中使用它。BaseView继承的FormView是Django用于呈现表单的默认通用视图之一
提示:在URL中使用基于类的视图时,请记住添加。as_view()
函数:
urlpatterns=[
路径(“”,views.HomePage.as_view(),name='home'),
]
您可以使用来完成此操作:
from django.views import View
class BaseView(TemplateView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['contact_form'] = ContactForm()
return context
现在,在继承自BaseView
的其他视图中,联系人表单
将自动添加到上下文中
class AboutView(BaseView):
template_name = 'about.html'
class FaqView(BaseView):
template_name = 'faq.html'
class HomeView(BaseView):
template_name = 'home.html'
如果确实希望使用基于函数的视图,可以编写自己的上下文处理器()
在文件myapp/context.py
中:
def my_context_processor(request):
return {'contact_form': ContactForm()}
现在,在settings.py
中,将上下文处理器添加到TEMPLATES
选项列表中,如下所示:
TEMPLATES = [
{
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'myapp.context.my_context_processor'
],
},
},
]
这种方法唯一的缺点是,
联系人表单将插入每个视图的上下文中,这在您的情况下可能并不重要。如果您想坚持使用函数,请使用部分:
从functools导入部分
def模板和联系人表单(模板、请求):
返回呈现(请求,模板,{“表单”:ContactForm()})
about=部分(带有联系人表单“about.html”的模板)
我知道我可以使用CBV。但我在整个项目中都使用了FBV,我不想失去规律性和一致性。这就是为什么,我想知道我是否可以用FBV做些什么。你的答案也很好,很有效,但我在整个项目中都使用了FBV,我不想失去规律性和一致性。这就是为什么,我想知道我是否可以对FBV做些什么,有什么建议吗?