2016-10-09 21 views
0

我的觀點將ID傳遞給我的表單。此ID是另一個表中的外鍵。我無法將ID保存在數據庫表中。 (ID:voucher_id,表,其中我現在的儲蓄形式:TmpPlInvoicedet)如何在Django模型表單中保存外鍵文本輸入

我想從(查看)做

發送voucher_id到---> TmpFormDetForm(表格) - - > TmpPlInvoicedet(DB)

試圖讓實例從表 'TmpPlInvoice'(已voucher_id作爲PK),並將其保存在形式給我的/新/ TmpPlInvoice馬

DoesNotExist tching查詢不存在

我在做什麼錯?

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'),) 

回答

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)) 
0

你似乎是科瑞新的發票編號,然後在您的表單中嘗試獲取與該編號匹配的發票。但那張發票當然不存在,因爲你還沒有創建它。

您可能想要使用get_or_create確保發票是在不存在的情況下創建的。

+0

偉大的觀察!在同一視圖中,我將ID傳遞給另一個表單並將ID保存到表'TmpPlInvoice'中。我沒有添加它以避免過於複雜。代表我的愚蠢。讓我編輯這個。 –