如何在Django模型中保存外键文本输入

时间:2016-10-09 10:00:22

标签: django django-forms django-views

我的观点将ID传递给我的表单。此id是另一个表中的外键。我无法将id保存在数据库表中。 (id:voucher_id,我保存表单的表:TmpPlInvoicedet)

我想做什么

从(查看)发送voucher_id到---> TmpFormDetForm(表格)---> TmpPlInvoicedet(DB)

尝试从表'TmpPlInvoice'中获取实例(其中voucher_id为PK)并将其保存在表单中给我

/ new / TmpPlInvoice匹配查询中的DoesNotExist不存在

我做错了什么?

Views.py

def new_invoic(request):

    # Create a voucher id according to my criteria
    temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct()
    if not temp_vid:
          voucher_id = str(1).zfill(4)
    else:
          voucher_id = str(int(max(temp_vid)) + 1).zfill(4)

    # POST METHOD TRying to show the voucher_id in the form in readonly format
    if request.method == 'POST':
          form_pk = TmpForm(request.POST or None, voucher_id=voucher_id,initial={'voucher_id': voucher_id})

          if form.is_valid():
               form_pk.save()
               form = TmpFormDetForm(request.POST or None, voucher=voucher_id, initial={'voucher': voucher_id})
               # My assumption is that since i have save the voucher_id in the TmpInvoice table so i can get the PK voucher_id value and save it in the TmpInvoiceDetForm
               form.save()
               return HttpResponseRedirect('/new/')
          else:
               return render_to_response('test.html',{'form': form, 'form_pk': form_pk},context_instance=RequestContext(request))
    else:
          form_pk = TmpForm(voucher_id=voucher_id,initial={'voucher_id': voucher_id})
          form = TmpFormDetForm(voucher=voucher_id, initial={'voucher': voucher_id})
          return render_to_response('test.html',{'form': form, 'form_pk': form_pk},context_instance=RequestContext(request))

Forms.py

# This form contains the FK. This one is giving errors while saving.

class TmpFormDetForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
         voucher = kwargs.pop('voucher', None)
         super(TmpFormDetForm, self).__init__(*args, **kwargs)
         self.fields['voucher'].initial = TmpPlInvoice.objects.get(voucher_id=voucher)

    voucher = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))

    class Meta:
          model = TmpPlInvoicedet
          exclude = ['emp_id','particulars','qty', 'rate' , 'itemtot', 'stock_code' ]
          widgets = {
              'voucher': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'required': 'False', 'name': 'voucher','readonly': 'readonly'}),
               'lineitem': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Total', 'required': 'False',  'blank': 'True'})}

# This form takes the PK. I save the PK here first.
class TmpForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
         voucher_id = kwargs.pop('voucher_id', None)
         super(TmpFor, self).__init__(*args, **kwargs)
         self.fields['voucher_id'].initial = voucher_id

    pos_code = MyModelChoiceField(queryset=Positions.objects.all(), widget=forms.Select(attrs={'class': 'select2_single form-control', 'blank': 'True'}))
    cust = MyModelChoiceField(queryset=Custodian.objects.all(), to_field_name='acct_id',widget=forms.Select(attrs={'class': 'select2_single form-control', 'blank': 'True'}))
    acct = MyModelChoiceField(queryset=Item.objects.all(), to_field_name='stock_code',widget=forms.Select(attrs={'class':'select2_single form-control', 'blank': 'True'}))

    voucher_date = forms.DateField(widget=forms.TextInput(attrs={'tabindex': '-1', 'class': 'form-control has-feedback-left', 'id': 'single_cal1','aria-describedby': 'inputSuccess2Status'}))

class Meta:
    model = TmpPlInvoice
    exclude = ['net_amt', 'post_date', 'address', 'posted']
    widgets = {
                'voucher_id': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'required':'False', 'name': 'voucher_id', 'readonly': 'readonly'}),
                'voucher_date': forms.TextInput(attrs={'tabindex': '-1', 'class': 'form-control has-feedback-left', 'id': 'single_cal1','aria-describedby': 'inputSuccess2Status'}),
                'particulars': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Particulars', 'required':'False'}),
            }

Models.py

class TmpPlInvoicedet(models.Model):
     stock_code = models.CharField(max_length=13, blank=True, null=True)
     voucher = models.ForeignKey(TmpPlInvoice, db_column='voucher_id')
     lineitem = models.CharField(max_length=6)
     particulars = models.CharField(max_length=200, blank=True, null=True)
     qty = models.FloatField(blank=True, null=True)
     rate = models.FloatField(blank=True, null=True)
     itemtot = models.FloatField(blank=True, null=True)
     emp_id = models.CharField(max_length=8, blank=True, null=True)

class Meta:
     managed = False
     db_table = 'tmp_pl_invoicedet'
     unique_together = (('voucher', 'lineitem'),)

2 个答案:

答案 0 :(得分:0)

您似乎在创建新的发票ID,然后在表单中尝试获取与该ID匹配的发票。但是,该发票尚未存在,当然,因为您还没有创建它。

您可能希望使用get_or_create确保在不存在发票的情况下创建发票。

答案 1 :(得分:0)

容易撒尿。

def master_detail(request):
    def get_new_voucher_id():
       temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct()
       logger.info('Voucher ID already present %s', temp_vid)
       if not temp_vid:
           voucher_id = str(1).zfill(4)
       else:
           voucher_id = str(int(max(temp_vid)) + 1).zfill(4)
       return voucher_id

  voucher_id = get_new_voucher_id()
  author_form = TmpForm(initial={'voucher_id': voucher_id})
  author = TmpPlInvoice()
  BookFormSet = inlineformset_factory(TmpPlInvoice, TmpPlInvoicedet, exclude=('emp_id', 'itemtot', 'voucher', 'lineitem','id'),
                                    form=TmpFormDetForm, extra=1)
  formset = BookFormSet(instance=author)

  if request.method == 'POST':
       logger.info('*'*50)
       author = TmpForm(request.POST, initial={'voucher_id': voucher_id})
       if author.is_valid():
           logger.info('Data for Author is %s', author.cleaned_data)
           created_author = author.save()
           formset = BookFormSet(request.POST, instance=created_author)

           if formset.is_valid():
               logger.info('Data for Book is %s', formset.cleaned_data)
               formset.save()
           else:
                logger.info('Formset errors %s', formset.errors)
       else:
           logger.info('Master form  errors %s', author.errors)
           logger.info('*'*50)
       return HttpResponseRedirect('/new/')
  else:
       logger.info('Formset from GET is %s', formset.errors)
       return render_to_response('new_invoice.html',
                              {'form': author_form, 'formset': formset},context_instance=RequestContext(request))