我是Django的新人。我尝试构建一个基于类的视图,以便创建一个对象。
模板中表单的默认名称是表单,我想将其更改为"ajoutersource"
,但我无法确定如何。
views.py
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 %}
答案 0 :(得分:1)
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 :(得分:0)
您可以通过以下方法轻松完成
方法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()调用)
答案 2 :(得分:0)
覆盖 get_context_data
,context['form']
取自 SomeForm
,并更改为 form_1
,您可以在模板中用作 form_1
class Something(generic.CreateView):
template_name = 'app/example.html'
form_class = forms.SomeForm
model = models.SomeModel
def get_context_data(self, **kwargs):
context = super(Something, self).get_context_data(**kwargs)
context["form_1"] = context["form"]
context["form_2"] = forms.SomeForm2(**self.get_form_kwargs())
return context