为什么 {{ form }} 代表模板文件中的表单实例?
Why {{ form }} represents a form instance in template file?
All you need to do to get your form into a template is to place the form instance into the template context. So if your form is called form in the context, {{ form }}
will render its <label>
and <input>
elements appropriately.
django 源代码中模板上下文的表单实例 named/defined as form
在哪里?以及如何将名称更改为其他名称 {{ my_form }}
例如?
在 Views.py 中呈现视图时,您可以执行以下操作来更改您呈现的表单的名称:
Views.py
from .forms import MyForm1
def MyForm(request):
my_form = Myform1
return render(request , 'MyForm.html' , {'my_form' : my_form})
然后在 HTML 页面上调用您的表单时,您可以将其调用为
{{ my_form }}
正如你在 中所说的那样:
Context means the repository of data used for rendering via HTML
template files.
至于如果您使用基于函数的视图,如何将 form
传递给上下文,这完全取决于您传递表单的键,例如下面的代码将它传递为 my_form
:
return render(request, 'template.html', {'my_form': my_form})
如果是基于 class 的视图,它们中的大多数继承自 ContextMixin
,后者声明用于将变量传递到上下文中的方法 get_context_data
。所有处理表单的基于 class 的视图也继承自 FormMixin
,查看它的 source code 它会覆盖 get_context_data
以将表单传递到上下文中:
def get_context_data(self, **kwargs):
"""Insert the form into the context dict."""
if 'form' not in kwargs:
kwargs['form'] = self.get_form()
return super().get_context_data(**kwargs)
当然,您可以决定自己再次覆盖 get_context_data
并使用其他名称传递表单,但这样做不是很有用:
class YourView(CreateView):
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['my_form'] = context['form']
return context
All you need to do to get your form into a template is to place the form instance into the template context. So if your form is called form in the context,
{{ form }}
will render its<label>
and<input>
elements appropriately.
django 源代码中模板上下文的表单实例 named/defined as form
在哪里?以及如何将名称更改为其他名称 {{ my_form }}
例如?
在 Views.py 中呈现视图时,您可以执行以下操作来更改您呈现的表单的名称:
Views.py
from .forms import MyForm1
def MyForm(request):
my_form = Myform1
return render(request , 'MyForm.html' , {'my_form' : my_form})
然后在 HTML 页面上调用您的表单时,您可以将其调用为
{{ my_form }}
正如你在
Context means the repository of data used for rendering via HTML template files.
至于如果您使用基于函数的视图,如何将 form
传递给上下文,这完全取决于您传递表单的键,例如下面的代码将它传递为 my_form
:
return render(request, 'template.html', {'my_form': my_form})
如果是基于 class 的视图,它们中的大多数继承自 ContextMixin
,后者声明用于将变量传递到上下文中的方法 get_context_data
。所有处理表单的基于 class 的视图也继承自 FormMixin
,查看它的 source code 它会覆盖 get_context_data
以将表单传递到上下文中:
def get_context_data(self, **kwargs): """Insert the form into the context dict.""" if 'form' not in kwargs: kwargs['form'] = self.get_form() return super().get_context_data(**kwargs)
当然,您可以决定自己再次覆盖 get_context_data
并使用其他名称传递表单,但这样做不是很有用:
class YourView(CreateView):
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['my_form'] = context['form']
return context