我是Django的新手。我尝试构建基于类的视图以创建对象。
模板中表单的默认名称是form,我想将其更改为"ajoutersource"
,但我无法弄清楚如何。
views.朋友
class ajoutSource(CreateView):
model = Source
template_name = "pmd/ajouterSource.html"
form_class = AjouterSourceForm
success_url = reverse_lazy(ListerSources)
ajouterSource.html
{% for field in ajoutersource %}
<div class="row">
{% if field.errors %}
<div class="error">{{ field.errors }}</div>
{% endif %}
<div class="label">{{ field.label }}</div>
<div class="field">{{ field }}</div>
</div>
{% endfor %}
class ajoutSource(CreateView):
model = Source
template_name = "pmd/ajouterSource.html"
form_class = AjouterSourceForm
success_url = reverse_lazy(ListerSources)
def get_context_data(self, **kwargs):
context = super(ajoutSource, self).get_context_data(**kwargs)
context["ajoutersource"]=context["form"]
return context
你可以通过以下方法完成
方法1(型号表格)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['new_name'] = self.get_form()
return context
方法2(简单表格)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['new_name'] = context["form"]
return context
建议使用方法1(注意:这是python 3.6+语法,对python 2.0+更改super()调用)