django:在一个模板中使用两个模型和两个表单时,数据不保存在db中

时间:2013-04-02 22:47:35

标签: django django-models django-forms django-admin django-views

我很难将表单保存到db中。每次我点击保存它都没有保存在db / admin中。似乎无法弄明白。我希望那里的人可以帮助我。

该项目是关于为建筑公司收集新客户的信息,如果客户存在于数据库中,那么它将查看特定客户的详细信息,并能够在需要时编辑特定客户并能够覆盖保存时的数据。此信息从客户模型和建筑模型以及customerForm和buildingForm中收集并显示在客户模板中。

models.py

class customer(models.Model)
    F_NAME  = models.CharField(max_length = 50) 
    L_NAME  = models.CharField(max_length = 50)
    ADD     = models.CharField(max_length = 60, blank =True)
    EMAIL   = models.EmailField()
    def __unicode__(self):
        return '%s' % ( self.F_NAME )

class building(models.Model):
    CUSTOMER      = models.ForeignKey(customer)
    B_USE         = models.CharField(max_length = 2, blank = True, choices = c.Use)
    B_FLOORSPACE  = models.IntegerField(default=0)
    B_YEAR        = models.IntegerField(null = True, blank = True)
    B_TYPE        = models.CharField(max_length = 2, blank = True, choices = c.Type)
    def __unicode__(self):
        return '%s' % (self.B_USE)

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
        exclude = ('CUSTOMER',)
        widgets = {'B_USE'       : RadioSelectNotNull(),
                   'B_TYPE'      : RadioSelectNotNull(),
                  }

views.py

def customerView(request ,**kwargs ):
    context ={}
    try:
        this_customer = customer.objects.get(id = kwargs ['pk'])
    except:
        this_customer = customer.objects.create(id = kwargs['pk'])
    try: 
        bform = buildingForm(instance=building())
        context['build']=True
        context['bform']=bform
    except: 
        context['build']=False
    form = customerForm(instance=this_customer)
    context['form']= form

    if request.method == 'POST':
        form = customerForm(request.POST, instance = customer())
        bform = [buildingForm(request.POST, prefix = str(x), instance = building()) for x in range (0,3)]
        if form.is_valid() and all ([bf.is_valid() for bf in bform]):
            new_customer = form.save()
            for bf in bform:
                new_build = bf.save(commit = False)
                new_build.CUSTOMER = new_customer
                new_build.save()
            return HttpResponseRedirect('customer.html')
    else:
        form = customerForm(instance=customer())
        bform = [buildingForm(prefix=str(x), instance=building())for x in range(0,3)]

    return render_to_response('customer.html',{'customer_form':form, 'build_form':bform}, context_instance = RequestContext(request))

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

{% if build %}

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

我在单个表单中尝试了多个模型条目的演示     http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ 和     Django: multiple models in one template using forms 和     How to use two different Django Form at the same template? 但无法看出错误在哪里。我的任务现在非常简单,我只需要保存所有已输入并保存在数据库中的信息。

1 个答案:

答案 0 :(得分:0)

您可能在某处遇到验证错误。由于您没有在模板中显示任何表单错误,因此您的表单将被重新显示而无需解释。