我使用TemplateView编写了一个CBV,将两个表单放在模板上。但是只有提交按钮显示减去字段。
multiple_form.html
<form action="" method="post">
{% csrf_token %}
{{ context.form1.as_p }}
<input type="submit">
</form>
<form action="" method="post">
{% csrf_token %}
{{ context.form2.as_p }}
<input type="submit">
</form>
forms.py
from django import forms
from django.forms import ModelForm
class Form1(forms.ModelForm):
username = forms.CharField(label=(u'User Name1'))
email = forms.EmailField(label=(u'Email Address1'))
class Form2(forms.ModelForm):
username = forms.CharField(label=(u'User Name2'))
email = forms.EmailField(label=(u'Email Address2'))
views.py
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView
from article.forms import Form1, Form2
class MultipleFormView(TemplateView):
template_name = 'blog/multiple_form.html'
def get_context_data(self, **kwargs):
context = super(MultipleFormView, self).get_context_data(**kwargs)
context['form1'] = Form1
context['form2'] = Form2
return context
success_url = '/'
答案 0 :(得分:1)
尝试删除多余的&#39;上下文&#39;在您的HTML中,{{context.form1}}会错误地链接到不存在的context['context']['form1']
。
<form action="" method="post">
{% csrf_token %}
{{ form1.as_p }}
<input type="submit">
</form>
<form action="" method="post">
{% csrf_token %}
{{ form2.as_p }}
<input type="submit">
</form>
答案 1 :(得分:0)
删除模板中无用的context
,只需form1.as_p
即可。
<form action="" method="post">
{% csrf_token %}
{{ form1.as_p }}
<input type="submit">
</form>
<form action="" method="post">
{% csrf_token %}
{{ form2.as_p }}
<input type="submit">
</form>
您需要实例化表单对象,而不是在您的上下文中传递该类。在这里,你传递的是一个类,Django将无法使用它。
class MultipleFormView(TemplateView):
template_name = 'blog/multiple_form.html'
def get_context_data(self, **kwargs):
context = super(MultipleFormView, self).get_context_data(**kwargs)
context['form1'] = Form1() # <----
context['form2'] = Form2() # note the parenthesis here
return context
success_url = '/'