如何使用基于类的视图在同一模板中使用两个不同的 Django 表单
Posted
技术标签:
【中文标题】如何使用基于类的视图在同一模板中使用两个不同的 Django 表单【英文标题】:How to use two different Django Form at the same template using class based view 【发布时间】:2016-03-14 14:57:14 【问题描述】:我正在使用基于 django 类的视图来创建两种表单(线程、消息)。
views.py
class ThreadForm(FormView):
template_name = 'thread.html'
form_class = ThreadModelForm
success_url = '/success'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
return super(ThreadForm, self).form_valid(form)
class MessageForm(FormView):
template_name = 'thread.html'
form_class = MessageModelForm
success_url = '/success'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
return super(MessageForm, self).form_valid(form)
两者都是渲染同一个html文件thread.html
。谁能告诉我如何在同一个模板中呈现两个表单?
thread.html
form.as_p
更新:我正在使用下面的视图,但它不起作用:
class MessageForm(FormView):
template_name = 'thread.html'
success_url = '/success'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
return super(MessageForm, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(MessageForm, self).get_context_data(**kwargs)
context['second_form'] = MessageModelForm
return context
【问题讨论】:
您可以从下面的链接Same problem You have but he has done in a different way获得帮助 【参考方案1】:为此使用get_context_data
方法。
def get_context_data(self, **kwargs):
context = super(FormViewName, self).get_context_data(**kwargs)
context['second_form'] = SecondForm
return context
然后在你的模板中你可以使用
second_form.as_p
此外,在您的 form_valid 方法中,您还必须检查 second_form 的有效性。
【讨论】:
嘿,它正在工作!urls.py
文件的一些问题 :) 我不需要两个类。
你能告诉我如何在这里验证second_form
吗?我正在使用模板中的单个提交按钮,它只向我传递第一个表单数据。【参考方案2】:
我是这样做的……
class SolicitudUpdate(UpdateView):
model = Solicitud
second_model = Persona
template_name = 'adopcion/solicitud_form.html'
form_class = SolicitudForm
second_form_class = PersonaForm
success_url = reverse_lazy('adopcion:solicitud_listar')
def get_context_data(self, **kwargs):
context = super(SolicitudUpdate, self).get_context_data(**kwargs)
pk = self.kwargs.get('pk', 0)
solicitud = self.model.objects.get(id=pk)
persona = self.second_model.objects.get(id=solicitud.persona_id)
if 'form' not in context:
context['form'] = self.form_class()
if 'form2' not in context:
context['form2'] = self.second_form_class(instance=persona)
context['id'] = pk
return context
【讨论】:
以上是关于如何使用基于类的视图在同一模板中使用两个不同的 Django 表单的主要内容,如果未能解决你的问题,请参考以下文章