如何在一个视图中保存多个具有多个实例的表单?

时间:2016-04-15 08:23:35

标签: python django django-forms

Models.py:

class BT(models.Model):
  """docstring for BT"""
  batch_number = models.CharField(_("Batch Number"), blank = False, null = False, max_length = 50)
  dp = models.ForeignKey('DP', blank = False, null = False, related_name='b_t')
  dispatch_date = models.DateTimeField(auto_now_add = False, auto_now = False, blank = False, null = False)
  estimated_arrival_date = models.DateTimeField(auto_now_add = False, auto_now = False, blank = False, null = False)
  dispatch_location = models.CharField( max_length=50, blank = False, null = False )
  arrival_location = models.CharField( max_length=50, blank = False, null = False )

  class Meta:
    unique_together = ("batch_number", "dp")

  def __unicode__(self):
    return '%s - %s' %(self.batch_number, self.dp.b_id)


class BD(models.Model):
  b_t = models.ForeignKey(BT, related_name='b_ds')
  b_d = models.CharField(max_length= 250, blank = True, null = False)

  class Meta:
    unique_together = ("b_t", "b_d")

  def __unicode__(self):
    return '%s' %(self.b_d)

class SD(models.Model):
  b_t = models.ForeignKey(BT, related_name='s_ds')
  s_d = models.CharField(max_length= 250, blank = True, null = False)

  class Meta:
    unique_together = ("b_t", "s_d")

  def __unicode__(self):
    return '%s' %(self.s_d)

class DD(models.Model):
  b_t = models.ForeignKey(BT, related_name='d_ds')
  d_d = models.CharField(max_length= 250, blank = True, null = False)

  class Meta:
    unique_together = ("b_t", "d_d")

  def __unicode__(self):
    return '%s' %(self.d_d)

class CD(models.Model):
  b_t = models.ForeignKey(BT, related_name='c_ds')
  c_d = models.CharField(max_length= 250, blank = True, null = False)

  class Meta:
    unique_together = ("b_t", "c_d")

  def __unicode__(self):
    return '%s' %(self.c_d)

class TD(models.Model):
  b_t = models.ForeignKey(BT, related_name='t_ds')
  t_d = models.CharField(max_length= 250, blank = True, null = False)

  class Meta:
    unique_together = ("b_t", "t_d")

  def __unicode__(self):
    return '%s' %(self.t_d)

class PL(models.Model):
  b_t = models.ForeignKey(BT, related_name='p_l')
  p_l_remark = models.CharField(max_length= 250, blank = True, null = False)
  p_l_attachment = models.FileField(upload_to = settings.PATH_TO_UPLOAD_P_L_FILE, max_length = 200, blank = True, null = True)


  class Meta:
    unique_together = ("b_t", "p_l_remark","p_l_attachment")

  def __unicode__(self):
    return '%s' %(self.p_l_remark)

class DL(models.Model):
  b_t = models.ForeignKey(BT, related_name='d_l')
  d_r = models.CharField(max_length= 250, blank = True, null = False)
  d_a = models.FileField(upload_to = settings.PATH_TO_UPLOAD_FILE, max_length = 200, blank = True, null = True)

  class Meta:
    unique_together = ("b_t", "d_r","d_a")

  def __unicode__(self):
    return '%s' %(self.d_r)

Forms.py:

class BDForm(ModelForm):
  """docstring for BDForm"""
  class Meta:
    model = BD
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    super(BDForm, self).__init__(*args, **kwargs)
    self.fields['b_d'].widget.attrs['class'] = 'form-control b_d'


class SDForm(ModelForm):
  """docstring for SDForm"""
  class Meta:
    model = SD
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    super(SDForm, self).__init__(*args, **kwargs)
    self.fields['s_d'].widget.attrs['class'] = 'form-control s_d'



class DDForm(ModelForm):
  """docstring for DDForm"""
  class Meta:
    model = DD
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    super(DDForm, self).__init__(*args, **kwargs)
    self.fields['d_d'].widget.attrs['class'] = 'form-control d_d'


class CDForm(ModelForm):
  """docstring for CDForm"""
  class Meta:
    model = CD
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    super(CDForm, self).__init__(*args, **kwargs)
    self.fields['c_d'].widget.attrs['class'] = 'form-control c_d'

class TDForm(ModelForm):
  """docstring for TDForm"""
  class Meta:
    model = TD
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    super(TDForm, self).__init__(*args, **kwargs)
    self.fields['t_d'].widget.attrs['class'] = 'form-control t_d'


class PLForm(ModelForm):
  """docstring for PLForm"""
  class Meta:
    model = PL
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    super(PLForm, self).__init__(*args, **kwargs)
    self.fields['p_l_remark'].widget.attrs['class'] = 'attachment_remark'
    self.fields['p_l_attachment'].widget.attrs['required'] = ''        



class DLForm(ModelForm):
  """docstring for DLForm"""
  class Meta:
    model = DL
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    super(DLForm, self).__init__(*args, **kwargs)
    self.fields['d_r'].widget.attrs['class'] = 'attachment_remark'
    self.fields['d_a'].widget.attrs['required'] = ''    

class BTForm(ModelForm):
  """docstring for BTForm"""
  class Meta:
    model = BT
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    super(BTForm, self).__init__(*args, **kwargs)
    for each_field in self.fields:
      self.fields[each_field].widget.attrs['class'] = 'form-control'
      self.fields[each_field].widget.attrs['required'] = ''
    self.fields['dispatch_date'].widget.attrs['class'] = 'form-control datepick'
    self.fields['estimated_arrival_date'].widget.attrs['class'] = 'form-control datepick'

Views.py:

from django.apps import apps
@csrf_exempt
def transfer_form(request):
  data = {}
  system_user, system_owner = get_system_user_owner(request.user)
  data['dps_list'] = get_loggedin_user_related_office_dp(system_user)

  b_t_form = BTForm()
  p_l_form = PLForm()
  d_l_form = DLForm()
  b_d_form = BDForm()
  s_d_form = SDForm()
  d_d_form = DDForm()
  c_d_form = CDForm()
  t_d_form = TDForm()

  if (request.method == 'POST'):

    b_t_form = BTForm(request.POST)
    p_l_form = PLForm(request.POST, request.FILES)
    d_l_form = DLForm(request.POST, request.FILES)
    b_d_form = BDForm(request.POST)
    s_d_form = SDForm(request.POST)
    d_d_form = DDForm(request.POST)
    c_d_form = CDForm(request.POST)
    t_d_form = TDForm(request.POST)

    if all([b_t_form.is_valid(), p_l_form.is_valid(), d_l_form.is_valid(), \
      b_d_form.is_valid(), s_d_form.is_valid(), d_d_form.is_valid(), \
      c_d_form.is_valid(), t_d_form.is_valid()]):

      b_t = b_t_form.save()
      b_t_obj = BT(id = b_t.pk)
      relations = {'b_d' : 'dp.BD', 's_d' : 'dp.SD', \
      'd_d' : 'dp.DD', 'c_d' : 'dp.CD', \
      't_d' : 'dp.TD', 'p_l_remark' : 'dp.PL', 'p_l_attachment' : 'dp.PL', \
      'd_r' : 'dp.DL', 'd_a' : 'dp.DL'}
      for each_key in relations:

        if each_key == 'p_l_attachment':
          post_data = request.FILES['p_l_attachment']
          each_obj = PL.objects.filter(b_t = b_t_obj)
          each_obj.p_l_attachment = post_data
          each_obj.save()     

        elif each_key == 'd_a':
          post_data = request.FILES['d_a']
          each_obj = DL.objects.filter(b_t = b_t_obj)
          each_obj.d_a = post_data
          each_obj.save()     

        else:
          post_data = request.POST.getlist(each_key)
          for each_rec in post_data:
            obj_data = {each_key : each_rec, 'b_t' : b_t_obj}
            model = apps.get_model( relations[each_key] )
            each_obj = model( **obj_data )
            each_obj.save()     

      if 'add_another_form' in request.POST: 
        p_l_obj = PL(b_t= b_t)
        d_l_obj = DL(b_t = b_t)
        data['b_t_form'] = BTForm(instance = b_t_obj)
        data['p_l_form'] = PLForm(instance = p_l_obj)
        data['d_l_form'] = DLForm(instance = d_l_obj)
        data['b_d_form'] = BDForm()
        data['s_d_form'] = SDForm()
        data['d_d_form'] = DDForm()
        data['c_d_form'] = CDForm()
        data['t_d_form'] = TDForm()

      data['notification'] = 'Transfer information has been updated successfully!'
    else:
      data['notification'] = 'An error Occurred!'
      err_keys = b_t_form.errors.keys()
      if len(err_keys):
        data['notification'] = err_keys

  if 'add_another_form' in request.POST:
    return render_to_response('b_t/transfer_form.html', data, context_instance=RequestContext(request))
  else:
    data['b_t_form'] = BTForm()
    data['b_d_form'] = BDForm()
    data['s_d_form'] = SDForm()
    data['d_d_form'] = DDForm()
    data['c_d_form'] = CDForm()
    data['t_d_form'] = TDForm()
    data['p_l_form'] = PLForm()
    data['d_l_form'] = DLForm()

    return render_to_response('b_t/transfer_form.html', data, context_instance=RequestContext(request))

此代码应允许用户添加除BT以外的所有模型的多个实例,BT为每个其他模型的ForeignKey

我尝试了Formset方法并尝试了here给出的方法。我正在使用Djnago 1.9python 2.7进行开发。

0 个答案:

没有答案