django:两个表单,但只有一个表单正在保存

时间:2013-04-23 15:02:59

标签: django django-forms django-views

任何人都可以帮助我。此代码有什么问题,因为只保存了一个表单,即表单,但不保存bform。我哪里出错?

views.py

def customerView(request, **kwargs):
    this_customer = customer.objects.get(id=kwargs['pk'])
    if request.method == 'POST':
        form = customerForm(request.POST, instance=this_customer)
        bform = buildingForm(request.POST)
        if form.is_valid() and bform.is_valid():
            form.save()
            bform.save()
    else:
        form = customerForm(instance=this_customer)
        bform = buildingForm()
    return render_to_response('customer.html',{'form':form, 'bform':bform,},
                                context_instance = RequestContext(request))

forms.py

class customerForm(ModelForm):
    F_NAME = forms.CharField(widget=forms.TextInput(attrs={'size':'34'}))
    L_NAME = forms.CharField(widget=forms.TextInput(attrs={'size':'34'}))  
    EMAIL  = forms.CharField(widget=forms.TextInput(attrs={'size':'19'}))  
    ADD    = forms.CharField(widget=forms.TextInput(attrs={'size':'34'}))
    class Meta:
        model = customer

class buildingForm(ModelForm):
    CUSTOMER     = forms.CharField(widget=forms.TextInput(attrs={'size':'20'}))
    B_FLOORSPACE = forms.CharField(widget=forms.TextInput(attrs={'size':'4'}))
    B_YEAR       = forms.CharField(widget=forms.TextInput(attrs={'size':'4'})) 
    class Meta:
        model = building
        widgets = {'B_USE'       : RadioSelectNotNull(),
                   'B_TYPE'      : RadioSelectNotNull(),
                  }

已编辑添加template-customer.html

<form action="" method="post">
<button type="submit" name="customer">Save</button>  
  {% csrf_token %}
    {{ form.id }} 

 ...more code...
<table> 
  <tr><td><div>First Name</div>{{ form.F_NAME }}</td></tr>     
  <tr><td><div>Last Name</div>{{ form.L_NAME }}</td></tr>
</table>

   ...more code....
<table> 
  <tr><td><div>Build Use</div></td><td>{{ bform.B_USE }}</td>
      <td><div>Build Space</div></td><td>{{ bform.B_FLOORSPACE }}</td>
      </tr>

 ...more code... 
</form>   

没有错误说编码中存在错误。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:-1)

我假设您在模板中的单独表单元素中显示了两个表单。这种方法的问题在于,您实际上一次只能提交一个表单。幸运的是,Django提供了Formsets作为解决方案。

相应的文档:https://docs.djangoproject.com/en/dev/topics/forms/formsets/