如何在基本html模板django中创建简单表单 [英] How to create a simple form in the base html template django
问题描述
我有一个包含多个页面的Django应用.像菜单或页脚一样,在所有这些页面中都重复了一些元素,因此我创建了基本模板并添加了这些重复的代码.现在,我想在基础模板的页脚上方有一个表单.但是我不知道如何使它工作.我应该创建一个返回base.html的视图吗?如何在网站的每个页面上继承此表单?请指导我;我有点泡菜!
I have a Django app that contains multiple pages. Like the menu or footer, some elements are repeated in all of these pages, so I created a base template and added these duplicated codes. Now I want to have a form above the footer in the base template. But I don't know how to make it work. Should I make a view that returns the base.html? How can I inherit this form on every page of the website? Please guide me; I'm in a bit of a pickle!
这是我的context_processor:
this is my context_processor :
def base_forms(request):
return {
'info_form': BasedContactForm()
}
这是我的base.html:我将其扩展到所有其他页面:
and this is my base.html: I extend it in all other pages:
<form method="post" action="">
{% csrf_token %}
{{ info_form }}
</form>
这是我的Blog应用视图:
and this is my Blog app views:
def base_info_form(request):
if request.method == 'POST':
info_form = BaseContactForm(request.POST)
if info_form.is_valid():
info_form.save()
return redirect('Home-Page')
else:
info_form = BaseContactForm()
return render(request, '', {'info_form': info_form})
推荐答案
您可以通过设置 TEMPLATES>将一些数据添加到全局上下文中.选项>context_processors
-写作您自己的上下文处理器.
And for extending templates use template tag extends
(Django Docs).
1.将变量添加到上下文中
创建 yourapp/context_processors.py :
from django.conf import settings
from yourapp.forms import MyForm
def base_data(request):
data = {}
# MyForm(request.GET, user=request.user)
data["my_form"] = MyForm()
data["my_email"] = settings.MYEMAIL
return data
并将其添加到 settings.py 中的 context_processors
:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
...
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
'yourapp.context_processors.base_data',
],
},
},
]
现在您可以在任何模板中访问此数据:
Now you can access your this data in any template:
{{ my_form }}, {{ my_email }}
2.扩展模板
您还可以使用模板标签 扩展
( Django文档)来扩展模板:
You can also use template tag extends
(Django Docs) to extend your templates:
template.html
base.html
在template.html中,以下路径将是有效的:
In template.html, the following paths would be valid:
{% extends "base.html" %}
<div class="container">
Some HTML code
</div>
其他信息 TEMPLATES
( Django文档)和 OPTIONS
> ( Django文档)的可用参数.
Additional info TEMPLATES
(Django Docs) and OPTIONS
(Django Docs) available parameters.
更新
views.py :
def contact(request):
if request.method == 'POST':
form = BaseContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('Home-Page')
else:
form = BaseContactForm()
return redirect(request.META.get('HTTP_REFERER'))
urls.py :
path('contact/', views.contact, name='contact'),
这篇关于如何在基本html模板django中创建简单表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!