1

谁能帮我这个。这段代码有什么问题,因为只保存了一个表单,即form,但没有保存bform。我哪里做错了??

视图.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))

表格.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>   

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

4

1 回答 1

-1

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

适当的文档:https ://docs.djangoproject.com/en/dev/topics/forms/formsets/

于 2013-04-23T15:12:09.907 回答